1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include <algorithm>
37 #include <cstdlib>
38 
39 using namespace clang;
40 using namespace sema;
41 
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44     return P->hasAttr<PassObjectSizeAttr>();
45   });
46 }
47 
48 /// A convenience routine for creating a decayed reference to a function.
49 static ExprResult
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51                       const Expr *Base, bool HadMultipleCandidates,
52                       SourceLocation Loc = SourceLocation(),
53                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55     return ExprError();
56   // If FoundDecl is different from Fn (such as if one is a template
57   // and the other a specialization), make sure DiagnoseUseOfDecl is
58   // called on both.
59   // FIXME: This would be more comprehensively addressed by modifying
60   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61   // being used.
62   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63     return ExprError();
64   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65     S.ResolveExceptionSpec(Loc, FPT);
66   DeclRefExpr *DRE = new (S.Context)
67       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70 
71   S.MarkDeclRefReferenced(DRE, Base);
72   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73                              CK_FunctionToPointerDecay);
74 }
75 
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77                                  bool InOverloadResolution,
78                                  StandardConversionSequence &SCS,
79                                  bool CStyle,
80                                  bool AllowObjCWritebackConversion);
81 
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83                                                  QualType &ToType,
84                                                  bool InOverloadResolution,
85                                                  StandardConversionSequence &SCS,
86                                                  bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89                         UserDefinedConversionSequence& User,
90                         OverloadCandidateSet& Conversions,
91                         bool AllowExplicit,
92                         bool AllowObjCConversionOnExplicit);
93 
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97                                    const StandardConversionSequence& SCS1,
98                                    const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109 
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113   static const ImplicitConversionRank
114     Rank[(int)ICK_Num_Conversion_Kinds] = {
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Promotion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_OCL_Scalar_Widening,
135     ICR_Complex_Real_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Writeback_Conversion,
139     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140                      // it was omitted by the patch that added
141                      // ICK_Zero_Event_Conversion
142     ICR_C_Conversion,
143     ICR_C_Conversion_Extension
144   };
145   return Rank[(int)Kind];
146 }
147 
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152     "No conversion",
153     "Lvalue-to-rvalue",
154     "Array-to-pointer",
155     "Function-to-pointer",
156     "Function pointer conversion",
157     "Qualification",
158     "Integral promotion",
159     "Floating point promotion",
160     "Complex promotion",
161     "Integral conversion",
162     "Floating conversion",
163     "Complex conversion",
164     "Floating-integral conversion",
165     "Pointer conversion",
166     "Pointer-to-member conversion",
167     "Boolean conversion",
168     "Compatible-types conversion",
169     "Derived-to-base conversion",
170     "Vector conversion",
171     "Vector splat",
172     "Complex-real conversion",
173     "Block Pointer conversion",
174     "Transparent Union Conversion",
175     "Writeback conversion",
176     "OpenCL Zero Event Conversion",
177     "C specific type conversion",
178     "Incompatible pointer conversion"
179   };
180   return Name[Kind];
181 }
182 
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186   First = ICK_Identity;
187   Second = ICK_Identity;
188   Third = ICK_Identity;
189   DeprecatedStringLiteralToCharPtr = false;
190   QualificationIncludesObjCLifetime = false;
191   ReferenceBinding = false;
192   DirectBinding = false;
193   IsLvalueReference = true;
194   BindsToFunctionLvalue = false;
195   BindsToRvalue = false;
196   BindsImplicitObjectArgumentWithoutRefQualifier = false;
197   ObjCLifetimeConversionBinding = false;
198   CopyConstructor = nullptr;
199 }
200 
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205   ImplicitConversionRank Rank = ICR_Exact_Match;
206   if  (GetConversionRank(First) > Rank)
207     Rank = GetConversionRank(First);
208   if  (GetConversionRank(Second) > Rank)
209     Rank = GetConversionRank(Second);
210   if  (GetConversionRank(Third) > Rank)
211     Rank = GetConversionRank(Third);
212   return Rank;
213 }
214 
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220   // Note that FromType has not necessarily been transformed by the
221   // array-to-pointer or function-to-pointer implicit conversions, so
222   // check for their presence as well as checking whether FromType is
223   // a pointer.
224   if (getToType(1)->isBooleanType() &&
225       (getFromType()->isPointerType() ||
226        getFromType()->isMemberPointerType() ||
227        getFromType()->isObjCObjectPointerType() ||
228        getFromType()->isBlockPointerType() ||
229        getFromType()->isNullPtrType() ||
230        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231     return true;
232 
233   return false;
234 }
235 
236 /// isPointerConversionToVoidPointer - Determines whether this
237 /// conversion is a conversion of a pointer to a void pointer. This is
238 /// used as part of the ranking of standard conversion sequences (C++
239 /// 13.3.3.2p4).
240 bool
241 StandardConversionSequence::
242 isPointerConversionToVoidPointer(ASTContext& Context) const {
243   QualType FromType = getFromType();
244   QualType ToType = getToType(1);
245 
246   // Note that FromType has not necessarily been transformed by the
247   // array-to-pointer implicit conversion, so check for its presence
248   // and redo the conversion to get a pointer.
249   if (First == ICK_Array_To_Pointer)
250     FromType = Context.getArrayDecayedType(FromType);
251 
252   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
253     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
254       return ToPtrType->getPointeeType()->isVoidType();
255 
256   return false;
257 }
258 
259 /// Skip any implicit casts which could be either part of a narrowing conversion
260 /// or after one in an implicit conversion.
261 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263     switch (ICE->getCastKind()) {
264     case CK_NoOp:
265     case CK_IntegralCast:
266     case CK_IntegralToBoolean:
267     case CK_IntegralToFloating:
268     case CK_BooleanToSignedIntegral:
269     case CK_FloatingToIntegral:
270     case CK_FloatingToBoolean:
271     case CK_FloatingCast:
272       Converted = ICE->getSubExpr();
273       continue;
274 
275     default:
276       return Converted;
277     }
278   }
279 
280   return Converted;
281 }
282 
283 /// Check if this standard conversion sequence represents a narrowing
284 /// conversion, according to C++11 [dcl.init.list]p7.
285 ///
286 /// \param Ctx  The AST context.
287 /// \param Converted  The result of applying this standard conversion sequence.
288 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
289 ///        value of the expression prior to the narrowing conversion.
290 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
291 ///        type of the expression prior to the narrowing conversion.
292 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293 ///        from floating point types to integral types should be ignored.
294 NarrowingKind StandardConversionSequence::getNarrowingKind(
295     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
297   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
298 
299   // C++11 [dcl.init.list]p7:
300   //   A narrowing conversion is an implicit conversion ...
301   QualType FromType = getToType(0);
302   QualType ToType = getToType(1);
303 
304   // A conversion to an enumeration type is narrowing if the conversion to
305   // the underlying type is narrowing. This only arises for expressions of
306   // the form 'Enum{init}'.
307   if (auto *ET = ToType->getAs<EnumType>())
308     ToType = ET->getDecl()->getIntegerType();
309 
310   switch (Second) {
311   // 'bool' is an integral type; dispatch to the right place to handle it.
312   case ICK_Boolean_Conversion:
313     if (FromType->isRealFloatingType())
314       goto FloatingIntegralConversion;
315     if (FromType->isIntegralOrUnscopedEnumerationType())
316       goto IntegralConversion;
317     // Boolean conversions can be from pointers and pointers to members
318     // [conv.bool], and those aren't considered narrowing conversions.
319     return NK_Not_Narrowing;
320 
321   // -- from a floating-point type to an integer type, or
322   //
323   // -- from an integer type or unscoped enumeration type to a floating-point
324   //    type, except where the source is a constant expression and the actual
325   //    value after conversion will fit into the target type and will produce
326   //    the original value when converted back to the original type, or
327   case ICK_Floating_Integral:
328   FloatingIntegralConversion:
329     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330       return NK_Type_Narrowing;
331     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
332                ToType->isRealFloatingType()) {
333       if (IgnoreFloatToIntegralConversion)
334         return NK_Not_Narrowing;
335       llvm::APSInt IntConstantValue;
336       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
337       assert(Initializer && "Unknown conversion expression");
338 
339       // If it's value-dependent, we can't tell whether it's narrowing.
340       if (Initializer->isValueDependent())
341         return NK_Dependent_Narrowing;
342 
343       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
344         // Convert the integer to the floating type.
345         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
346         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
347                                 llvm::APFloat::rmNearestTiesToEven);
348         // And back.
349         llvm::APSInt ConvertedValue = IntConstantValue;
350         bool ignored;
351         Result.convertToInteger(ConvertedValue,
352                                 llvm::APFloat::rmTowardZero, &ignored);
353         // If the resulting value is different, this was a narrowing conversion.
354         if (IntConstantValue != ConvertedValue) {
355           ConstantValue = APValue(IntConstantValue);
356           ConstantType = Initializer->getType();
357           return NK_Constant_Narrowing;
358         }
359       } else {
360         // Variables are always narrowings.
361         return NK_Variable_Narrowing;
362       }
363     }
364     return NK_Not_Narrowing;
365 
366   // -- from long double to double or float, or from double to float, except
367   //    where the source is a constant expression and the actual value after
368   //    conversion is within the range of values that can be represented (even
369   //    if it cannot be represented exactly), or
370   case ICK_Floating_Conversion:
371     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
372         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
373       // FromType is larger than ToType.
374       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
375 
376       // If it's value-dependent, we can't tell whether it's narrowing.
377       if (Initializer->isValueDependent())
378         return NK_Dependent_Narrowing;
379 
380       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
381         // Constant!
382         assert(ConstantValue.isFloat());
383         llvm::APFloat FloatVal = ConstantValue.getFloat();
384         // Convert the source value into the target type.
385         bool ignored;
386         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
387           Ctx.getFloatTypeSemantics(ToType),
388           llvm::APFloat::rmNearestTiesToEven, &ignored);
389         // If there was no overflow, the source value is within the range of
390         // values that can be represented.
391         if (ConvertStatus & llvm::APFloat::opOverflow) {
392           ConstantType = Initializer->getType();
393           return NK_Constant_Narrowing;
394         }
395       } else {
396         return NK_Variable_Narrowing;
397       }
398     }
399     return NK_Not_Narrowing;
400 
401   // -- from an integer type or unscoped enumeration type to an integer type
402   //    that cannot represent all the values of the original type, except where
403   //    the source is a constant expression and the actual value after
404   //    conversion will fit into the target type and will produce the original
405   //    value when converted back to the original type.
406   case ICK_Integral_Conversion:
407   IntegralConversion: {
408     assert(FromType->isIntegralOrUnscopedEnumerationType());
409     assert(ToType->isIntegralOrUnscopedEnumerationType());
410     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
411     const unsigned FromWidth = Ctx.getIntWidth(FromType);
412     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
413     const unsigned ToWidth = Ctx.getIntWidth(ToType);
414 
415     if (FromWidth > ToWidth ||
416         (FromWidth == ToWidth && FromSigned != ToSigned) ||
417         (FromSigned && !ToSigned)) {
418       // Not all values of FromType can be represented in ToType.
419       llvm::APSInt InitializerValue;
420       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
421 
422       // If it's value-dependent, we can't tell whether it's narrowing.
423       if (Initializer->isValueDependent())
424         return NK_Dependent_Narrowing;
425 
426       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
427         // Such conversions on variables are always narrowing.
428         return NK_Variable_Narrowing;
429       }
430       bool Narrowing = false;
431       if (FromWidth < ToWidth) {
432         // Negative -> unsigned is narrowing. Otherwise, more bits is never
433         // narrowing.
434         if (InitializerValue.isSigned() && InitializerValue.isNegative())
435           Narrowing = true;
436       } else {
437         // Add a bit to the InitializerValue so we don't have to worry about
438         // signed vs. unsigned comparisons.
439         InitializerValue = InitializerValue.extend(
440           InitializerValue.getBitWidth() + 1);
441         // Convert the initializer to and from the target width and signed-ness.
442         llvm::APSInt ConvertedValue = InitializerValue;
443         ConvertedValue = ConvertedValue.trunc(ToWidth);
444         ConvertedValue.setIsSigned(ToSigned);
445         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
446         ConvertedValue.setIsSigned(InitializerValue.isSigned());
447         // If the result is different, this was a narrowing conversion.
448         if (ConvertedValue != InitializerValue)
449           Narrowing = true;
450       }
451       if (Narrowing) {
452         ConstantType = Initializer->getType();
453         ConstantValue = APValue(InitializerValue);
454         return NK_Constant_Narrowing;
455       }
456     }
457     return NK_Not_Narrowing;
458   }
459 
460   default:
461     // Other kinds of conversions are not narrowings.
462     return NK_Not_Narrowing;
463   }
464 }
465 
466 /// dump - Print this standard conversion sequence to standard
467 /// error. Useful for debugging overloading issues.
468 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
469   raw_ostream &OS = llvm::errs();
470   bool PrintedSomething = false;
471   if (First != ICK_Identity) {
472     OS << GetImplicitConversionName(First);
473     PrintedSomething = true;
474   }
475 
476   if (Second != ICK_Identity) {
477     if (PrintedSomething) {
478       OS << " -> ";
479     }
480     OS << GetImplicitConversionName(Second);
481 
482     if (CopyConstructor) {
483       OS << " (by copy constructor)";
484     } else if (DirectBinding) {
485       OS << " (direct reference binding)";
486     } else if (ReferenceBinding) {
487       OS << " (reference binding)";
488     }
489     PrintedSomething = true;
490   }
491 
492   if (Third != ICK_Identity) {
493     if (PrintedSomething) {
494       OS << " -> ";
495     }
496     OS << GetImplicitConversionName(Third);
497     PrintedSomething = true;
498   }
499 
500   if (!PrintedSomething) {
501     OS << "No conversions required";
502   }
503 }
504 
505 /// dump - Print this user-defined conversion sequence to standard
506 /// error. Useful for debugging overloading issues.
507 void UserDefinedConversionSequence::dump() const {
508   raw_ostream &OS = llvm::errs();
509   if (Before.First || Before.Second || Before.Third) {
510     Before.dump();
511     OS << " -> ";
512   }
513   if (ConversionFunction)
514     OS << '\'' << *ConversionFunction << '\'';
515   else
516     OS << "aggregate initialization";
517   if (After.First || After.Second || After.Third) {
518     OS << " -> ";
519     After.dump();
520   }
521 }
522 
523 /// dump - Print this implicit conversion sequence to standard
524 /// error. Useful for debugging overloading issues.
525 void ImplicitConversionSequence::dump() const {
526   raw_ostream &OS = llvm::errs();
527   if (isStdInitializerListElement())
528     OS << "Worst std::initializer_list element conversion: ";
529   switch (ConversionKind) {
530   case StandardConversion:
531     OS << "Standard conversion: ";
532     Standard.dump();
533     break;
534   case UserDefinedConversion:
535     OS << "User-defined conversion: ";
536     UserDefined.dump();
537     break;
538   case EllipsisConversion:
539     OS << "Ellipsis conversion";
540     break;
541   case AmbiguousConversion:
542     OS << "Ambiguous conversion";
543     break;
544   case BadConversion:
545     OS << "Bad conversion";
546     break;
547   }
548 
549   OS << "\n";
550 }
551 
552 void AmbiguousConversionSequence::construct() {
553   new (&conversions()) ConversionSet();
554 }
555 
556 void AmbiguousConversionSequence::destruct() {
557   conversions().~ConversionSet();
558 }
559 
560 void
561 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
562   FromTypePtr = O.FromTypePtr;
563   ToTypePtr = O.ToTypePtr;
564   new (&conversions()) ConversionSet(O.conversions());
565 }
566 
567 namespace {
568   // Structure used by DeductionFailureInfo to store
569   // template argument information.
570   struct DFIArguments {
571     TemplateArgument FirstArg;
572     TemplateArgument SecondArg;
573   };
574   // Structure used by DeductionFailureInfo to store
575   // template parameter and template argument information.
576   struct DFIParamWithArguments : DFIArguments {
577     TemplateParameter Param;
578   };
579   // Structure used by DeductionFailureInfo to store template argument
580   // information and the index of the problematic call argument.
581   struct DFIDeducedMismatchArgs : DFIArguments {
582     TemplateArgumentList *TemplateArgs;
583     unsigned CallArgIndex;
584   };
585 }
586 
587 /// Convert from Sema's representation of template deduction information
588 /// to the form used in overload-candidate information.
589 DeductionFailureInfo
590 clang::MakeDeductionFailureInfo(ASTContext &Context,
591                                 Sema::TemplateDeductionResult TDK,
592                                 TemplateDeductionInfo &Info) {
593   DeductionFailureInfo Result;
594   Result.Result = static_cast<unsigned>(TDK);
595   Result.HasDiagnostic = false;
596   switch (TDK) {
597   case Sema::TDK_Invalid:
598   case Sema::TDK_InstantiationDepth:
599   case Sema::TDK_TooManyArguments:
600   case Sema::TDK_TooFewArguments:
601   case Sema::TDK_MiscellaneousDeductionFailure:
602   case Sema::TDK_CUDATargetMismatch:
603     Result.Data = nullptr;
604     break;
605 
606   case Sema::TDK_Incomplete:
607   case Sema::TDK_InvalidExplicitArguments:
608     Result.Data = Info.Param.getOpaqueValue();
609     break;
610 
611   case Sema::TDK_DeducedMismatch:
612   case Sema::TDK_DeducedMismatchNested: {
613     // FIXME: Should allocate from normal heap so that we can free this later.
614     auto *Saved = new (Context) DFIDeducedMismatchArgs;
615     Saved->FirstArg = Info.FirstArg;
616     Saved->SecondArg = Info.SecondArg;
617     Saved->TemplateArgs = Info.take();
618     Saved->CallArgIndex = Info.CallArgIndex;
619     Result.Data = Saved;
620     break;
621   }
622 
623   case Sema::TDK_NonDeducedMismatch: {
624     // FIXME: Should allocate from normal heap so that we can free this later.
625     DFIArguments *Saved = new (Context) DFIArguments;
626     Saved->FirstArg = Info.FirstArg;
627     Saved->SecondArg = Info.SecondArg;
628     Result.Data = Saved;
629     break;
630   }
631 
632   case Sema::TDK_IncompletePack:
633     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
634   case Sema::TDK_Inconsistent:
635   case Sema::TDK_Underqualified: {
636     // FIXME: Should allocate from normal heap so that we can free this later.
637     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
638     Saved->Param = Info.Param;
639     Saved->FirstArg = Info.FirstArg;
640     Saved->SecondArg = Info.SecondArg;
641     Result.Data = Saved;
642     break;
643   }
644 
645   case Sema::TDK_SubstitutionFailure:
646     Result.Data = Info.take();
647     if (Info.hasSFINAEDiagnostic()) {
648       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
649           SourceLocation(), PartialDiagnostic::NullDiagnostic());
650       Info.takeSFINAEDiagnostic(*Diag);
651       Result.HasDiagnostic = true;
652     }
653     break;
654 
655   case Sema::TDK_Success:
656   case Sema::TDK_NonDependentConversionFailure:
657     llvm_unreachable("not a deduction failure");
658   }
659 
660   return Result;
661 }
662 
663 void DeductionFailureInfo::Destroy() {
664   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665   case Sema::TDK_Success:
666   case Sema::TDK_Invalid:
667   case Sema::TDK_InstantiationDepth:
668   case Sema::TDK_Incomplete:
669   case Sema::TDK_TooManyArguments:
670   case Sema::TDK_TooFewArguments:
671   case Sema::TDK_InvalidExplicitArguments:
672   case Sema::TDK_CUDATargetMismatch:
673   case Sema::TDK_NonDependentConversionFailure:
674     break;
675 
676   case Sema::TDK_IncompletePack:
677   case Sema::TDK_Inconsistent:
678   case Sema::TDK_Underqualified:
679   case Sema::TDK_DeducedMismatch:
680   case Sema::TDK_DeducedMismatchNested:
681   case Sema::TDK_NonDeducedMismatch:
682     // FIXME: Destroy the data?
683     Data = nullptr;
684     break;
685 
686   case Sema::TDK_SubstitutionFailure:
687     // FIXME: Destroy the template argument list?
688     Data = nullptr;
689     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
690       Diag->~PartialDiagnosticAt();
691       HasDiagnostic = false;
692     }
693     break;
694 
695   // Unhandled
696   case Sema::TDK_MiscellaneousDeductionFailure:
697     break;
698   }
699 }
700 
701 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
702   if (HasDiagnostic)
703     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
704   return nullptr;
705 }
706 
707 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
708   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709   case Sema::TDK_Success:
710   case Sema::TDK_Invalid:
711   case Sema::TDK_InstantiationDepth:
712   case Sema::TDK_TooManyArguments:
713   case Sema::TDK_TooFewArguments:
714   case Sema::TDK_SubstitutionFailure:
715   case Sema::TDK_DeducedMismatch:
716   case Sema::TDK_DeducedMismatchNested:
717   case Sema::TDK_NonDeducedMismatch:
718   case Sema::TDK_CUDATargetMismatch:
719   case Sema::TDK_NonDependentConversionFailure:
720     return TemplateParameter();
721 
722   case Sema::TDK_Incomplete:
723   case Sema::TDK_InvalidExplicitArguments:
724     return TemplateParameter::getFromOpaqueValue(Data);
725 
726   case Sema::TDK_IncompletePack:
727   case Sema::TDK_Inconsistent:
728   case Sema::TDK_Underqualified:
729     return static_cast<DFIParamWithArguments*>(Data)->Param;
730 
731   // Unhandled
732   case Sema::TDK_MiscellaneousDeductionFailure:
733     break;
734   }
735 
736   return TemplateParameter();
737 }
738 
739 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
740   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741   case Sema::TDK_Success:
742   case Sema::TDK_Invalid:
743   case Sema::TDK_InstantiationDepth:
744   case Sema::TDK_TooManyArguments:
745   case Sema::TDK_TooFewArguments:
746   case Sema::TDK_Incomplete:
747   case Sema::TDK_IncompletePack:
748   case Sema::TDK_InvalidExplicitArguments:
749   case Sema::TDK_Inconsistent:
750   case Sema::TDK_Underqualified:
751   case Sema::TDK_NonDeducedMismatch:
752   case Sema::TDK_CUDATargetMismatch:
753   case Sema::TDK_NonDependentConversionFailure:
754     return nullptr;
755 
756   case Sema::TDK_DeducedMismatch:
757   case Sema::TDK_DeducedMismatchNested:
758     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
759 
760   case Sema::TDK_SubstitutionFailure:
761     return static_cast<TemplateArgumentList*>(Data);
762 
763   // Unhandled
764   case Sema::TDK_MiscellaneousDeductionFailure:
765     break;
766   }
767 
768   return nullptr;
769 }
770 
771 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
772   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773   case Sema::TDK_Success:
774   case Sema::TDK_Invalid:
775   case Sema::TDK_InstantiationDepth:
776   case Sema::TDK_Incomplete:
777   case Sema::TDK_TooManyArguments:
778   case Sema::TDK_TooFewArguments:
779   case Sema::TDK_InvalidExplicitArguments:
780   case Sema::TDK_SubstitutionFailure:
781   case Sema::TDK_CUDATargetMismatch:
782   case Sema::TDK_NonDependentConversionFailure:
783     return nullptr;
784 
785   case Sema::TDK_IncompletePack:
786   case Sema::TDK_Inconsistent:
787   case Sema::TDK_Underqualified:
788   case Sema::TDK_DeducedMismatch:
789   case Sema::TDK_DeducedMismatchNested:
790   case Sema::TDK_NonDeducedMismatch:
791     return &static_cast<DFIArguments*>(Data)->FirstArg;
792 
793   // Unhandled
794   case Sema::TDK_MiscellaneousDeductionFailure:
795     break;
796   }
797 
798   return nullptr;
799 }
800 
801 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
802   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
803   case Sema::TDK_Success:
804   case Sema::TDK_Invalid:
805   case Sema::TDK_InstantiationDepth:
806   case Sema::TDK_Incomplete:
807   case Sema::TDK_IncompletePack:
808   case Sema::TDK_TooManyArguments:
809   case Sema::TDK_TooFewArguments:
810   case Sema::TDK_InvalidExplicitArguments:
811   case Sema::TDK_SubstitutionFailure:
812   case Sema::TDK_CUDATargetMismatch:
813   case Sema::TDK_NonDependentConversionFailure:
814     return nullptr;
815 
816   case Sema::TDK_Inconsistent:
817   case Sema::TDK_Underqualified:
818   case Sema::TDK_DeducedMismatch:
819   case Sema::TDK_DeducedMismatchNested:
820   case Sema::TDK_NonDeducedMismatch:
821     return &static_cast<DFIArguments*>(Data)->SecondArg;
822 
823   // Unhandled
824   case Sema::TDK_MiscellaneousDeductionFailure:
825     break;
826   }
827 
828   return nullptr;
829 }
830 
831 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
832   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833   case Sema::TDK_DeducedMismatch:
834   case Sema::TDK_DeducedMismatchNested:
835     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
836 
837   default:
838     return llvm::None;
839   }
840 }
841 
842 void OverloadCandidateSet::destroyCandidates() {
843   for (iterator i = begin(), e = end(); i != e; ++i) {
844     for (auto &C : i->Conversions)
845       C.~ImplicitConversionSequence();
846     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
847       i->DeductionFailure.Destroy();
848   }
849 }
850 
851 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
852   destroyCandidates();
853   SlabAllocator.Reset();
854   NumInlineBytesUsed = 0;
855   Candidates.clear();
856   Functions.clear();
857   Kind = CSK;
858 }
859 
860 namespace {
861   class UnbridgedCastsSet {
862     struct Entry {
863       Expr **Addr;
864       Expr *Saved;
865     };
866     SmallVector<Entry, 2> Entries;
867 
868   public:
869     void save(Sema &S, Expr *&E) {
870       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
871       Entry entry = { &E, E };
872       Entries.push_back(entry);
873       E = S.stripARCUnbridgedCast(E);
874     }
875 
876     void restore() {
877       for (SmallVectorImpl<Entry>::iterator
878              i = Entries.begin(), e = Entries.end(); i != e; ++i)
879         *i->Addr = i->Saved;
880     }
881   };
882 }
883 
884 /// checkPlaceholderForOverload - Do any interesting placeholder-like
885 /// preprocessing on the given expression.
886 ///
887 /// \param unbridgedCasts a collection to which to add unbridged casts;
888 ///   without this, they will be immediately diagnosed as errors
889 ///
890 /// Return true on unrecoverable error.
891 static bool
892 checkPlaceholderForOverload(Sema &S, Expr *&E,
893                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
894   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
895     // We can't handle overloaded expressions here because overload
896     // resolution might reasonably tweak them.
897     if (placeholder->getKind() == BuiltinType::Overload) return false;
898 
899     // If the context potentially accepts unbridged ARC casts, strip
900     // the unbridged cast and add it to the collection for later restoration.
901     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
902         unbridgedCasts) {
903       unbridgedCasts->save(S, E);
904       return false;
905     }
906 
907     // Go ahead and check everything else.
908     ExprResult result = S.CheckPlaceholderExpr(E);
909     if (result.isInvalid())
910       return true;
911 
912     E = result.get();
913     return false;
914   }
915 
916   // Nothing to do.
917   return false;
918 }
919 
920 /// checkArgPlaceholdersForOverload - Check a set of call operands for
921 /// placeholders.
922 static bool checkArgPlaceholdersForOverload(Sema &S,
923                                             MultiExprArg Args,
924                                             UnbridgedCastsSet &unbridged) {
925   for (unsigned i = 0, e = Args.size(); i != e; ++i)
926     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
927       return true;
928 
929   return false;
930 }
931 
932 /// Determine whether the given New declaration is an overload of the
933 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
934 /// New and Old cannot be overloaded, e.g., if New has the same signature as
935 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
936 /// functions (or function templates) at all. When it does return Ovl_Match or
937 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
938 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
939 /// declaration.
940 ///
941 /// Example: Given the following input:
942 ///
943 ///   void f(int, float); // #1
944 ///   void f(int, int); // #2
945 ///   int f(int, int); // #3
946 ///
947 /// When we process #1, there is no previous declaration of "f", so IsOverload
948 /// will not be used.
949 ///
950 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
951 /// the parameter types, we see that #1 and #2 are overloaded (since they have
952 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
953 /// unchanged.
954 ///
955 /// When we process #3, Old is an overload set containing #1 and #2. We compare
956 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
957 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
958 /// functions are not part of the signature), IsOverload returns Ovl_Match and
959 /// MatchedDecl will be set to point to the FunctionDecl for #2.
960 ///
961 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
962 /// by a using declaration. The rules for whether to hide shadow declarations
963 /// ignore some properties which otherwise figure into a function template's
964 /// signature.
965 Sema::OverloadKind
966 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
967                     NamedDecl *&Match, bool NewIsUsingDecl) {
968   for (LookupResult::iterator I = Old.begin(), E = Old.end();
969          I != E; ++I) {
970     NamedDecl *OldD = *I;
971 
972     bool OldIsUsingDecl = false;
973     if (isa<UsingShadowDecl>(OldD)) {
974       OldIsUsingDecl = true;
975 
976       // We can always introduce two using declarations into the same
977       // context, even if they have identical signatures.
978       if (NewIsUsingDecl) continue;
979 
980       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
981     }
982 
983     // A using-declaration does not conflict with another declaration
984     // if one of them is hidden.
985     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
986       continue;
987 
988     // If either declaration was introduced by a using declaration,
989     // we'll need to use slightly different rules for matching.
990     // Essentially, these rules are the normal rules, except that
991     // function templates hide function templates with different
992     // return types or template parameter lists.
993     bool UseMemberUsingDeclRules =
994       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
995       !New->getFriendObjectKind();
996 
997     if (FunctionDecl *OldF = OldD->getAsFunction()) {
998       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
999         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1000           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001           continue;
1002         }
1003 
1004         if (!isa<FunctionTemplateDecl>(OldD) &&
1005             !shouldLinkPossiblyHiddenDecl(*I, New))
1006           continue;
1007 
1008         Match = *I;
1009         return Ovl_Match;
1010       }
1011 
1012       // Builtins that have custom typechecking or have a reference should
1013       // not be overloadable or redeclarable.
1014       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1015         Match = *I;
1016         return Ovl_NonFunction;
1017       }
1018     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1019       // We can overload with these, which can show up when doing
1020       // redeclaration checks for UsingDecls.
1021       assert(Old.getLookupKind() == LookupUsingDeclName);
1022     } else if (isa<TagDecl>(OldD)) {
1023       // We can always overload with tags by hiding them.
1024     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1025       // Optimistically assume that an unresolved using decl will
1026       // overload; if it doesn't, we'll have to diagnose during
1027       // template instantiation.
1028       //
1029       // Exception: if the scope is dependent and this is not a class
1030       // member, the using declaration can only introduce an enumerator.
1031       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1032         Match = *I;
1033         return Ovl_NonFunction;
1034       }
1035     } else {
1036       // (C++ 13p1):
1037       //   Only function declarations can be overloaded; object and type
1038       //   declarations cannot be overloaded.
1039       Match = *I;
1040       return Ovl_NonFunction;
1041     }
1042   }
1043 
1044   return Ovl_Overload;
1045 }
1046 
1047 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1048                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1049   // C++ [basic.start.main]p2: This function shall not be overloaded.
1050   if (New->isMain())
1051     return false;
1052 
1053   // MSVCRT user defined entry points cannot be overloaded.
1054   if (New->isMSVCRTEntryPoint())
1055     return false;
1056 
1057   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1058   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1059 
1060   // C++ [temp.fct]p2:
1061   //   A function template can be overloaded with other function templates
1062   //   and with normal (non-template) functions.
1063   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1064     return true;
1065 
1066   // Is the function New an overload of the function Old?
1067   QualType OldQType = Context.getCanonicalType(Old->getType());
1068   QualType NewQType = Context.getCanonicalType(New->getType());
1069 
1070   // Compare the signatures (C++ 1.3.10) of the two functions to
1071   // determine whether they are overloads. If we find any mismatch
1072   // in the signature, they are overloads.
1073 
1074   // If either of these functions is a K&R-style function (no
1075   // prototype), then we consider them to have matching signatures.
1076   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1077       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1078     return false;
1079 
1080   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1081   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1082 
1083   // The signature of a function includes the types of its
1084   // parameters (C++ 1.3.10), which includes the presence or absence
1085   // of the ellipsis; see C++ DR 357).
1086   if (OldQType != NewQType &&
1087       (OldType->getNumParams() != NewType->getNumParams() ||
1088        OldType->isVariadic() != NewType->isVariadic() ||
1089        !FunctionParamTypesAreEqual(OldType, NewType)))
1090     return true;
1091 
1092   // C++ [temp.over.link]p4:
1093   //   The signature of a function template consists of its function
1094   //   signature, its return type and its template parameter list. The names
1095   //   of the template parameters are significant only for establishing the
1096   //   relationship between the template parameters and the rest of the
1097   //   signature.
1098   //
1099   // We check the return type and template parameter lists for function
1100   // templates first; the remaining checks follow.
1101   //
1102   // However, we don't consider either of these when deciding whether
1103   // a member introduced by a shadow declaration is hidden.
1104   if (!UseMemberUsingDeclRules && NewTemplate &&
1105       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1106                                        OldTemplate->getTemplateParameters(),
1107                                        false, TPL_TemplateMatch) ||
1108        !Context.hasSameType(Old->getDeclaredReturnType(),
1109                             New->getDeclaredReturnType())))
1110     return true;
1111 
1112   // If the function is a class member, its signature includes the
1113   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1114   //
1115   // As part of this, also check whether one of the member functions
1116   // is static, in which case they are not overloads (C++
1117   // 13.1p2). While not part of the definition of the signature,
1118   // this check is important to determine whether these functions
1119   // can be overloaded.
1120   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1121   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1122   if (OldMethod && NewMethod &&
1123       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1124     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1125       if (!UseMemberUsingDeclRules &&
1126           (OldMethod->getRefQualifier() == RQ_None ||
1127            NewMethod->getRefQualifier() == RQ_None)) {
1128         // C++0x [over.load]p2:
1129         //   - Member function declarations with the same name and the same
1130         //     parameter-type-list as well as member function template
1131         //     declarations with the same name, the same parameter-type-list, and
1132         //     the same template parameter lists cannot be overloaded if any of
1133         //     them, but not all, have a ref-qualifier (8.3.5).
1134         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1135           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1136         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1137       }
1138       return true;
1139     }
1140 
1141     // We may not have applied the implicit const for a constexpr member
1142     // function yet (because we haven't yet resolved whether this is a static
1143     // or non-static member function). Add it now, on the assumption that this
1144     // is a redeclaration of OldMethod.
1145     // FIXME: OpenCL: Need to consider address spaces
1146     unsigned OldQuals = OldMethod->getTypeQualifiers().getCVRUQualifiers();
1147     unsigned NewQuals = NewMethod->getTypeQualifiers().getCVRUQualifiers();
1148     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1149         !isa<CXXConstructorDecl>(NewMethod))
1150       NewQuals |= Qualifiers::Const;
1151 
1152     // We do not allow overloading based off of '__restrict'.
1153     OldQuals &= ~Qualifiers::Restrict;
1154     NewQuals &= ~Qualifiers::Restrict;
1155     if (OldQuals != NewQuals)
1156       return true;
1157   }
1158 
1159   // Though pass_object_size is placed on parameters and takes an argument, we
1160   // consider it to be a function-level modifier for the sake of function
1161   // identity. Either the function has one or more parameters with
1162   // pass_object_size or it doesn't.
1163   if (functionHasPassObjectSizeParams(New) !=
1164       functionHasPassObjectSizeParams(Old))
1165     return true;
1166 
1167   // enable_if attributes are an order-sensitive part of the signature.
1168   for (specific_attr_iterator<EnableIfAttr>
1169          NewI = New->specific_attr_begin<EnableIfAttr>(),
1170          NewE = New->specific_attr_end<EnableIfAttr>(),
1171          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1172          OldE = Old->specific_attr_end<EnableIfAttr>();
1173        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1174     if (NewI == NewE || OldI == OldE)
1175       return true;
1176     llvm::FoldingSetNodeID NewID, OldID;
1177     NewI->getCond()->Profile(NewID, Context, true);
1178     OldI->getCond()->Profile(OldID, Context, true);
1179     if (NewID != OldID)
1180       return true;
1181   }
1182 
1183   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1184     // Don't allow overloading of destructors.  (In theory we could, but it
1185     // would be a giant change to clang.)
1186     if (isa<CXXDestructorDecl>(New))
1187       return false;
1188 
1189     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1190                        OldTarget = IdentifyCUDATarget(Old);
1191     if (NewTarget == CFT_InvalidTarget)
1192       return false;
1193 
1194     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1195 
1196     // Allow overloading of functions with same signature and different CUDA
1197     // target attributes.
1198     return NewTarget != OldTarget;
1199   }
1200 
1201   // The signatures match; this is not an overload.
1202   return false;
1203 }
1204 
1205 /// Checks availability of the function depending on the current
1206 /// function context. Inside an unavailable function, unavailability is ignored.
1207 ///
1208 /// \returns true if \arg FD is unavailable and current context is inside
1209 /// an available function, false otherwise.
1210 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1211   if (!FD->isUnavailable())
1212     return false;
1213 
1214   // Walk up the context of the caller.
1215   Decl *C = cast<Decl>(CurContext);
1216   do {
1217     if (C->isUnavailable())
1218       return false;
1219   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1220   return true;
1221 }
1222 
1223 /// Tries a user-defined conversion from From to ToType.
1224 ///
1225 /// Produces an implicit conversion sequence for when a standard conversion
1226 /// is not an option. See TryImplicitConversion for more information.
1227 static ImplicitConversionSequence
1228 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1229                          bool SuppressUserConversions,
1230                          bool AllowExplicit,
1231                          bool InOverloadResolution,
1232                          bool CStyle,
1233                          bool AllowObjCWritebackConversion,
1234                          bool AllowObjCConversionOnExplicit) {
1235   ImplicitConversionSequence ICS;
1236 
1237   if (SuppressUserConversions) {
1238     // We're not in the case above, so there is no conversion that
1239     // we can perform.
1240     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1241     return ICS;
1242   }
1243 
1244   // Attempt user-defined conversion.
1245   OverloadCandidateSet Conversions(From->getExprLoc(),
1246                                    OverloadCandidateSet::CSK_Normal);
1247   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1248                                   Conversions, AllowExplicit,
1249                                   AllowObjCConversionOnExplicit)) {
1250   case OR_Success:
1251   case OR_Deleted:
1252     ICS.setUserDefined();
1253     // C++ [over.ics.user]p4:
1254     //   A conversion of an expression of class type to the same class
1255     //   type is given Exact Match rank, and a conversion of an
1256     //   expression of class type to a base class of that type is
1257     //   given Conversion rank, in spite of the fact that a copy
1258     //   constructor (i.e., a user-defined conversion function) is
1259     //   called for those cases.
1260     if (CXXConstructorDecl *Constructor
1261           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1262       QualType FromCanon
1263         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1264       QualType ToCanon
1265         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1266       if (Constructor->isCopyConstructor() &&
1267           (FromCanon == ToCanon ||
1268            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1269         // Turn this into a "standard" conversion sequence, so that it
1270         // gets ranked with standard conversion sequences.
1271         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1272         ICS.setStandard();
1273         ICS.Standard.setAsIdentityConversion();
1274         ICS.Standard.setFromType(From->getType());
1275         ICS.Standard.setAllToTypes(ToType);
1276         ICS.Standard.CopyConstructor = Constructor;
1277         ICS.Standard.FoundCopyConstructor = Found;
1278         if (ToCanon != FromCanon)
1279           ICS.Standard.Second = ICK_Derived_To_Base;
1280       }
1281     }
1282     break;
1283 
1284   case OR_Ambiguous:
1285     ICS.setAmbiguous();
1286     ICS.Ambiguous.setFromType(From->getType());
1287     ICS.Ambiguous.setToType(ToType);
1288     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1289          Cand != Conversions.end(); ++Cand)
1290       if (Cand->Viable)
1291         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1292     break;
1293 
1294     // Fall through.
1295   case OR_No_Viable_Function:
1296     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1297     break;
1298   }
1299 
1300   return ICS;
1301 }
1302 
1303 /// TryImplicitConversion - Attempt to perform an implicit conversion
1304 /// from the given expression (Expr) to the given type (ToType). This
1305 /// function returns an implicit conversion sequence that can be used
1306 /// to perform the initialization. Given
1307 ///
1308 ///   void f(float f);
1309 ///   void g(int i) { f(i); }
1310 ///
1311 /// this routine would produce an implicit conversion sequence to
1312 /// describe the initialization of f from i, which will be a standard
1313 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1314 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1315 //
1316 /// Note that this routine only determines how the conversion can be
1317 /// performed; it does not actually perform the conversion. As such,
1318 /// it will not produce any diagnostics if no conversion is available,
1319 /// but will instead return an implicit conversion sequence of kind
1320 /// "BadConversion".
1321 ///
1322 /// If @p SuppressUserConversions, then user-defined conversions are
1323 /// not permitted.
1324 /// If @p AllowExplicit, then explicit user-defined conversions are
1325 /// permitted.
1326 ///
1327 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1328 /// writeback conversion, which allows __autoreleasing id* parameters to
1329 /// be initialized with __strong id* or __weak id* arguments.
1330 static ImplicitConversionSequence
1331 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1332                       bool SuppressUserConversions,
1333                       bool AllowExplicit,
1334                       bool InOverloadResolution,
1335                       bool CStyle,
1336                       bool AllowObjCWritebackConversion,
1337                       bool AllowObjCConversionOnExplicit) {
1338   ImplicitConversionSequence ICS;
1339   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1340                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1341     ICS.setStandard();
1342     return ICS;
1343   }
1344 
1345   if (!S.getLangOpts().CPlusPlus) {
1346     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1347     return ICS;
1348   }
1349 
1350   // C++ [over.ics.user]p4:
1351   //   A conversion of an expression of class type to the same class
1352   //   type is given Exact Match rank, and a conversion of an
1353   //   expression of class type to a base class of that type is
1354   //   given Conversion rank, in spite of the fact that a copy/move
1355   //   constructor (i.e., a user-defined conversion function) is
1356   //   called for those cases.
1357   QualType FromType = From->getType();
1358   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1359       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1360        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1361     ICS.setStandard();
1362     ICS.Standard.setAsIdentityConversion();
1363     ICS.Standard.setFromType(FromType);
1364     ICS.Standard.setAllToTypes(ToType);
1365 
1366     // We don't actually check at this point whether there is a valid
1367     // copy/move constructor, since overloading just assumes that it
1368     // exists. When we actually perform initialization, we'll find the
1369     // appropriate constructor to copy the returned object, if needed.
1370     ICS.Standard.CopyConstructor = nullptr;
1371 
1372     // Determine whether this is considered a derived-to-base conversion.
1373     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1374       ICS.Standard.Second = ICK_Derived_To_Base;
1375 
1376     return ICS;
1377   }
1378 
1379   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1380                                   AllowExplicit, InOverloadResolution, CStyle,
1381                                   AllowObjCWritebackConversion,
1382                                   AllowObjCConversionOnExplicit);
1383 }
1384 
1385 ImplicitConversionSequence
1386 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1387                             bool SuppressUserConversions,
1388                             bool AllowExplicit,
1389                             bool InOverloadResolution,
1390                             bool CStyle,
1391                             bool AllowObjCWritebackConversion) {
1392   return ::TryImplicitConversion(*this, From, ToType,
1393                                  SuppressUserConversions, AllowExplicit,
1394                                  InOverloadResolution, CStyle,
1395                                  AllowObjCWritebackConversion,
1396                                  /*AllowObjCConversionOnExplicit=*/false);
1397 }
1398 
1399 /// PerformImplicitConversion - Perform an implicit conversion of the
1400 /// expression From to the type ToType. Returns the
1401 /// converted expression. Flavor is the kind of conversion we're
1402 /// performing, used in the error message. If @p AllowExplicit,
1403 /// explicit user-defined conversions are permitted.
1404 ExprResult
1405 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1406                                 AssignmentAction Action, bool AllowExplicit) {
1407   ImplicitConversionSequence ICS;
1408   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1409 }
1410 
1411 ExprResult
1412 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1413                                 AssignmentAction Action, bool AllowExplicit,
1414                                 ImplicitConversionSequence& ICS) {
1415   if (checkPlaceholderForOverload(*this, From))
1416     return ExprError();
1417 
1418   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1419   bool AllowObjCWritebackConversion
1420     = getLangOpts().ObjCAutoRefCount &&
1421       (Action == AA_Passing || Action == AA_Sending);
1422   if (getLangOpts().ObjC)
1423     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1424                                       From->getType(), From);
1425   ICS = ::TryImplicitConversion(*this, From, ToType,
1426                                 /*SuppressUserConversions=*/false,
1427                                 AllowExplicit,
1428                                 /*InOverloadResolution=*/false,
1429                                 /*CStyle=*/false,
1430                                 AllowObjCWritebackConversion,
1431                                 /*AllowObjCConversionOnExplicit=*/false);
1432   return PerformImplicitConversion(From, ToType, ICS, Action);
1433 }
1434 
1435 /// Determine whether the conversion from FromType to ToType is a valid
1436 /// conversion that strips "noexcept" or "noreturn" off the nested function
1437 /// type.
1438 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1439                                 QualType &ResultTy) {
1440   if (Context.hasSameUnqualifiedType(FromType, ToType))
1441     return false;
1442 
1443   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1444   //                    or F(t noexcept) -> F(t)
1445   // where F adds one of the following at most once:
1446   //   - a pointer
1447   //   - a member pointer
1448   //   - a block pointer
1449   // Changes here need matching changes in FindCompositePointerType.
1450   CanQualType CanTo = Context.getCanonicalType(ToType);
1451   CanQualType CanFrom = Context.getCanonicalType(FromType);
1452   Type::TypeClass TyClass = CanTo->getTypeClass();
1453   if (TyClass != CanFrom->getTypeClass()) return false;
1454   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1455     if (TyClass == Type::Pointer) {
1456       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1457       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1458     } else if (TyClass == Type::BlockPointer) {
1459       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1460       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1461     } else if (TyClass == Type::MemberPointer) {
1462       auto ToMPT = CanTo.getAs<MemberPointerType>();
1463       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1464       // A function pointer conversion cannot change the class of the function.
1465       if (ToMPT->getClass() != FromMPT->getClass())
1466         return false;
1467       CanTo = ToMPT->getPointeeType();
1468       CanFrom = FromMPT->getPointeeType();
1469     } else {
1470       return false;
1471     }
1472 
1473     TyClass = CanTo->getTypeClass();
1474     if (TyClass != CanFrom->getTypeClass()) return false;
1475     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1476       return false;
1477   }
1478 
1479   const auto *FromFn = cast<FunctionType>(CanFrom);
1480   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1481 
1482   const auto *ToFn = cast<FunctionType>(CanTo);
1483   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1484 
1485   bool Changed = false;
1486 
1487   // Drop 'noreturn' if not present in target type.
1488   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1489     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1490     Changed = true;
1491   }
1492 
1493   // Drop 'noexcept' if not present in target type.
1494   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1495     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1496     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1497       FromFn = cast<FunctionType>(
1498           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1499                                                    EST_None)
1500                  .getTypePtr());
1501       Changed = true;
1502     }
1503 
1504     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1505     // only if the ExtParameterInfo lists of the two function prototypes can be
1506     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1507     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1508     bool CanUseToFPT, CanUseFromFPT;
1509     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1510                                       CanUseFromFPT, NewParamInfos) &&
1511         CanUseToFPT && !CanUseFromFPT) {
1512       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1513       ExtInfo.ExtParameterInfos =
1514           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1515       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1516                                             FromFPT->getParamTypes(), ExtInfo);
1517       FromFn = QT->getAs<FunctionType>();
1518       Changed = true;
1519     }
1520   }
1521 
1522   if (!Changed)
1523     return false;
1524 
1525   assert(QualType(FromFn, 0).isCanonical());
1526   if (QualType(FromFn, 0) != CanTo) return false;
1527 
1528   ResultTy = ToType;
1529   return true;
1530 }
1531 
1532 /// Determine whether the conversion from FromType to ToType is a valid
1533 /// vector conversion.
1534 ///
1535 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1536 /// conversion.
1537 static bool IsVectorConversion(Sema &S, QualType FromType,
1538                                QualType ToType, ImplicitConversionKind &ICK) {
1539   // We need at least one of these types to be a vector type to have a vector
1540   // conversion.
1541   if (!ToType->isVectorType() && !FromType->isVectorType())
1542     return false;
1543 
1544   // Identical types require no conversions.
1545   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1546     return false;
1547 
1548   // There are no conversions between extended vector types, only identity.
1549   if (ToType->isExtVectorType()) {
1550     // There are no conversions between extended vector types other than the
1551     // identity conversion.
1552     if (FromType->isExtVectorType())
1553       return false;
1554 
1555     // Vector splat from any arithmetic type to a vector.
1556     if (FromType->isArithmeticType()) {
1557       ICK = ICK_Vector_Splat;
1558       return true;
1559     }
1560   }
1561 
1562   // We can perform the conversion between vector types in the following cases:
1563   // 1)vector types are equivalent AltiVec and GCC vector types
1564   // 2)lax vector conversions are permitted and the vector types are of the
1565   //   same size
1566   if (ToType->isVectorType() && FromType->isVectorType()) {
1567     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1568         S.isLaxVectorConversion(FromType, ToType)) {
1569       ICK = ICK_Vector_Conversion;
1570       return true;
1571     }
1572   }
1573 
1574   return false;
1575 }
1576 
1577 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1578                                 bool InOverloadResolution,
1579                                 StandardConversionSequence &SCS,
1580                                 bool CStyle);
1581 
1582 /// IsStandardConversion - Determines whether there is a standard
1583 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1584 /// expression From to the type ToType. Standard conversion sequences
1585 /// only consider non-class types; for conversions that involve class
1586 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1587 /// contain the standard conversion sequence required to perform this
1588 /// conversion and this routine will return true. Otherwise, this
1589 /// routine will return false and the value of SCS is unspecified.
1590 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1591                                  bool InOverloadResolution,
1592                                  StandardConversionSequence &SCS,
1593                                  bool CStyle,
1594                                  bool AllowObjCWritebackConversion) {
1595   QualType FromType = From->getType();
1596 
1597   // Standard conversions (C++ [conv])
1598   SCS.setAsIdentityConversion();
1599   SCS.IncompatibleObjC = false;
1600   SCS.setFromType(FromType);
1601   SCS.CopyConstructor = nullptr;
1602 
1603   // There are no standard conversions for class types in C++, so
1604   // abort early. When overloading in C, however, we do permit them.
1605   if (S.getLangOpts().CPlusPlus &&
1606       (FromType->isRecordType() || ToType->isRecordType()))
1607     return false;
1608 
1609   // The first conversion can be an lvalue-to-rvalue conversion,
1610   // array-to-pointer conversion, or function-to-pointer conversion
1611   // (C++ 4p1).
1612 
1613   if (FromType == S.Context.OverloadTy) {
1614     DeclAccessPair AccessPair;
1615     if (FunctionDecl *Fn
1616           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1617                                                  AccessPair)) {
1618       // We were able to resolve the address of the overloaded function,
1619       // so we can convert to the type of that function.
1620       FromType = Fn->getType();
1621       SCS.setFromType(FromType);
1622 
1623       // we can sometimes resolve &foo<int> regardless of ToType, so check
1624       // if the type matches (identity) or we are converting to bool
1625       if (!S.Context.hasSameUnqualifiedType(
1626                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1627         QualType resultTy;
1628         // if the function type matches except for [[noreturn]], it's ok
1629         if (!S.IsFunctionConversion(FromType,
1630               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1631           // otherwise, only a boolean conversion is standard
1632           if (!ToType->isBooleanType())
1633             return false;
1634       }
1635 
1636       // Check if the "from" expression is taking the address of an overloaded
1637       // function and recompute the FromType accordingly. Take advantage of the
1638       // fact that non-static member functions *must* have such an address-of
1639       // expression.
1640       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1641       if (Method && !Method->isStatic()) {
1642         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1643                "Non-unary operator on non-static member address");
1644         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1645                == UO_AddrOf &&
1646                "Non-address-of operator on non-static member address");
1647         const Type *ClassType
1648           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1649         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1650       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1651         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1652                UO_AddrOf &&
1653                "Non-address-of operator for overloaded function expression");
1654         FromType = S.Context.getPointerType(FromType);
1655       }
1656 
1657       // Check that we've computed the proper type after overload resolution.
1658       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1659       // be calling it from within an NDEBUG block.
1660       assert(S.Context.hasSameType(
1661         FromType,
1662         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1663     } else {
1664       return false;
1665     }
1666   }
1667   // Lvalue-to-rvalue conversion (C++11 4.1):
1668   //   A glvalue (3.10) of a non-function, non-array type T can
1669   //   be converted to a prvalue.
1670   bool argIsLValue = From->isGLValue();
1671   if (argIsLValue &&
1672       !FromType->isFunctionType() && !FromType->isArrayType() &&
1673       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1674     SCS.First = ICK_Lvalue_To_Rvalue;
1675 
1676     // C11 6.3.2.1p2:
1677     //   ... if the lvalue has atomic type, the value has the non-atomic version
1678     //   of the type of the lvalue ...
1679     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1680       FromType = Atomic->getValueType();
1681 
1682     // If T is a non-class type, the type of the rvalue is the
1683     // cv-unqualified version of T. Otherwise, the type of the rvalue
1684     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1685     // just strip the qualifiers because they don't matter.
1686     FromType = FromType.getUnqualifiedType();
1687   } else if (FromType->isArrayType()) {
1688     // Array-to-pointer conversion (C++ 4.2)
1689     SCS.First = ICK_Array_To_Pointer;
1690 
1691     // An lvalue or rvalue of type "array of N T" or "array of unknown
1692     // bound of T" can be converted to an rvalue of type "pointer to
1693     // T" (C++ 4.2p1).
1694     FromType = S.Context.getArrayDecayedType(FromType);
1695 
1696     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1697       // This conversion is deprecated in C++03 (D.4)
1698       SCS.DeprecatedStringLiteralToCharPtr = true;
1699 
1700       // For the purpose of ranking in overload resolution
1701       // (13.3.3.1.1), this conversion is considered an
1702       // array-to-pointer conversion followed by a qualification
1703       // conversion (4.4). (C++ 4.2p2)
1704       SCS.Second = ICK_Identity;
1705       SCS.Third = ICK_Qualification;
1706       SCS.QualificationIncludesObjCLifetime = false;
1707       SCS.setAllToTypes(FromType);
1708       return true;
1709     }
1710   } else if (FromType->isFunctionType() && argIsLValue) {
1711     // Function-to-pointer conversion (C++ 4.3).
1712     SCS.First = ICK_Function_To_Pointer;
1713 
1714     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1715       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1716         if (!S.checkAddressOfFunctionIsAvailable(FD))
1717           return false;
1718 
1719     // An lvalue of function type T can be converted to an rvalue of
1720     // type "pointer to T." The result is a pointer to the
1721     // function. (C++ 4.3p1).
1722     FromType = S.Context.getPointerType(FromType);
1723   } else {
1724     // We don't require any conversions for the first step.
1725     SCS.First = ICK_Identity;
1726   }
1727   SCS.setToType(0, FromType);
1728 
1729   // The second conversion can be an integral promotion, floating
1730   // point promotion, integral conversion, floating point conversion,
1731   // floating-integral conversion, pointer conversion,
1732   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1733   // For overloading in C, this can also be a "compatible-type"
1734   // conversion.
1735   bool IncompatibleObjC = false;
1736   ImplicitConversionKind SecondICK = ICK_Identity;
1737   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1738     // The unqualified versions of the types are the same: there's no
1739     // conversion to do.
1740     SCS.Second = ICK_Identity;
1741   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1742     // Integral promotion (C++ 4.5).
1743     SCS.Second = ICK_Integral_Promotion;
1744     FromType = ToType.getUnqualifiedType();
1745   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1746     // Floating point promotion (C++ 4.6).
1747     SCS.Second = ICK_Floating_Promotion;
1748     FromType = ToType.getUnqualifiedType();
1749   } else if (S.IsComplexPromotion(FromType, ToType)) {
1750     // Complex promotion (Clang extension)
1751     SCS.Second = ICK_Complex_Promotion;
1752     FromType = ToType.getUnqualifiedType();
1753   } else if (ToType->isBooleanType() &&
1754              (FromType->isArithmeticType() ||
1755               FromType->isAnyPointerType() ||
1756               FromType->isBlockPointerType() ||
1757               FromType->isMemberPointerType() ||
1758               FromType->isNullPtrType())) {
1759     // Boolean conversions (C++ 4.12).
1760     SCS.Second = ICK_Boolean_Conversion;
1761     FromType = S.Context.BoolTy;
1762   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1763              ToType->isIntegralType(S.Context)) {
1764     // Integral conversions (C++ 4.7).
1765     SCS.Second = ICK_Integral_Conversion;
1766     FromType = ToType.getUnqualifiedType();
1767   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1768     // Complex conversions (C99 6.3.1.6)
1769     SCS.Second = ICK_Complex_Conversion;
1770     FromType = ToType.getUnqualifiedType();
1771   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1772              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1773     // Complex-real conversions (C99 6.3.1.7)
1774     SCS.Second = ICK_Complex_Real;
1775     FromType = ToType.getUnqualifiedType();
1776   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1777     // FIXME: disable conversions between long double and __float128 if
1778     // their representation is different until there is back end support
1779     // We of course allow this conversion if long double is really double.
1780     if (&S.Context.getFloatTypeSemantics(FromType) !=
1781         &S.Context.getFloatTypeSemantics(ToType)) {
1782       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1783                                     ToType == S.Context.LongDoubleTy) ||
1784                                    (FromType == S.Context.LongDoubleTy &&
1785                                     ToType == S.Context.Float128Ty));
1786       if (Float128AndLongDouble &&
1787           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1788            &llvm::APFloat::PPCDoubleDouble()))
1789         return false;
1790     }
1791     // Floating point conversions (C++ 4.8).
1792     SCS.Second = ICK_Floating_Conversion;
1793     FromType = ToType.getUnqualifiedType();
1794   } else if ((FromType->isRealFloatingType() &&
1795               ToType->isIntegralType(S.Context)) ||
1796              (FromType->isIntegralOrUnscopedEnumerationType() &&
1797               ToType->isRealFloatingType())) {
1798     // Floating-integral conversions (C++ 4.9).
1799     SCS.Second = ICK_Floating_Integral;
1800     FromType = ToType.getUnqualifiedType();
1801   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1802     SCS.Second = ICK_Block_Pointer_Conversion;
1803   } else if (AllowObjCWritebackConversion &&
1804              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1805     SCS.Second = ICK_Writeback_Conversion;
1806   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1807                                    FromType, IncompatibleObjC)) {
1808     // Pointer conversions (C++ 4.10).
1809     SCS.Second = ICK_Pointer_Conversion;
1810     SCS.IncompatibleObjC = IncompatibleObjC;
1811     FromType = FromType.getUnqualifiedType();
1812   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1813                                          InOverloadResolution, FromType)) {
1814     // Pointer to member conversions (4.11).
1815     SCS.Second = ICK_Pointer_Member;
1816   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1817     SCS.Second = SecondICK;
1818     FromType = ToType.getUnqualifiedType();
1819   } else if (!S.getLangOpts().CPlusPlus &&
1820              S.Context.typesAreCompatible(ToType, FromType)) {
1821     // Compatible conversions (Clang extension for C function overloading)
1822     SCS.Second = ICK_Compatible_Conversion;
1823     FromType = ToType.getUnqualifiedType();
1824   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1825                                              InOverloadResolution,
1826                                              SCS, CStyle)) {
1827     SCS.Second = ICK_TransparentUnionConversion;
1828     FromType = ToType;
1829   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1830                                  CStyle)) {
1831     // tryAtomicConversion has updated the standard conversion sequence
1832     // appropriately.
1833     return true;
1834   } else if (ToType->isEventT() &&
1835              From->isIntegerConstantExpr(S.getASTContext()) &&
1836              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1837     SCS.Second = ICK_Zero_Event_Conversion;
1838     FromType = ToType;
1839   } else if (ToType->isQueueT() &&
1840              From->isIntegerConstantExpr(S.getASTContext()) &&
1841              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1842     SCS.Second = ICK_Zero_Queue_Conversion;
1843     FromType = ToType;
1844   } else {
1845     // No second conversion required.
1846     SCS.Second = ICK_Identity;
1847   }
1848   SCS.setToType(1, FromType);
1849 
1850   // The third conversion can be a function pointer conversion or a
1851   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1852   bool ObjCLifetimeConversion;
1853   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1854     // Function pointer conversions (removing 'noexcept') including removal of
1855     // 'noreturn' (Clang extension).
1856     SCS.Third = ICK_Function_Conversion;
1857   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1858                                          ObjCLifetimeConversion)) {
1859     SCS.Third = ICK_Qualification;
1860     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1861     FromType = ToType;
1862   } else {
1863     // No conversion required
1864     SCS.Third = ICK_Identity;
1865   }
1866 
1867   // C++ [over.best.ics]p6:
1868   //   [...] Any difference in top-level cv-qualification is
1869   //   subsumed by the initialization itself and does not constitute
1870   //   a conversion. [...]
1871   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1872   QualType CanonTo = S.Context.getCanonicalType(ToType);
1873   if (CanonFrom.getLocalUnqualifiedType()
1874                                      == CanonTo.getLocalUnqualifiedType() &&
1875       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1876     FromType = ToType;
1877     CanonFrom = CanonTo;
1878   }
1879 
1880   SCS.setToType(2, FromType);
1881 
1882   if (CanonFrom == CanonTo)
1883     return true;
1884 
1885   // If we have not converted the argument type to the parameter type,
1886   // this is a bad conversion sequence, unless we're resolving an overload in C.
1887   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1888     return false;
1889 
1890   ExprResult ER = ExprResult{From};
1891   Sema::AssignConvertType Conv =
1892       S.CheckSingleAssignmentConstraints(ToType, ER,
1893                                          /*Diagnose=*/false,
1894                                          /*DiagnoseCFAudited=*/false,
1895                                          /*ConvertRHS=*/false);
1896   ImplicitConversionKind SecondConv;
1897   switch (Conv) {
1898   case Sema::Compatible:
1899     SecondConv = ICK_C_Only_Conversion;
1900     break;
1901   // For our purposes, discarding qualifiers is just as bad as using an
1902   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1903   // qualifiers, as well.
1904   case Sema::CompatiblePointerDiscardsQualifiers:
1905   case Sema::IncompatiblePointer:
1906   case Sema::IncompatiblePointerSign:
1907     SecondConv = ICK_Incompatible_Pointer_Conversion;
1908     break;
1909   default:
1910     return false;
1911   }
1912 
1913   // First can only be an lvalue conversion, so we pretend that this was the
1914   // second conversion. First should already be valid from earlier in the
1915   // function.
1916   SCS.Second = SecondConv;
1917   SCS.setToType(1, ToType);
1918 
1919   // Third is Identity, because Second should rank us worse than any other
1920   // conversion. This could also be ICK_Qualification, but it's simpler to just
1921   // lump everything in with the second conversion, and we don't gain anything
1922   // from making this ICK_Qualification.
1923   SCS.Third = ICK_Identity;
1924   SCS.setToType(2, ToType);
1925   return true;
1926 }
1927 
1928 static bool
1929 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1930                                      QualType &ToType,
1931                                      bool InOverloadResolution,
1932                                      StandardConversionSequence &SCS,
1933                                      bool CStyle) {
1934 
1935   const RecordType *UT = ToType->getAsUnionType();
1936   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1937     return false;
1938   // The field to initialize within the transparent union.
1939   RecordDecl *UD = UT->getDecl();
1940   // It's compatible if the expression matches any of the fields.
1941   for (const auto *it : UD->fields()) {
1942     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1943                              CStyle, /*ObjCWritebackConversion=*/false)) {
1944       ToType = it->getType();
1945       return true;
1946     }
1947   }
1948   return false;
1949 }
1950 
1951 /// IsIntegralPromotion - Determines whether the conversion from the
1952 /// expression From (whose potentially-adjusted type is FromType) to
1953 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1954 /// sets PromotedType to the promoted type.
1955 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1956   const BuiltinType *To = ToType->getAs<BuiltinType>();
1957   // All integers are built-in.
1958   if (!To) {
1959     return false;
1960   }
1961 
1962   // An rvalue of type char, signed char, unsigned char, short int, or
1963   // unsigned short int can be converted to an rvalue of type int if
1964   // int can represent all the values of the source type; otherwise,
1965   // the source rvalue can be converted to an rvalue of type unsigned
1966   // int (C++ 4.5p1).
1967   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1968       !FromType->isEnumeralType()) {
1969     if (// We can promote any signed, promotable integer type to an int
1970         (FromType->isSignedIntegerType() ||
1971          // We can promote any unsigned integer type whose size is
1972          // less than int to an int.
1973          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1974       return To->getKind() == BuiltinType::Int;
1975     }
1976 
1977     return To->getKind() == BuiltinType::UInt;
1978   }
1979 
1980   // C++11 [conv.prom]p3:
1981   //   A prvalue of an unscoped enumeration type whose underlying type is not
1982   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1983   //   following types that can represent all the values of the enumeration
1984   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1985   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1986   //   long long int. If none of the types in that list can represent all the
1987   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1988   //   type can be converted to an rvalue a prvalue of the extended integer type
1989   //   with lowest integer conversion rank (4.13) greater than the rank of long
1990   //   long in which all the values of the enumeration can be represented. If
1991   //   there are two such extended types, the signed one is chosen.
1992   // C++11 [conv.prom]p4:
1993   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1994   //   can be converted to a prvalue of its underlying type. Moreover, if
1995   //   integral promotion can be applied to its underlying type, a prvalue of an
1996   //   unscoped enumeration type whose underlying type is fixed can also be
1997   //   converted to a prvalue of the promoted underlying type.
1998   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1999     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2000     // provided for a scoped enumeration.
2001     if (FromEnumType->getDecl()->isScoped())
2002       return false;
2003 
2004     // We can perform an integral promotion to the underlying type of the enum,
2005     // even if that's not the promoted type. Note that the check for promoting
2006     // the underlying type is based on the type alone, and does not consider
2007     // the bitfield-ness of the actual source expression.
2008     if (FromEnumType->getDecl()->isFixed()) {
2009       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2010       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2011              IsIntegralPromotion(nullptr, Underlying, ToType);
2012     }
2013 
2014     // We have already pre-calculated the promotion type, so this is trivial.
2015     if (ToType->isIntegerType() &&
2016         isCompleteType(From->getBeginLoc(), FromType))
2017       return Context.hasSameUnqualifiedType(
2018           ToType, FromEnumType->getDecl()->getPromotionType());
2019 
2020     // C++ [conv.prom]p5:
2021     //   If the bit-field has an enumerated type, it is treated as any other
2022     //   value of that type for promotion purposes.
2023     //
2024     // ... so do not fall through into the bit-field checks below in C++.
2025     if (getLangOpts().CPlusPlus)
2026       return false;
2027   }
2028 
2029   // C++0x [conv.prom]p2:
2030   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2031   //   to an rvalue a prvalue of the first of the following types that can
2032   //   represent all the values of its underlying type: int, unsigned int,
2033   //   long int, unsigned long int, long long int, or unsigned long long int.
2034   //   If none of the types in that list can represent all the values of its
2035   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2036   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2037   //   type.
2038   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2039       ToType->isIntegerType()) {
2040     // Determine whether the type we're converting from is signed or
2041     // unsigned.
2042     bool FromIsSigned = FromType->isSignedIntegerType();
2043     uint64_t FromSize = Context.getTypeSize(FromType);
2044 
2045     // The types we'll try to promote to, in the appropriate
2046     // order. Try each of these types.
2047     QualType PromoteTypes[6] = {
2048       Context.IntTy, Context.UnsignedIntTy,
2049       Context.LongTy, Context.UnsignedLongTy ,
2050       Context.LongLongTy, Context.UnsignedLongLongTy
2051     };
2052     for (int Idx = 0; Idx < 6; ++Idx) {
2053       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2054       if (FromSize < ToSize ||
2055           (FromSize == ToSize &&
2056            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2057         // We found the type that we can promote to. If this is the
2058         // type we wanted, we have a promotion. Otherwise, no
2059         // promotion.
2060         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2061       }
2062     }
2063   }
2064 
2065   // An rvalue for an integral bit-field (9.6) can be converted to an
2066   // rvalue of type int if int can represent all the values of the
2067   // bit-field; otherwise, it can be converted to unsigned int if
2068   // unsigned int can represent all the values of the bit-field. If
2069   // the bit-field is larger yet, no integral promotion applies to
2070   // it. If the bit-field has an enumerated type, it is treated as any
2071   // other value of that type for promotion purposes (C++ 4.5p3).
2072   // FIXME: We should delay checking of bit-fields until we actually perform the
2073   // conversion.
2074   //
2075   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2076   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2077   // bit-fields and those whose underlying type is larger than int) for GCC
2078   // compatibility.
2079   if (From) {
2080     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2081       llvm::APSInt BitWidth;
2082       if (FromType->isIntegralType(Context) &&
2083           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2084         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2085         ToSize = Context.getTypeSize(ToType);
2086 
2087         // Are we promoting to an int from a bitfield that fits in an int?
2088         if (BitWidth < ToSize ||
2089             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2090           return To->getKind() == BuiltinType::Int;
2091         }
2092 
2093         // Are we promoting to an unsigned int from an unsigned bitfield
2094         // that fits into an unsigned int?
2095         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2096           return To->getKind() == BuiltinType::UInt;
2097         }
2098 
2099         return false;
2100       }
2101     }
2102   }
2103 
2104   // An rvalue of type bool can be converted to an rvalue of type int,
2105   // with false becoming zero and true becoming one (C++ 4.5p4).
2106   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2107     return true;
2108   }
2109 
2110   return false;
2111 }
2112 
2113 /// IsFloatingPointPromotion - Determines whether the conversion from
2114 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2115 /// returns true and sets PromotedType to the promoted type.
2116 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2117   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2118     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2119       /// An rvalue of type float can be converted to an rvalue of type
2120       /// double. (C++ 4.6p1).
2121       if (FromBuiltin->getKind() == BuiltinType::Float &&
2122           ToBuiltin->getKind() == BuiltinType::Double)
2123         return true;
2124 
2125       // C99 6.3.1.5p1:
2126       //   When a float is promoted to double or long double, or a
2127       //   double is promoted to long double [...].
2128       if (!getLangOpts().CPlusPlus &&
2129           (FromBuiltin->getKind() == BuiltinType::Float ||
2130            FromBuiltin->getKind() == BuiltinType::Double) &&
2131           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2132            ToBuiltin->getKind() == BuiltinType::Float128))
2133         return true;
2134 
2135       // Half can be promoted to float.
2136       if (!getLangOpts().NativeHalfType &&
2137            FromBuiltin->getKind() == BuiltinType::Half &&
2138           ToBuiltin->getKind() == BuiltinType::Float)
2139         return true;
2140     }
2141 
2142   return false;
2143 }
2144 
2145 /// Determine if a conversion is a complex promotion.
2146 ///
2147 /// A complex promotion is defined as a complex -> complex conversion
2148 /// where the conversion between the underlying real types is a
2149 /// floating-point or integral promotion.
2150 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2151   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2152   if (!FromComplex)
2153     return false;
2154 
2155   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2156   if (!ToComplex)
2157     return false;
2158 
2159   return IsFloatingPointPromotion(FromComplex->getElementType(),
2160                                   ToComplex->getElementType()) ||
2161     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2162                         ToComplex->getElementType());
2163 }
2164 
2165 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2166 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2167 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2168 /// if non-empty, will be a pointer to ToType that may or may not have
2169 /// the right set of qualifiers on its pointee.
2170 ///
2171 static QualType
2172 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2173                                    QualType ToPointee, QualType ToType,
2174                                    ASTContext &Context,
2175                                    bool StripObjCLifetime = false) {
2176   assert((FromPtr->getTypeClass() == Type::Pointer ||
2177           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2178          "Invalid similarly-qualified pointer type");
2179 
2180   /// Conversions to 'id' subsume cv-qualifier conversions.
2181   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2182     return ToType.getUnqualifiedType();
2183 
2184   QualType CanonFromPointee
2185     = Context.getCanonicalType(FromPtr->getPointeeType());
2186   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2187   Qualifiers Quals = CanonFromPointee.getQualifiers();
2188 
2189   if (StripObjCLifetime)
2190     Quals.removeObjCLifetime();
2191 
2192   // Exact qualifier match -> return the pointer type we're converting to.
2193   if (CanonToPointee.getLocalQualifiers() == Quals) {
2194     // ToType is exactly what we need. Return it.
2195     if (!ToType.isNull())
2196       return ToType.getUnqualifiedType();
2197 
2198     // Build a pointer to ToPointee. It has the right qualifiers
2199     // already.
2200     if (isa<ObjCObjectPointerType>(ToType))
2201       return Context.getObjCObjectPointerType(ToPointee);
2202     return Context.getPointerType(ToPointee);
2203   }
2204 
2205   // Just build a canonical type that has the right qualifiers.
2206   QualType QualifiedCanonToPointee
2207     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2208 
2209   if (isa<ObjCObjectPointerType>(ToType))
2210     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2211   return Context.getPointerType(QualifiedCanonToPointee);
2212 }
2213 
2214 static bool isNullPointerConstantForConversion(Expr *Expr,
2215                                                bool InOverloadResolution,
2216                                                ASTContext &Context) {
2217   // Handle value-dependent integral null pointer constants correctly.
2218   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2219   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2220       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2221     return !InOverloadResolution;
2222 
2223   return Expr->isNullPointerConstant(Context,
2224                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2225                                         : Expr::NPC_ValueDependentIsNull);
2226 }
2227 
2228 /// IsPointerConversion - Determines whether the conversion of the
2229 /// expression From, which has the (possibly adjusted) type FromType,
2230 /// can be converted to the type ToType via a pointer conversion (C++
2231 /// 4.10). If so, returns true and places the converted type (that
2232 /// might differ from ToType in its cv-qualifiers at some level) into
2233 /// ConvertedType.
2234 ///
2235 /// This routine also supports conversions to and from block pointers
2236 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2237 /// pointers to interfaces. FIXME: Once we've determined the
2238 /// appropriate overloading rules for Objective-C, we may want to
2239 /// split the Objective-C checks into a different routine; however,
2240 /// GCC seems to consider all of these conversions to be pointer
2241 /// conversions, so for now they live here. IncompatibleObjC will be
2242 /// set if the conversion is an allowed Objective-C conversion that
2243 /// should result in a warning.
2244 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2245                                bool InOverloadResolution,
2246                                QualType& ConvertedType,
2247                                bool &IncompatibleObjC) {
2248   IncompatibleObjC = false;
2249   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2250                               IncompatibleObjC))
2251     return true;
2252 
2253   // Conversion from a null pointer constant to any Objective-C pointer type.
2254   if (ToType->isObjCObjectPointerType() &&
2255       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2256     ConvertedType = ToType;
2257     return true;
2258   }
2259 
2260   // Blocks: Block pointers can be converted to void*.
2261   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2262       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2263     ConvertedType = ToType;
2264     return true;
2265   }
2266   // Blocks: A null pointer constant can be converted to a block
2267   // pointer type.
2268   if (ToType->isBlockPointerType() &&
2269       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2270     ConvertedType = ToType;
2271     return true;
2272   }
2273 
2274   // If the left-hand-side is nullptr_t, the right side can be a null
2275   // pointer constant.
2276   if (ToType->isNullPtrType() &&
2277       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2278     ConvertedType = ToType;
2279     return true;
2280   }
2281 
2282   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2283   if (!ToTypePtr)
2284     return false;
2285 
2286   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2287   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2288     ConvertedType = ToType;
2289     return true;
2290   }
2291 
2292   // Beyond this point, both types need to be pointers
2293   // , including objective-c pointers.
2294   QualType ToPointeeType = ToTypePtr->getPointeeType();
2295   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2296       !getLangOpts().ObjCAutoRefCount) {
2297     ConvertedType = BuildSimilarlyQualifiedPointerType(
2298                                       FromType->getAs<ObjCObjectPointerType>(),
2299                                                        ToPointeeType,
2300                                                        ToType, Context);
2301     return true;
2302   }
2303   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2304   if (!FromTypePtr)
2305     return false;
2306 
2307   QualType FromPointeeType = FromTypePtr->getPointeeType();
2308 
2309   // If the unqualified pointee types are the same, this can't be a
2310   // pointer conversion, so don't do all of the work below.
2311   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2312     return false;
2313 
2314   // An rvalue of type "pointer to cv T," where T is an object type,
2315   // can be converted to an rvalue of type "pointer to cv void" (C++
2316   // 4.10p2).
2317   if (FromPointeeType->isIncompleteOrObjectType() &&
2318       ToPointeeType->isVoidType()) {
2319     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2320                                                        ToPointeeType,
2321                                                        ToType, Context,
2322                                                    /*StripObjCLifetime=*/true);
2323     return true;
2324   }
2325 
2326   // MSVC allows implicit function to void* type conversion.
2327   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2328       ToPointeeType->isVoidType()) {
2329     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2330                                                        ToPointeeType,
2331                                                        ToType, Context);
2332     return true;
2333   }
2334 
2335   // When we're overloading in C, we allow a special kind of pointer
2336   // conversion for compatible-but-not-identical pointee types.
2337   if (!getLangOpts().CPlusPlus &&
2338       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2339     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2340                                                        ToPointeeType,
2341                                                        ToType, Context);
2342     return true;
2343   }
2344 
2345   // C++ [conv.ptr]p3:
2346   //
2347   //   An rvalue of type "pointer to cv D," where D is a class type,
2348   //   can be converted to an rvalue of type "pointer to cv B," where
2349   //   B is a base class (clause 10) of D. If B is an inaccessible
2350   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2351   //   necessitates this conversion is ill-formed. The result of the
2352   //   conversion is a pointer to the base class sub-object of the
2353   //   derived class object. The null pointer value is converted to
2354   //   the null pointer value of the destination type.
2355   //
2356   // Note that we do not check for ambiguity or inaccessibility
2357   // here. That is handled by CheckPointerConversion.
2358   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2359       ToPointeeType->isRecordType() &&
2360       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2361       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2362     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2363                                                        ToPointeeType,
2364                                                        ToType, Context);
2365     return true;
2366   }
2367 
2368   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2369       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2370     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2371                                                        ToPointeeType,
2372                                                        ToType, Context);
2373     return true;
2374   }
2375 
2376   return false;
2377 }
2378 
2379 /// Adopt the given qualifiers for the given type.
2380 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2381   Qualifiers TQs = T.getQualifiers();
2382 
2383   // Check whether qualifiers already match.
2384   if (TQs == Qs)
2385     return T;
2386 
2387   if (Qs.compatiblyIncludes(TQs))
2388     return Context.getQualifiedType(T, Qs);
2389 
2390   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2391 }
2392 
2393 /// isObjCPointerConversion - Determines whether this is an
2394 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2395 /// with the same arguments and return values.
2396 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2397                                    QualType& ConvertedType,
2398                                    bool &IncompatibleObjC) {
2399   if (!getLangOpts().ObjC)
2400     return false;
2401 
2402   // The set of qualifiers on the type we're converting from.
2403   Qualifiers FromQualifiers = FromType.getQualifiers();
2404 
2405   // First, we handle all conversions on ObjC object pointer types.
2406   const ObjCObjectPointerType* ToObjCPtr =
2407     ToType->getAs<ObjCObjectPointerType>();
2408   const ObjCObjectPointerType *FromObjCPtr =
2409     FromType->getAs<ObjCObjectPointerType>();
2410 
2411   if (ToObjCPtr && FromObjCPtr) {
2412     // If the pointee types are the same (ignoring qualifications),
2413     // then this is not a pointer conversion.
2414     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2415                                        FromObjCPtr->getPointeeType()))
2416       return false;
2417 
2418     // Conversion between Objective-C pointers.
2419     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2420       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2421       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2422       if (getLangOpts().CPlusPlus && LHS && RHS &&
2423           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2424                                                 FromObjCPtr->getPointeeType()))
2425         return false;
2426       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2427                                                    ToObjCPtr->getPointeeType(),
2428                                                          ToType, Context);
2429       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2430       return true;
2431     }
2432 
2433     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2434       // Okay: this is some kind of implicit downcast of Objective-C
2435       // interfaces, which is permitted. However, we're going to
2436       // complain about it.
2437       IncompatibleObjC = true;
2438       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2439                                                    ToObjCPtr->getPointeeType(),
2440                                                          ToType, Context);
2441       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2442       return true;
2443     }
2444   }
2445   // Beyond this point, both types need to be C pointers or block pointers.
2446   QualType ToPointeeType;
2447   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2448     ToPointeeType = ToCPtr->getPointeeType();
2449   else if (const BlockPointerType *ToBlockPtr =
2450             ToType->getAs<BlockPointerType>()) {
2451     // Objective C++: We're able to convert from a pointer to any object
2452     // to a block pointer type.
2453     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2454       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2455       return true;
2456     }
2457     ToPointeeType = ToBlockPtr->getPointeeType();
2458   }
2459   else if (FromType->getAs<BlockPointerType>() &&
2460            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2461     // Objective C++: We're able to convert from a block pointer type to a
2462     // pointer to any object.
2463     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2464     return true;
2465   }
2466   else
2467     return false;
2468 
2469   QualType FromPointeeType;
2470   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2471     FromPointeeType = FromCPtr->getPointeeType();
2472   else if (const BlockPointerType *FromBlockPtr =
2473            FromType->getAs<BlockPointerType>())
2474     FromPointeeType = FromBlockPtr->getPointeeType();
2475   else
2476     return false;
2477 
2478   // If we have pointers to pointers, recursively check whether this
2479   // is an Objective-C conversion.
2480   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2481       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2482                               IncompatibleObjC)) {
2483     // We always complain about this conversion.
2484     IncompatibleObjC = true;
2485     ConvertedType = Context.getPointerType(ConvertedType);
2486     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2487     return true;
2488   }
2489   // Allow conversion of pointee being objective-c pointer to another one;
2490   // as in I* to id.
2491   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2492       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2493       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2494                               IncompatibleObjC)) {
2495 
2496     ConvertedType = Context.getPointerType(ConvertedType);
2497     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2498     return true;
2499   }
2500 
2501   // If we have pointers to functions or blocks, check whether the only
2502   // differences in the argument and result types are in Objective-C
2503   // pointer conversions. If so, we permit the conversion (but
2504   // complain about it).
2505   const FunctionProtoType *FromFunctionType
2506     = FromPointeeType->getAs<FunctionProtoType>();
2507   const FunctionProtoType *ToFunctionType
2508     = ToPointeeType->getAs<FunctionProtoType>();
2509   if (FromFunctionType && ToFunctionType) {
2510     // If the function types are exactly the same, this isn't an
2511     // Objective-C pointer conversion.
2512     if (Context.getCanonicalType(FromPointeeType)
2513           == Context.getCanonicalType(ToPointeeType))
2514       return false;
2515 
2516     // Perform the quick checks that will tell us whether these
2517     // function types are obviously different.
2518     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2519         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2520         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2521       return false;
2522 
2523     bool HasObjCConversion = false;
2524     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2525         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2526       // Okay, the types match exactly. Nothing to do.
2527     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2528                                        ToFunctionType->getReturnType(),
2529                                        ConvertedType, IncompatibleObjC)) {
2530       // Okay, we have an Objective-C pointer conversion.
2531       HasObjCConversion = true;
2532     } else {
2533       // Function types are too different. Abort.
2534       return false;
2535     }
2536 
2537     // Check argument types.
2538     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2539          ArgIdx != NumArgs; ++ArgIdx) {
2540       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2541       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2542       if (Context.getCanonicalType(FromArgType)
2543             == Context.getCanonicalType(ToArgType)) {
2544         // Okay, the types match exactly. Nothing to do.
2545       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2546                                          ConvertedType, IncompatibleObjC)) {
2547         // Okay, we have an Objective-C pointer conversion.
2548         HasObjCConversion = true;
2549       } else {
2550         // Argument types are too different. Abort.
2551         return false;
2552       }
2553     }
2554 
2555     if (HasObjCConversion) {
2556       // We had an Objective-C conversion. Allow this pointer
2557       // conversion, but complain about it.
2558       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2559       IncompatibleObjC = true;
2560       return true;
2561     }
2562   }
2563 
2564   return false;
2565 }
2566 
2567 /// Determine whether this is an Objective-C writeback conversion,
2568 /// used for parameter passing when performing automatic reference counting.
2569 ///
2570 /// \param FromType The type we're converting form.
2571 ///
2572 /// \param ToType The type we're converting to.
2573 ///
2574 /// \param ConvertedType The type that will be produced after applying
2575 /// this conversion.
2576 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2577                                      QualType &ConvertedType) {
2578   if (!getLangOpts().ObjCAutoRefCount ||
2579       Context.hasSameUnqualifiedType(FromType, ToType))
2580     return false;
2581 
2582   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2583   QualType ToPointee;
2584   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2585     ToPointee = ToPointer->getPointeeType();
2586   else
2587     return false;
2588 
2589   Qualifiers ToQuals = ToPointee.getQualifiers();
2590   if (!ToPointee->isObjCLifetimeType() ||
2591       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2592       !ToQuals.withoutObjCLifetime().empty())
2593     return false;
2594 
2595   // Argument must be a pointer to __strong to __weak.
2596   QualType FromPointee;
2597   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2598     FromPointee = FromPointer->getPointeeType();
2599   else
2600     return false;
2601 
2602   Qualifiers FromQuals = FromPointee.getQualifiers();
2603   if (!FromPointee->isObjCLifetimeType() ||
2604       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2605        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2606     return false;
2607 
2608   // Make sure that we have compatible qualifiers.
2609   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2610   if (!ToQuals.compatiblyIncludes(FromQuals))
2611     return false;
2612 
2613   // Remove qualifiers from the pointee type we're converting from; they
2614   // aren't used in the compatibility check belong, and we'll be adding back
2615   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2616   FromPointee = FromPointee.getUnqualifiedType();
2617 
2618   // The unqualified form of the pointee types must be compatible.
2619   ToPointee = ToPointee.getUnqualifiedType();
2620   bool IncompatibleObjC;
2621   if (Context.typesAreCompatible(FromPointee, ToPointee))
2622     FromPointee = ToPointee;
2623   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2624                                     IncompatibleObjC))
2625     return false;
2626 
2627   /// Construct the type we're converting to, which is a pointer to
2628   /// __autoreleasing pointee.
2629   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2630   ConvertedType = Context.getPointerType(FromPointee);
2631   return true;
2632 }
2633 
2634 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2635                                     QualType& ConvertedType) {
2636   QualType ToPointeeType;
2637   if (const BlockPointerType *ToBlockPtr =
2638         ToType->getAs<BlockPointerType>())
2639     ToPointeeType = ToBlockPtr->getPointeeType();
2640   else
2641     return false;
2642 
2643   QualType FromPointeeType;
2644   if (const BlockPointerType *FromBlockPtr =
2645       FromType->getAs<BlockPointerType>())
2646     FromPointeeType = FromBlockPtr->getPointeeType();
2647   else
2648     return false;
2649   // We have pointer to blocks, check whether the only
2650   // differences in the argument and result types are in Objective-C
2651   // pointer conversions. If so, we permit the conversion.
2652 
2653   const FunctionProtoType *FromFunctionType
2654     = FromPointeeType->getAs<FunctionProtoType>();
2655   const FunctionProtoType *ToFunctionType
2656     = ToPointeeType->getAs<FunctionProtoType>();
2657 
2658   if (!FromFunctionType || !ToFunctionType)
2659     return false;
2660 
2661   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2662     return true;
2663 
2664   // Perform the quick checks that will tell us whether these
2665   // function types are obviously different.
2666   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2667       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2668     return false;
2669 
2670   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2671   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2672   if (FromEInfo != ToEInfo)
2673     return false;
2674 
2675   bool IncompatibleObjC = false;
2676   if (Context.hasSameType(FromFunctionType->getReturnType(),
2677                           ToFunctionType->getReturnType())) {
2678     // Okay, the types match exactly. Nothing to do.
2679   } else {
2680     QualType RHS = FromFunctionType->getReturnType();
2681     QualType LHS = ToFunctionType->getReturnType();
2682     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2683         !RHS.hasQualifiers() && LHS.hasQualifiers())
2684        LHS = LHS.getUnqualifiedType();
2685 
2686      if (Context.hasSameType(RHS,LHS)) {
2687        // OK exact match.
2688      } else if (isObjCPointerConversion(RHS, LHS,
2689                                         ConvertedType, IncompatibleObjC)) {
2690      if (IncompatibleObjC)
2691        return false;
2692      // Okay, we have an Objective-C pointer conversion.
2693      }
2694      else
2695        return false;
2696    }
2697 
2698    // Check argument types.
2699    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2700         ArgIdx != NumArgs; ++ArgIdx) {
2701      IncompatibleObjC = false;
2702      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2703      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2704      if (Context.hasSameType(FromArgType, ToArgType)) {
2705        // Okay, the types match exactly. Nothing to do.
2706      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2707                                         ConvertedType, IncompatibleObjC)) {
2708        if (IncompatibleObjC)
2709          return false;
2710        // Okay, we have an Objective-C pointer conversion.
2711      } else
2712        // Argument types are too different. Abort.
2713        return false;
2714    }
2715 
2716    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2717    bool CanUseToFPT, CanUseFromFPT;
2718    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2719                                       CanUseToFPT, CanUseFromFPT,
2720                                       NewParamInfos))
2721      return false;
2722 
2723    ConvertedType = ToType;
2724    return true;
2725 }
2726 
2727 enum {
2728   ft_default,
2729   ft_different_class,
2730   ft_parameter_arity,
2731   ft_parameter_mismatch,
2732   ft_return_type,
2733   ft_qualifer_mismatch,
2734   ft_noexcept
2735 };
2736 
2737 /// Attempts to get the FunctionProtoType from a Type. Handles
2738 /// MemberFunctionPointers properly.
2739 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2740   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2741     return FPT;
2742 
2743   if (auto *MPT = FromType->getAs<MemberPointerType>())
2744     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2745 
2746   return nullptr;
2747 }
2748 
2749 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2750 /// function types.  Catches different number of parameter, mismatch in
2751 /// parameter types, and different return types.
2752 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2753                                       QualType FromType, QualType ToType) {
2754   // If either type is not valid, include no extra info.
2755   if (FromType.isNull() || ToType.isNull()) {
2756     PDiag << ft_default;
2757     return;
2758   }
2759 
2760   // Get the function type from the pointers.
2761   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2762     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2763                             *ToMember = ToType->getAs<MemberPointerType>();
2764     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2765       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2766             << QualType(FromMember->getClass(), 0);
2767       return;
2768     }
2769     FromType = FromMember->getPointeeType();
2770     ToType = ToMember->getPointeeType();
2771   }
2772 
2773   if (FromType->isPointerType())
2774     FromType = FromType->getPointeeType();
2775   if (ToType->isPointerType())
2776     ToType = ToType->getPointeeType();
2777 
2778   // Remove references.
2779   FromType = FromType.getNonReferenceType();
2780   ToType = ToType.getNonReferenceType();
2781 
2782   // Don't print extra info for non-specialized template functions.
2783   if (FromType->isInstantiationDependentType() &&
2784       !FromType->getAs<TemplateSpecializationType>()) {
2785     PDiag << ft_default;
2786     return;
2787   }
2788 
2789   // No extra info for same types.
2790   if (Context.hasSameType(FromType, ToType)) {
2791     PDiag << ft_default;
2792     return;
2793   }
2794 
2795   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2796                           *ToFunction = tryGetFunctionProtoType(ToType);
2797 
2798   // Both types need to be function types.
2799   if (!FromFunction || !ToFunction) {
2800     PDiag << ft_default;
2801     return;
2802   }
2803 
2804   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2805     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2806           << FromFunction->getNumParams();
2807     return;
2808   }
2809 
2810   // Handle different parameter types.
2811   unsigned ArgPos;
2812   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2813     PDiag << ft_parameter_mismatch << ArgPos + 1
2814           << ToFunction->getParamType(ArgPos)
2815           << FromFunction->getParamType(ArgPos);
2816     return;
2817   }
2818 
2819   // Handle different return type.
2820   if (!Context.hasSameType(FromFunction->getReturnType(),
2821                            ToFunction->getReturnType())) {
2822     PDiag << ft_return_type << ToFunction->getReturnType()
2823           << FromFunction->getReturnType();
2824     return;
2825   }
2826 
2827   if (FromFunction->getTypeQuals() != ToFunction->getTypeQuals()) {
2828     PDiag << ft_qualifer_mismatch << ToFunction->getTypeQuals()
2829           << FromFunction->getTypeQuals();
2830     return;
2831   }
2832 
2833   // Handle exception specification differences on canonical type (in C++17
2834   // onwards).
2835   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2836           ->isNothrow() !=
2837       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2838           ->isNothrow()) {
2839     PDiag << ft_noexcept;
2840     return;
2841   }
2842 
2843   // Unable to find a difference, so add no extra info.
2844   PDiag << ft_default;
2845 }
2846 
2847 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2848 /// for equality of their argument types. Caller has already checked that
2849 /// they have same number of arguments.  If the parameters are different,
2850 /// ArgPos will have the parameter index of the first different parameter.
2851 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2852                                       const FunctionProtoType *NewType,
2853                                       unsigned *ArgPos) {
2854   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2855                                               N = NewType->param_type_begin(),
2856                                               E = OldType->param_type_end();
2857        O && (O != E); ++O, ++N) {
2858     if (!Context.hasSameType(O->getUnqualifiedType(),
2859                              N->getUnqualifiedType())) {
2860       if (ArgPos)
2861         *ArgPos = O - OldType->param_type_begin();
2862       return false;
2863     }
2864   }
2865   return true;
2866 }
2867 
2868 /// CheckPointerConversion - Check the pointer conversion from the
2869 /// expression From to the type ToType. This routine checks for
2870 /// ambiguous or inaccessible derived-to-base pointer
2871 /// conversions for which IsPointerConversion has already returned
2872 /// true. It returns true and produces a diagnostic if there was an
2873 /// error, or returns false otherwise.
2874 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2875                                   CastKind &Kind,
2876                                   CXXCastPath& BasePath,
2877                                   bool IgnoreBaseAccess,
2878                                   bool Diagnose) {
2879   QualType FromType = From->getType();
2880   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2881 
2882   Kind = CK_BitCast;
2883 
2884   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2885       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2886           Expr::NPCK_ZeroExpression) {
2887     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2888       DiagRuntimeBehavior(From->getExprLoc(), From,
2889                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2890                             << ToType << From->getSourceRange());
2891     else if (!isUnevaluatedContext())
2892       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2893         << ToType << From->getSourceRange();
2894   }
2895   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2896     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2897       QualType FromPointeeType = FromPtrType->getPointeeType(),
2898                ToPointeeType   = ToPtrType->getPointeeType();
2899 
2900       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2901           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2902         // We must have a derived-to-base conversion. Check an
2903         // ambiguous or inaccessible conversion.
2904         unsigned InaccessibleID = 0;
2905         unsigned AmbigiousID = 0;
2906         if (Diagnose) {
2907           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2908           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2909         }
2910         if (CheckDerivedToBaseConversion(
2911                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2912                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2913                 &BasePath, IgnoreBaseAccess))
2914           return true;
2915 
2916         // The conversion was successful.
2917         Kind = CK_DerivedToBase;
2918       }
2919 
2920       if (Diagnose && !IsCStyleOrFunctionalCast &&
2921           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2922         assert(getLangOpts().MSVCCompat &&
2923                "this should only be possible with MSVCCompat!");
2924         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2925             << From->getSourceRange();
2926       }
2927     }
2928   } else if (const ObjCObjectPointerType *ToPtrType =
2929                ToType->getAs<ObjCObjectPointerType>()) {
2930     if (const ObjCObjectPointerType *FromPtrType =
2931           FromType->getAs<ObjCObjectPointerType>()) {
2932       // Objective-C++ conversions are always okay.
2933       // FIXME: We should have a different class of conversions for the
2934       // Objective-C++ implicit conversions.
2935       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2936         return false;
2937     } else if (FromType->isBlockPointerType()) {
2938       Kind = CK_BlockPointerToObjCPointerCast;
2939     } else {
2940       Kind = CK_CPointerToObjCPointerCast;
2941     }
2942   } else if (ToType->isBlockPointerType()) {
2943     if (!FromType->isBlockPointerType())
2944       Kind = CK_AnyPointerToBlockPointerCast;
2945   }
2946 
2947   // We shouldn't fall into this case unless it's valid for other
2948   // reasons.
2949   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2950     Kind = CK_NullToPointer;
2951 
2952   return false;
2953 }
2954 
2955 /// IsMemberPointerConversion - Determines whether the conversion of the
2956 /// expression From, which has the (possibly adjusted) type FromType, can be
2957 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2958 /// If so, returns true and places the converted type (that might differ from
2959 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2960 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2961                                      QualType ToType,
2962                                      bool InOverloadResolution,
2963                                      QualType &ConvertedType) {
2964   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2965   if (!ToTypePtr)
2966     return false;
2967 
2968   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2969   if (From->isNullPointerConstant(Context,
2970                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2971                                         : Expr::NPC_ValueDependentIsNull)) {
2972     ConvertedType = ToType;
2973     return true;
2974   }
2975 
2976   // Otherwise, both types have to be member pointers.
2977   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2978   if (!FromTypePtr)
2979     return false;
2980 
2981   // A pointer to member of B can be converted to a pointer to member of D,
2982   // where D is derived from B (C++ 4.11p2).
2983   QualType FromClass(FromTypePtr->getClass(), 0);
2984   QualType ToClass(ToTypePtr->getClass(), 0);
2985 
2986   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2987       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
2988     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2989                                                  ToClass.getTypePtr());
2990     return true;
2991   }
2992 
2993   return false;
2994 }
2995 
2996 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2997 /// expression From to the type ToType. This routine checks for ambiguous or
2998 /// virtual or inaccessible base-to-derived member pointer conversions
2999 /// for which IsMemberPointerConversion has already returned true. It returns
3000 /// true and produces a diagnostic if there was an error, or returns false
3001 /// otherwise.
3002 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3003                                         CastKind &Kind,
3004                                         CXXCastPath &BasePath,
3005                                         bool IgnoreBaseAccess) {
3006   QualType FromType = From->getType();
3007   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3008   if (!FromPtrType) {
3009     // This must be a null pointer to member pointer conversion
3010     assert(From->isNullPointerConstant(Context,
3011                                        Expr::NPC_ValueDependentIsNull) &&
3012            "Expr must be null pointer constant!");
3013     Kind = CK_NullToMemberPointer;
3014     return false;
3015   }
3016 
3017   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3018   assert(ToPtrType && "No member pointer cast has a target type "
3019                       "that is not a member pointer.");
3020 
3021   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3022   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3023 
3024   // FIXME: What about dependent types?
3025   assert(FromClass->isRecordType() && "Pointer into non-class.");
3026   assert(ToClass->isRecordType() && "Pointer into non-class.");
3027 
3028   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3029                      /*DetectVirtual=*/true);
3030   bool DerivationOkay =
3031       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3032   assert(DerivationOkay &&
3033          "Should not have been called if derivation isn't OK.");
3034   (void)DerivationOkay;
3035 
3036   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3037                                   getUnqualifiedType())) {
3038     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3039     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3040       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3041     return true;
3042   }
3043 
3044   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3045     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3046       << FromClass << ToClass << QualType(VBase, 0)
3047       << From->getSourceRange();
3048     return true;
3049   }
3050 
3051   if (!IgnoreBaseAccess)
3052     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3053                          Paths.front(),
3054                          diag::err_downcast_from_inaccessible_base);
3055 
3056   // Must be a base to derived member conversion.
3057   BuildBasePathArray(Paths, BasePath);
3058   Kind = CK_BaseToDerivedMemberPointer;
3059   return false;
3060 }
3061 
3062 /// Determine whether the lifetime conversion between the two given
3063 /// qualifiers sets is nontrivial.
3064 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3065                                                Qualifiers ToQuals) {
3066   // Converting anything to const __unsafe_unretained is trivial.
3067   if (ToQuals.hasConst() &&
3068       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3069     return false;
3070 
3071   return true;
3072 }
3073 
3074 /// IsQualificationConversion - Determines whether the conversion from
3075 /// an rvalue of type FromType to ToType is a qualification conversion
3076 /// (C++ 4.4).
3077 ///
3078 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3079 /// when the qualification conversion involves a change in the Objective-C
3080 /// object lifetime.
3081 bool
3082 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3083                                 bool CStyle, bool &ObjCLifetimeConversion) {
3084   FromType = Context.getCanonicalType(FromType);
3085   ToType = Context.getCanonicalType(ToType);
3086   ObjCLifetimeConversion = false;
3087 
3088   // If FromType and ToType are the same type, this is not a
3089   // qualification conversion.
3090   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3091     return false;
3092 
3093   // (C++ 4.4p4):
3094   //   A conversion can add cv-qualifiers at levels other than the first
3095   //   in multi-level pointers, subject to the following rules: [...]
3096   bool PreviousToQualsIncludeConst = true;
3097   bool UnwrappedAnyPointer = false;
3098   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3099     // Within each iteration of the loop, we check the qualifiers to
3100     // determine if this still looks like a qualification
3101     // conversion. Then, if all is well, we unwrap one more level of
3102     // pointers or pointers-to-members and do it all again
3103     // until there are no more pointers or pointers-to-members left to
3104     // unwrap.
3105     UnwrappedAnyPointer = true;
3106 
3107     Qualifiers FromQuals = FromType.getQualifiers();
3108     Qualifiers ToQuals = ToType.getQualifiers();
3109 
3110     // Ignore __unaligned qualifier if this type is void.
3111     if (ToType.getUnqualifiedType()->isVoidType())
3112       FromQuals.removeUnaligned();
3113 
3114     // Objective-C ARC:
3115     //   Check Objective-C lifetime conversions.
3116     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3117         UnwrappedAnyPointer) {
3118       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3119         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3120           ObjCLifetimeConversion = true;
3121         FromQuals.removeObjCLifetime();
3122         ToQuals.removeObjCLifetime();
3123       } else {
3124         // Qualification conversions cannot cast between different
3125         // Objective-C lifetime qualifiers.
3126         return false;
3127       }
3128     }
3129 
3130     // Allow addition/removal of GC attributes but not changing GC attributes.
3131     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3132         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3133       FromQuals.removeObjCGCAttr();
3134       ToQuals.removeObjCGCAttr();
3135     }
3136 
3137     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3138     //      2,j, and similarly for volatile.
3139     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3140       return false;
3141 
3142     //   -- if the cv 1,j and cv 2,j are different, then const is in
3143     //      every cv for 0 < k < j.
3144     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3145         && !PreviousToQualsIncludeConst)
3146       return false;
3147 
3148     // Keep track of whether all prior cv-qualifiers in the "to" type
3149     // include const.
3150     PreviousToQualsIncludeConst
3151       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3152   }
3153 
3154   // Allows address space promotion by language rules implemented in
3155   // Type::Qualifiers::isAddressSpaceSupersetOf.
3156   Qualifiers FromQuals = FromType.getQualifiers();
3157   Qualifiers ToQuals = ToType.getQualifiers();
3158   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3159       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3160     return false;
3161   }
3162 
3163   // We are left with FromType and ToType being the pointee types
3164   // after unwrapping the original FromType and ToType the same number
3165   // of types. If we unwrapped any pointers, and if FromType and
3166   // ToType have the same unqualified type (since we checked
3167   // qualifiers above), then this is a qualification conversion.
3168   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3169 }
3170 
3171 /// - Determine whether this is a conversion from a scalar type to an
3172 /// atomic type.
3173 ///
3174 /// If successful, updates \c SCS's second and third steps in the conversion
3175 /// sequence to finish the conversion.
3176 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3177                                 bool InOverloadResolution,
3178                                 StandardConversionSequence &SCS,
3179                                 bool CStyle) {
3180   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3181   if (!ToAtomic)
3182     return false;
3183 
3184   StandardConversionSequence InnerSCS;
3185   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3186                             InOverloadResolution, InnerSCS,
3187                             CStyle, /*AllowObjCWritebackConversion=*/false))
3188     return false;
3189 
3190   SCS.Second = InnerSCS.Second;
3191   SCS.setToType(1, InnerSCS.getToType(1));
3192   SCS.Third = InnerSCS.Third;
3193   SCS.QualificationIncludesObjCLifetime
3194     = InnerSCS.QualificationIncludesObjCLifetime;
3195   SCS.setToType(2, InnerSCS.getToType(2));
3196   return true;
3197 }
3198 
3199 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3200                                               CXXConstructorDecl *Constructor,
3201                                               QualType Type) {
3202   const FunctionProtoType *CtorType =
3203       Constructor->getType()->getAs<FunctionProtoType>();
3204   if (CtorType->getNumParams() > 0) {
3205     QualType FirstArg = CtorType->getParamType(0);
3206     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3207       return true;
3208   }
3209   return false;
3210 }
3211 
3212 static OverloadingResult
3213 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3214                                        CXXRecordDecl *To,
3215                                        UserDefinedConversionSequence &User,
3216                                        OverloadCandidateSet &CandidateSet,
3217                                        bool AllowExplicit) {
3218   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3219   for (auto *D : S.LookupConstructors(To)) {
3220     auto Info = getConstructorInfo(D);
3221     if (!Info)
3222       continue;
3223 
3224     bool Usable = !Info.Constructor->isInvalidDecl() &&
3225                   S.isInitListConstructor(Info.Constructor) &&
3226                   (AllowExplicit || !Info.Constructor->isExplicit());
3227     if (Usable) {
3228       // If the first argument is (a reference to) the target type,
3229       // suppress conversions.
3230       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3231           S.Context, Info.Constructor, ToType);
3232       if (Info.ConstructorTmpl)
3233         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3234                                        /*ExplicitArgs*/ nullptr, From,
3235                                        CandidateSet, SuppressUserConversions);
3236       else
3237         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3238                                CandidateSet, SuppressUserConversions);
3239     }
3240   }
3241 
3242   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3243 
3244   OverloadCandidateSet::iterator Best;
3245   switch (auto Result =
3246               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3247   case OR_Deleted:
3248   case OR_Success: {
3249     // Record the standard conversion we used and the conversion function.
3250     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3251     QualType ThisType = Constructor->getThisType(S.Context);
3252     // Initializer lists don't have conversions as such.
3253     User.Before.setAsIdentityConversion();
3254     User.HadMultipleCandidates = HadMultipleCandidates;
3255     User.ConversionFunction = Constructor;
3256     User.FoundConversionFunction = Best->FoundDecl;
3257     User.After.setAsIdentityConversion();
3258     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3259     User.After.setAllToTypes(ToType);
3260     return Result;
3261   }
3262 
3263   case OR_No_Viable_Function:
3264     return OR_No_Viable_Function;
3265   case OR_Ambiguous:
3266     return OR_Ambiguous;
3267   }
3268 
3269   llvm_unreachable("Invalid OverloadResult!");
3270 }
3271 
3272 /// Determines whether there is a user-defined conversion sequence
3273 /// (C++ [over.ics.user]) that converts expression From to the type
3274 /// ToType. If such a conversion exists, User will contain the
3275 /// user-defined conversion sequence that performs such a conversion
3276 /// and this routine will return true. Otherwise, this routine returns
3277 /// false and User is unspecified.
3278 ///
3279 /// \param AllowExplicit  true if the conversion should consider C++0x
3280 /// "explicit" conversion functions as well as non-explicit conversion
3281 /// functions (C++0x [class.conv.fct]p2).
3282 ///
3283 /// \param AllowObjCConversionOnExplicit true if the conversion should
3284 /// allow an extra Objective-C pointer conversion on uses of explicit
3285 /// constructors. Requires \c AllowExplicit to also be set.
3286 static OverloadingResult
3287 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3288                         UserDefinedConversionSequence &User,
3289                         OverloadCandidateSet &CandidateSet,
3290                         bool AllowExplicit,
3291                         bool AllowObjCConversionOnExplicit) {
3292   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3293   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3294 
3295   // Whether we will only visit constructors.
3296   bool ConstructorsOnly = false;
3297 
3298   // If the type we are conversion to is a class type, enumerate its
3299   // constructors.
3300   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3301     // C++ [over.match.ctor]p1:
3302     //   When objects of class type are direct-initialized (8.5), or
3303     //   copy-initialized from an expression of the same or a
3304     //   derived class type (8.5), overload resolution selects the
3305     //   constructor. [...] For copy-initialization, the candidate
3306     //   functions are all the converting constructors (12.3.1) of
3307     //   that class. The argument list is the expression-list within
3308     //   the parentheses of the initializer.
3309     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3310         (From->getType()->getAs<RecordType>() &&
3311          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3312       ConstructorsOnly = true;
3313 
3314     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3315       // We're not going to find any constructors.
3316     } else if (CXXRecordDecl *ToRecordDecl
3317                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3318 
3319       Expr **Args = &From;
3320       unsigned NumArgs = 1;
3321       bool ListInitializing = false;
3322       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3323         // But first, see if there is an init-list-constructor that will work.
3324         OverloadingResult Result = IsInitializerListConstructorConversion(
3325             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3326         if (Result != OR_No_Viable_Function)
3327           return Result;
3328         // Never mind.
3329         CandidateSet.clear(
3330             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3331 
3332         // If we're list-initializing, we pass the individual elements as
3333         // arguments, not the entire list.
3334         Args = InitList->getInits();
3335         NumArgs = InitList->getNumInits();
3336         ListInitializing = true;
3337       }
3338 
3339       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3340         auto Info = getConstructorInfo(D);
3341         if (!Info)
3342           continue;
3343 
3344         bool Usable = !Info.Constructor->isInvalidDecl();
3345         if (ListInitializing)
3346           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3347         else
3348           Usable = Usable &&
3349                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3350         if (Usable) {
3351           bool SuppressUserConversions = !ConstructorsOnly;
3352           if (SuppressUserConversions && ListInitializing) {
3353             SuppressUserConversions = false;
3354             if (NumArgs == 1) {
3355               // If the first argument is (a reference to) the target type,
3356               // suppress conversions.
3357               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3358                   S.Context, Info.Constructor, ToType);
3359             }
3360           }
3361           if (Info.ConstructorTmpl)
3362             S.AddTemplateOverloadCandidate(
3363                 Info.ConstructorTmpl, Info.FoundDecl,
3364                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3365                 CandidateSet, SuppressUserConversions);
3366           else
3367             // Allow one user-defined conversion when user specifies a
3368             // From->ToType conversion via an static cast (c-style, etc).
3369             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3370                                    llvm::makeArrayRef(Args, NumArgs),
3371                                    CandidateSet, SuppressUserConversions);
3372         }
3373       }
3374     }
3375   }
3376 
3377   // Enumerate conversion functions, if we're allowed to.
3378   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3379   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3380     // No conversion functions from incomplete types.
3381   } else if (const RecordType *FromRecordType =
3382                  From->getType()->getAs<RecordType>()) {
3383     if (CXXRecordDecl *FromRecordDecl
3384          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3385       // Add all of the conversion functions as candidates.
3386       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3387       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3388         DeclAccessPair FoundDecl = I.getPair();
3389         NamedDecl *D = FoundDecl.getDecl();
3390         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3391         if (isa<UsingShadowDecl>(D))
3392           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3393 
3394         CXXConversionDecl *Conv;
3395         FunctionTemplateDecl *ConvTemplate;
3396         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3397           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3398         else
3399           Conv = cast<CXXConversionDecl>(D);
3400 
3401         if (AllowExplicit || !Conv->isExplicit()) {
3402           if (ConvTemplate)
3403             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3404                                              ActingContext, From, ToType,
3405                                              CandidateSet,
3406                                              AllowObjCConversionOnExplicit);
3407           else
3408             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3409                                      From, ToType, CandidateSet,
3410                                      AllowObjCConversionOnExplicit);
3411         }
3412       }
3413     }
3414   }
3415 
3416   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3417 
3418   OverloadCandidateSet::iterator Best;
3419   switch (auto Result =
3420               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3421   case OR_Success:
3422   case OR_Deleted:
3423     // Record the standard conversion we used and the conversion function.
3424     if (CXXConstructorDecl *Constructor
3425           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3426       // C++ [over.ics.user]p1:
3427       //   If the user-defined conversion is specified by a
3428       //   constructor (12.3.1), the initial standard conversion
3429       //   sequence converts the source type to the type required by
3430       //   the argument of the constructor.
3431       //
3432       QualType ThisType = Constructor->getThisType(S.Context);
3433       if (isa<InitListExpr>(From)) {
3434         // Initializer lists don't have conversions as such.
3435         User.Before.setAsIdentityConversion();
3436       } else {
3437         if (Best->Conversions[0].isEllipsis())
3438           User.EllipsisConversion = true;
3439         else {
3440           User.Before = Best->Conversions[0].Standard;
3441           User.EllipsisConversion = false;
3442         }
3443       }
3444       User.HadMultipleCandidates = HadMultipleCandidates;
3445       User.ConversionFunction = Constructor;
3446       User.FoundConversionFunction = Best->FoundDecl;
3447       User.After.setAsIdentityConversion();
3448       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3449       User.After.setAllToTypes(ToType);
3450       return Result;
3451     }
3452     if (CXXConversionDecl *Conversion
3453                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3454       // C++ [over.ics.user]p1:
3455       //
3456       //   [...] If the user-defined conversion is specified by a
3457       //   conversion function (12.3.2), the initial standard
3458       //   conversion sequence converts the source type to the
3459       //   implicit object parameter of the conversion function.
3460       User.Before = Best->Conversions[0].Standard;
3461       User.HadMultipleCandidates = HadMultipleCandidates;
3462       User.ConversionFunction = Conversion;
3463       User.FoundConversionFunction = Best->FoundDecl;
3464       User.EllipsisConversion = false;
3465 
3466       // C++ [over.ics.user]p2:
3467       //   The second standard conversion sequence converts the
3468       //   result of the user-defined conversion to the target type
3469       //   for the sequence. Since an implicit conversion sequence
3470       //   is an initialization, the special rules for
3471       //   initialization by user-defined conversion apply when
3472       //   selecting the best user-defined conversion for a
3473       //   user-defined conversion sequence (see 13.3.3 and
3474       //   13.3.3.1).
3475       User.After = Best->FinalConversion;
3476       return Result;
3477     }
3478     llvm_unreachable("Not a constructor or conversion function?");
3479 
3480   case OR_No_Viable_Function:
3481     return OR_No_Viable_Function;
3482 
3483   case OR_Ambiguous:
3484     return OR_Ambiguous;
3485   }
3486 
3487   llvm_unreachable("Invalid OverloadResult!");
3488 }
3489 
3490 bool
3491 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3492   ImplicitConversionSequence ICS;
3493   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3494                                     OverloadCandidateSet::CSK_Normal);
3495   OverloadingResult OvResult =
3496     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3497                             CandidateSet, false, false);
3498   if (OvResult == OR_Ambiguous)
3499     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3500         << From->getType() << ToType << From->getSourceRange();
3501   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3502     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3503                              diag::err_typecheck_nonviable_condition_incomplete,
3504                              From->getType(), From->getSourceRange()))
3505       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3506           << false << From->getType() << From->getSourceRange() << ToType;
3507   } else
3508     return false;
3509   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3510   return true;
3511 }
3512 
3513 /// Compare the user-defined conversion functions or constructors
3514 /// of two user-defined conversion sequences to determine whether any ordering
3515 /// is possible.
3516 static ImplicitConversionSequence::CompareKind
3517 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3518                            FunctionDecl *Function2) {
3519   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3520     return ImplicitConversionSequence::Indistinguishable;
3521 
3522   // Objective-C++:
3523   //   If both conversion functions are implicitly-declared conversions from
3524   //   a lambda closure type to a function pointer and a block pointer,
3525   //   respectively, always prefer the conversion to a function pointer,
3526   //   because the function pointer is more lightweight and is more likely
3527   //   to keep code working.
3528   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3529   if (!Conv1)
3530     return ImplicitConversionSequence::Indistinguishable;
3531 
3532   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3533   if (!Conv2)
3534     return ImplicitConversionSequence::Indistinguishable;
3535 
3536   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3537     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3538     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3539     if (Block1 != Block2)
3540       return Block1 ? ImplicitConversionSequence::Worse
3541                     : ImplicitConversionSequence::Better;
3542   }
3543 
3544   return ImplicitConversionSequence::Indistinguishable;
3545 }
3546 
3547 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3548     const ImplicitConversionSequence &ICS) {
3549   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3550          (ICS.isUserDefined() &&
3551           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3552 }
3553 
3554 /// CompareImplicitConversionSequences - Compare two implicit
3555 /// conversion sequences to determine whether one is better than the
3556 /// other or if they are indistinguishable (C++ 13.3.3.2).
3557 static ImplicitConversionSequence::CompareKind
3558 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3559                                    const ImplicitConversionSequence& ICS1,
3560                                    const ImplicitConversionSequence& ICS2)
3561 {
3562   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3563   // conversion sequences (as defined in 13.3.3.1)
3564   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3565   //      conversion sequence than a user-defined conversion sequence or
3566   //      an ellipsis conversion sequence, and
3567   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3568   //      conversion sequence than an ellipsis conversion sequence
3569   //      (13.3.3.1.3).
3570   //
3571   // C++0x [over.best.ics]p10:
3572   //   For the purpose of ranking implicit conversion sequences as
3573   //   described in 13.3.3.2, the ambiguous conversion sequence is
3574   //   treated as a user-defined sequence that is indistinguishable
3575   //   from any other user-defined conversion sequence.
3576 
3577   // String literal to 'char *' conversion has been deprecated in C++03. It has
3578   // been removed from C++11. We still accept this conversion, if it happens at
3579   // the best viable function. Otherwise, this conversion is considered worse
3580   // than ellipsis conversion. Consider this as an extension; this is not in the
3581   // standard. For example:
3582   //
3583   // int &f(...);    // #1
3584   // void f(char*);  // #2
3585   // void g() { int &r = f("foo"); }
3586   //
3587   // In C++03, we pick #2 as the best viable function.
3588   // In C++11, we pick #1 as the best viable function, because ellipsis
3589   // conversion is better than string-literal to char* conversion (since there
3590   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3591   // convert arguments, #2 would be the best viable function in C++11.
3592   // If the best viable function has this conversion, a warning will be issued
3593   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3594 
3595   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3596       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3597       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3598     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3599                ? ImplicitConversionSequence::Worse
3600                : ImplicitConversionSequence::Better;
3601 
3602   if (ICS1.getKindRank() < ICS2.getKindRank())
3603     return ImplicitConversionSequence::Better;
3604   if (ICS2.getKindRank() < ICS1.getKindRank())
3605     return ImplicitConversionSequence::Worse;
3606 
3607   // The following checks require both conversion sequences to be of
3608   // the same kind.
3609   if (ICS1.getKind() != ICS2.getKind())
3610     return ImplicitConversionSequence::Indistinguishable;
3611 
3612   ImplicitConversionSequence::CompareKind Result =
3613       ImplicitConversionSequence::Indistinguishable;
3614 
3615   // Two implicit conversion sequences of the same form are
3616   // indistinguishable conversion sequences unless one of the
3617   // following rules apply: (C++ 13.3.3.2p3):
3618 
3619   // List-initialization sequence L1 is a better conversion sequence than
3620   // list-initialization sequence L2 if:
3621   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3622   //   if not that,
3623   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3624   //   and N1 is smaller than N2.,
3625   // even if one of the other rules in this paragraph would otherwise apply.
3626   if (!ICS1.isBad()) {
3627     if (ICS1.isStdInitializerListElement() &&
3628         !ICS2.isStdInitializerListElement())
3629       return ImplicitConversionSequence::Better;
3630     if (!ICS1.isStdInitializerListElement() &&
3631         ICS2.isStdInitializerListElement())
3632       return ImplicitConversionSequence::Worse;
3633   }
3634 
3635   if (ICS1.isStandard())
3636     // Standard conversion sequence S1 is a better conversion sequence than
3637     // standard conversion sequence S2 if [...]
3638     Result = CompareStandardConversionSequences(S, Loc,
3639                                                 ICS1.Standard, ICS2.Standard);
3640   else if (ICS1.isUserDefined()) {
3641     // User-defined conversion sequence U1 is a better conversion
3642     // sequence than another user-defined conversion sequence U2 if
3643     // they contain the same user-defined conversion function or
3644     // constructor and if the second standard conversion sequence of
3645     // U1 is better than the second standard conversion sequence of
3646     // U2 (C++ 13.3.3.2p3).
3647     if (ICS1.UserDefined.ConversionFunction ==
3648           ICS2.UserDefined.ConversionFunction)
3649       Result = CompareStandardConversionSequences(S, Loc,
3650                                                   ICS1.UserDefined.After,
3651                                                   ICS2.UserDefined.After);
3652     else
3653       Result = compareConversionFunctions(S,
3654                                           ICS1.UserDefined.ConversionFunction,
3655                                           ICS2.UserDefined.ConversionFunction);
3656   }
3657 
3658   return Result;
3659 }
3660 
3661 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3662 // determine if one is a proper subset of the other.
3663 static ImplicitConversionSequence::CompareKind
3664 compareStandardConversionSubsets(ASTContext &Context,
3665                                  const StandardConversionSequence& SCS1,
3666                                  const StandardConversionSequence& SCS2) {
3667   ImplicitConversionSequence::CompareKind Result
3668     = ImplicitConversionSequence::Indistinguishable;
3669 
3670   // the identity conversion sequence is considered to be a subsequence of
3671   // any non-identity conversion sequence
3672   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3673     return ImplicitConversionSequence::Better;
3674   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3675     return ImplicitConversionSequence::Worse;
3676 
3677   if (SCS1.Second != SCS2.Second) {
3678     if (SCS1.Second == ICK_Identity)
3679       Result = ImplicitConversionSequence::Better;
3680     else if (SCS2.Second == ICK_Identity)
3681       Result = ImplicitConversionSequence::Worse;
3682     else
3683       return ImplicitConversionSequence::Indistinguishable;
3684   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3685     return ImplicitConversionSequence::Indistinguishable;
3686 
3687   if (SCS1.Third == SCS2.Third) {
3688     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3689                              : ImplicitConversionSequence::Indistinguishable;
3690   }
3691 
3692   if (SCS1.Third == ICK_Identity)
3693     return Result == ImplicitConversionSequence::Worse
3694              ? ImplicitConversionSequence::Indistinguishable
3695              : ImplicitConversionSequence::Better;
3696 
3697   if (SCS2.Third == ICK_Identity)
3698     return Result == ImplicitConversionSequence::Better
3699              ? ImplicitConversionSequence::Indistinguishable
3700              : ImplicitConversionSequence::Worse;
3701 
3702   return ImplicitConversionSequence::Indistinguishable;
3703 }
3704 
3705 /// Determine whether one of the given reference bindings is better
3706 /// than the other based on what kind of bindings they are.
3707 static bool
3708 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3709                              const StandardConversionSequence &SCS2) {
3710   // C++0x [over.ics.rank]p3b4:
3711   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3712   //      implicit object parameter of a non-static member function declared
3713   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3714   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3715   //      lvalue reference to a function lvalue and S2 binds an rvalue
3716   //      reference*.
3717   //
3718   // FIXME: Rvalue references. We're going rogue with the above edits,
3719   // because the semantics in the current C++0x working paper (N3225 at the
3720   // time of this writing) break the standard definition of std::forward
3721   // and std::reference_wrapper when dealing with references to functions.
3722   // Proposed wording changes submitted to CWG for consideration.
3723   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3724       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3725     return false;
3726 
3727   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3728           SCS2.IsLvalueReference) ||
3729          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3730           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3731 }
3732 
3733 /// CompareStandardConversionSequences - Compare two standard
3734 /// conversion sequences to determine whether one is better than the
3735 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3736 static ImplicitConversionSequence::CompareKind
3737 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3738                                    const StandardConversionSequence& SCS1,
3739                                    const StandardConversionSequence& SCS2)
3740 {
3741   // Standard conversion sequence S1 is a better conversion sequence
3742   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3743 
3744   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3745   //     sequences in the canonical form defined by 13.3.3.1.1,
3746   //     excluding any Lvalue Transformation; the identity conversion
3747   //     sequence is considered to be a subsequence of any
3748   //     non-identity conversion sequence) or, if not that,
3749   if (ImplicitConversionSequence::CompareKind CK
3750         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3751     return CK;
3752 
3753   //  -- the rank of S1 is better than the rank of S2 (by the rules
3754   //     defined below), or, if not that,
3755   ImplicitConversionRank Rank1 = SCS1.getRank();
3756   ImplicitConversionRank Rank2 = SCS2.getRank();
3757   if (Rank1 < Rank2)
3758     return ImplicitConversionSequence::Better;
3759   else if (Rank2 < Rank1)
3760     return ImplicitConversionSequence::Worse;
3761 
3762   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3763   // are indistinguishable unless one of the following rules
3764   // applies:
3765 
3766   //   A conversion that is not a conversion of a pointer, or
3767   //   pointer to member, to bool is better than another conversion
3768   //   that is such a conversion.
3769   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3770     return SCS2.isPointerConversionToBool()
3771              ? ImplicitConversionSequence::Better
3772              : ImplicitConversionSequence::Worse;
3773 
3774   // C++ [over.ics.rank]p4b2:
3775   //
3776   //   If class B is derived directly or indirectly from class A,
3777   //   conversion of B* to A* is better than conversion of B* to
3778   //   void*, and conversion of A* to void* is better than conversion
3779   //   of B* to void*.
3780   bool SCS1ConvertsToVoid
3781     = SCS1.isPointerConversionToVoidPointer(S.Context);
3782   bool SCS2ConvertsToVoid
3783     = SCS2.isPointerConversionToVoidPointer(S.Context);
3784   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3785     // Exactly one of the conversion sequences is a conversion to
3786     // a void pointer; it's the worse conversion.
3787     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3788                               : ImplicitConversionSequence::Worse;
3789   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3790     // Neither conversion sequence converts to a void pointer; compare
3791     // their derived-to-base conversions.
3792     if (ImplicitConversionSequence::CompareKind DerivedCK
3793           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3794       return DerivedCK;
3795   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3796              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3797     // Both conversion sequences are conversions to void
3798     // pointers. Compare the source types to determine if there's an
3799     // inheritance relationship in their sources.
3800     QualType FromType1 = SCS1.getFromType();
3801     QualType FromType2 = SCS2.getFromType();
3802 
3803     // Adjust the types we're converting from via the array-to-pointer
3804     // conversion, if we need to.
3805     if (SCS1.First == ICK_Array_To_Pointer)
3806       FromType1 = S.Context.getArrayDecayedType(FromType1);
3807     if (SCS2.First == ICK_Array_To_Pointer)
3808       FromType2 = S.Context.getArrayDecayedType(FromType2);
3809 
3810     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3811     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3812 
3813     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3814       return ImplicitConversionSequence::Better;
3815     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3816       return ImplicitConversionSequence::Worse;
3817 
3818     // Objective-C++: If one interface is more specific than the
3819     // other, it is the better one.
3820     const ObjCObjectPointerType* FromObjCPtr1
3821       = FromType1->getAs<ObjCObjectPointerType>();
3822     const ObjCObjectPointerType* FromObjCPtr2
3823       = FromType2->getAs<ObjCObjectPointerType>();
3824     if (FromObjCPtr1 && FromObjCPtr2) {
3825       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3826                                                           FromObjCPtr2);
3827       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3828                                                            FromObjCPtr1);
3829       if (AssignLeft != AssignRight) {
3830         return AssignLeft? ImplicitConversionSequence::Better
3831                          : ImplicitConversionSequence::Worse;
3832       }
3833     }
3834   }
3835 
3836   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3837   // bullet 3).
3838   if (ImplicitConversionSequence::CompareKind QualCK
3839         = CompareQualificationConversions(S, SCS1, SCS2))
3840     return QualCK;
3841 
3842   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3843     // Check for a better reference binding based on the kind of bindings.
3844     if (isBetterReferenceBindingKind(SCS1, SCS2))
3845       return ImplicitConversionSequence::Better;
3846     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3847       return ImplicitConversionSequence::Worse;
3848 
3849     // C++ [over.ics.rank]p3b4:
3850     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3851     //      which the references refer are the same type except for
3852     //      top-level cv-qualifiers, and the type to which the reference
3853     //      initialized by S2 refers is more cv-qualified than the type
3854     //      to which the reference initialized by S1 refers.
3855     QualType T1 = SCS1.getToType(2);
3856     QualType T2 = SCS2.getToType(2);
3857     T1 = S.Context.getCanonicalType(T1);
3858     T2 = S.Context.getCanonicalType(T2);
3859     Qualifiers T1Quals, T2Quals;
3860     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3861     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3862     if (UnqualT1 == UnqualT2) {
3863       // Objective-C++ ARC: If the references refer to objects with different
3864       // lifetimes, prefer bindings that don't change lifetime.
3865       if (SCS1.ObjCLifetimeConversionBinding !=
3866                                           SCS2.ObjCLifetimeConversionBinding) {
3867         return SCS1.ObjCLifetimeConversionBinding
3868                                            ? ImplicitConversionSequence::Worse
3869                                            : ImplicitConversionSequence::Better;
3870       }
3871 
3872       // If the type is an array type, promote the element qualifiers to the
3873       // type for comparison.
3874       if (isa<ArrayType>(T1) && T1Quals)
3875         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3876       if (isa<ArrayType>(T2) && T2Quals)
3877         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3878       if (T2.isMoreQualifiedThan(T1))
3879         return ImplicitConversionSequence::Better;
3880       else if (T1.isMoreQualifiedThan(T2))
3881         return ImplicitConversionSequence::Worse;
3882     }
3883   }
3884 
3885   // In Microsoft mode, prefer an integral conversion to a
3886   // floating-to-integral conversion if the integral conversion
3887   // is between types of the same size.
3888   // For example:
3889   // void f(float);
3890   // void f(int);
3891   // int main {
3892   //    long a;
3893   //    f(a);
3894   // }
3895   // Here, MSVC will call f(int) instead of generating a compile error
3896   // as clang will do in standard mode.
3897   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3898       SCS2.Second == ICK_Floating_Integral &&
3899       S.Context.getTypeSize(SCS1.getFromType()) ==
3900           S.Context.getTypeSize(SCS1.getToType(2)))
3901     return ImplicitConversionSequence::Better;
3902 
3903   // Prefer a compatible vector conversion over a lax vector conversion
3904   // For example:
3905   //
3906   // typedef float __v4sf __attribute__((__vector_size__(16)));
3907   // void f(vector float);
3908   // void f(vector signed int);
3909   // int main() {
3910   //   __v4sf a;
3911   //   f(a);
3912   // }
3913   // Here, we'd like to choose f(vector float) and not
3914   // report an ambiguous call error
3915   if (SCS1.Second == ICK_Vector_Conversion &&
3916       SCS2.Second == ICK_Vector_Conversion) {
3917     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3918         SCS1.getFromType(), SCS1.getToType(2));
3919     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3920         SCS2.getFromType(), SCS2.getToType(2));
3921 
3922     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3923       return SCS1IsCompatibleVectorConversion
3924                  ? ImplicitConversionSequence::Better
3925                  : ImplicitConversionSequence::Worse;
3926   }
3927 
3928   return ImplicitConversionSequence::Indistinguishable;
3929 }
3930 
3931 /// CompareQualificationConversions - Compares two standard conversion
3932 /// sequences to determine whether they can be ranked based on their
3933 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3934 static ImplicitConversionSequence::CompareKind
3935 CompareQualificationConversions(Sema &S,
3936                                 const StandardConversionSequence& SCS1,
3937                                 const StandardConversionSequence& SCS2) {
3938   // C++ 13.3.3.2p3:
3939   //  -- S1 and S2 differ only in their qualification conversion and
3940   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3941   //     cv-qualification signature of type T1 is a proper subset of
3942   //     the cv-qualification signature of type T2, and S1 is not the
3943   //     deprecated string literal array-to-pointer conversion (4.2).
3944   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3945       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3946     return ImplicitConversionSequence::Indistinguishable;
3947 
3948   // FIXME: the example in the standard doesn't use a qualification
3949   // conversion (!)
3950   QualType T1 = SCS1.getToType(2);
3951   QualType T2 = SCS2.getToType(2);
3952   T1 = S.Context.getCanonicalType(T1);
3953   T2 = S.Context.getCanonicalType(T2);
3954   Qualifiers T1Quals, T2Quals;
3955   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3956   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3957 
3958   // If the types are the same, we won't learn anything by unwrapped
3959   // them.
3960   if (UnqualT1 == UnqualT2)
3961     return ImplicitConversionSequence::Indistinguishable;
3962 
3963   // If the type is an array type, promote the element qualifiers to the type
3964   // for comparison.
3965   if (isa<ArrayType>(T1) && T1Quals)
3966     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3967   if (isa<ArrayType>(T2) && T2Quals)
3968     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3969 
3970   ImplicitConversionSequence::CompareKind Result
3971     = ImplicitConversionSequence::Indistinguishable;
3972 
3973   // Objective-C++ ARC:
3974   //   Prefer qualification conversions not involving a change in lifetime
3975   //   to qualification conversions that do not change lifetime.
3976   if (SCS1.QualificationIncludesObjCLifetime !=
3977                                       SCS2.QualificationIncludesObjCLifetime) {
3978     Result = SCS1.QualificationIncludesObjCLifetime
3979                ? ImplicitConversionSequence::Worse
3980                : ImplicitConversionSequence::Better;
3981   }
3982 
3983   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
3984     // Within each iteration of the loop, we check the qualifiers to
3985     // determine if this still looks like a qualification
3986     // conversion. Then, if all is well, we unwrap one more level of
3987     // pointers or pointers-to-members and do it all again
3988     // until there are no more pointers or pointers-to-members left
3989     // to unwrap. This essentially mimics what
3990     // IsQualificationConversion does, but here we're checking for a
3991     // strict subset of qualifiers.
3992     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3993       // The qualifiers are the same, so this doesn't tell us anything
3994       // about how the sequences rank.
3995       ;
3996     else if (T2.isMoreQualifiedThan(T1)) {
3997       // T1 has fewer qualifiers, so it could be the better sequence.
3998       if (Result == ImplicitConversionSequence::Worse)
3999         // Neither has qualifiers that are a subset of the other's
4000         // qualifiers.
4001         return ImplicitConversionSequence::Indistinguishable;
4002 
4003       Result = ImplicitConversionSequence::Better;
4004     } else if (T1.isMoreQualifiedThan(T2)) {
4005       // T2 has fewer qualifiers, so it could be the better sequence.
4006       if (Result == ImplicitConversionSequence::Better)
4007         // Neither has qualifiers that are a subset of the other's
4008         // qualifiers.
4009         return ImplicitConversionSequence::Indistinguishable;
4010 
4011       Result = ImplicitConversionSequence::Worse;
4012     } else {
4013       // Qualifiers are disjoint.
4014       return ImplicitConversionSequence::Indistinguishable;
4015     }
4016 
4017     // If the types after this point are equivalent, we're done.
4018     if (S.Context.hasSameUnqualifiedType(T1, T2))
4019       break;
4020   }
4021 
4022   // Check that the winning standard conversion sequence isn't using
4023   // the deprecated string literal array to pointer conversion.
4024   switch (Result) {
4025   case ImplicitConversionSequence::Better:
4026     if (SCS1.DeprecatedStringLiteralToCharPtr)
4027       Result = ImplicitConversionSequence::Indistinguishable;
4028     break;
4029 
4030   case ImplicitConversionSequence::Indistinguishable:
4031     break;
4032 
4033   case ImplicitConversionSequence::Worse:
4034     if (SCS2.DeprecatedStringLiteralToCharPtr)
4035       Result = ImplicitConversionSequence::Indistinguishable;
4036     break;
4037   }
4038 
4039   return Result;
4040 }
4041 
4042 /// CompareDerivedToBaseConversions - Compares two standard conversion
4043 /// sequences to determine whether they can be ranked based on their
4044 /// various kinds of derived-to-base conversions (C++
4045 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4046 /// conversions between Objective-C interface types.
4047 static ImplicitConversionSequence::CompareKind
4048 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4049                                 const StandardConversionSequence& SCS1,
4050                                 const StandardConversionSequence& SCS2) {
4051   QualType FromType1 = SCS1.getFromType();
4052   QualType ToType1 = SCS1.getToType(1);
4053   QualType FromType2 = SCS2.getFromType();
4054   QualType ToType2 = SCS2.getToType(1);
4055 
4056   // Adjust the types we're converting from via the array-to-pointer
4057   // conversion, if we need to.
4058   if (SCS1.First == ICK_Array_To_Pointer)
4059     FromType1 = S.Context.getArrayDecayedType(FromType1);
4060   if (SCS2.First == ICK_Array_To_Pointer)
4061     FromType2 = S.Context.getArrayDecayedType(FromType2);
4062 
4063   // Canonicalize all of the types.
4064   FromType1 = S.Context.getCanonicalType(FromType1);
4065   ToType1 = S.Context.getCanonicalType(ToType1);
4066   FromType2 = S.Context.getCanonicalType(FromType2);
4067   ToType2 = S.Context.getCanonicalType(ToType2);
4068 
4069   // C++ [over.ics.rank]p4b3:
4070   //
4071   //   If class B is derived directly or indirectly from class A and
4072   //   class C is derived directly or indirectly from B,
4073   //
4074   // Compare based on pointer conversions.
4075   if (SCS1.Second == ICK_Pointer_Conversion &&
4076       SCS2.Second == ICK_Pointer_Conversion &&
4077       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4078       FromType1->isPointerType() && FromType2->isPointerType() &&
4079       ToType1->isPointerType() && ToType2->isPointerType()) {
4080     QualType FromPointee1
4081       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4082     QualType ToPointee1
4083       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4084     QualType FromPointee2
4085       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4086     QualType ToPointee2
4087       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4088 
4089     //   -- conversion of C* to B* is better than conversion of C* to A*,
4090     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4091       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4092         return ImplicitConversionSequence::Better;
4093       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4094         return ImplicitConversionSequence::Worse;
4095     }
4096 
4097     //   -- conversion of B* to A* is better than conversion of C* to A*,
4098     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4099       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4100         return ImplicitConversionSequence::Better;
4101       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4102         return ImplicitConversionSequence::Worse;
4103     }
4104   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4105              SCS2.Second == ICK_Pointer_Conversion) {
4106     const ObjCObjectPointerType *FromPtr1
4107       = FromType1->getAs<ObjCObjectPointerType>();
4108     const ObjCObjectPointerType *FromPtr2
4109       = FromType2->getAs<ObjCObjectPointerType>();
4110     const ObjCObjectPointerType *ToPtr1
4111       = ToType1->getAs<ObjCObjectPointerType>();
4112     const ObjCObjectPointerType *ToPtr2
4113       = ToType2->getAs<ObjCObjectPointerType>();
4114 
4115     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4116       // Apply the same conversion ranking rules for Objective-C pointer types
4117       // that we do for C++ pointers to class types. However, we employ the
4118       // Objective-C pseudo-subtyping relationship used for assignment of
4119       // Objective-C pointer types.
4120       bool FromAssignLeft
4121         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4122       bool FromAssignRight
4123         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4124       bool ToAssignLeft
4125         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4126       bool ToAssignRight
4127         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4128 
4129       // A conversion to an a non-id object pointer type or qualified 'id'
4130       // type is better than a conversion to 'id'.
4131       if (ToPtr1->isObjCIdType() &&
4132           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4133         return ImplicitConversionSequence::Worse;
4134       if (ToPtr2->isObjCIdType() &&
4135           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4136         return ImplicitConversionSequence::Better;
4137 
4138       // A conversion to a non-id object pointer type is better than a
4139       // conversion to a qualified 'id' type
4140       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4141         return ImplicitConversionSequence::Worse;
4142       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4143         return ImplicitConversionSequence::Better;
4144 
4145       // A conversion to an a non-Class object pointer type or qualified 'Class'
4146       // type is better than a conversion to 'Class'.
4147       if (ToPtr1->isObjCClassType() &&
4148           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4149         return ImplicitConversionSequence::Worse;
4150       if (ToPtr2->isObjCClassType() &&
4151           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4152         return ImplicitConversionSequence::Better;
4153 
4154       // A conversion to a non-Class object pointer type is better than a
4155       // conversion to a qualified 'Class' type.
4156       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4157         return ImplicitConversionSequence::Worse;
4158       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4159         return ImplicitConversionSequence::Better;
4160 
4161       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4162       if (S.Context.hasSameType(FromType1, FromType2) &&
4163           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4164           (ToAssignLeft != ToAssignRight)) {
4165         if (FromPtr1->isSpecialized()) {
4166           // "conversion of B<A> * to B * is better than conversion of B * to
4167           // C *.
4168           bool IsFirstSame =
4169               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4170           bool IsSecondSame =
4171               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4172           if (IsFirstSame) {
4173             if (!IsSecondSame)
4174               return ImplicitConversionSequence::Better;
4175           } else if (IsSecondSame)
4176             return ImplicitConversionSequence::Worse;
4177         }
4178         return ToAssignLeft? ImplicitConversionSequence::Worse
4179                            : ImplicitConversionSequence::Better;
4180       }
4181 
4182       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4183       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4184           (FromAssignLeft != FromAssignRight))
4185         return FromAssignLeft? ImplicitConversionSequence::Better
4186         : ImplicitConversionSequence::Worse;
4187     }
4188   }
4189 
4190   // Ranking of member-pointer types.
4191   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4192       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4193       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4194     const MemberPointerType * FromMemPointer1 =
4195                                         FromType1->getAs<MemberPointerType>();
4196     const MemberPointerType * ToMemPointer1 =
4197                                           ToType1->getAs<MemberPointerType>();
4198     const MemberPointerType * FromMemPointer2 =
4199                                           FromType2->getAs<MemberPointerType>();
4200     const MemberPointerType * ToMemPointer2 =
4201                                           ToType2->getAs<MemberPointerType>();
4202     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4203     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4204     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4205     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4206     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4207     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4208     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4209     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4210     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4211     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4212       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4213         return ImplicitConversionSequence::Worse;
4214       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4215         return ImplicitConversionSequence::Better;
4216     }
4217     // conversion of B::* to C::* is better than conversion of A::* to C::*
4218     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4219       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4220         return ImplicitConversionSequence::Better;
4221       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4222         return ImplicitConversionSequence::Worse;
4223     }
4224   }
4225 
4226   if (SCS1.Second == ICK_Derived_To_Base) {
4227     //   -- conversion of C to B is better than conversion of C to A,
4228     //   -- binding of an expression of type C to a reference of type
4229     //      B& is better than binding an expression of type C to a
4230     //      reference of type A&,
4231     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4232         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4233       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4234         return ImplicitConversionSequence::Better;
4235       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4236         return ImplicitConversionSequence::Worse;
4237     }
4238 
4239     //   -- conversion of B to A is better than conversion of C to A.
4240     //   -- binding of an expression of type B to a reference of type
4241     //      A& is better than binding an expression of type C to a
4242     //      reference of type A&,
4243     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4244         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4245       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4246         return ImplicitConversionSequence::Better;
4247       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4248         return ImplicitConversionSequence::Worse;
4249     }
4250   }
4251 
4252   return ImplicitConversionSequence::Indistinguishable;
4253 }
4254 
4255 /// Determine whether the given type is valid, e.g., it is not an invalid
4256 /// C++ class.
4257 static bool isTypeValid(QualType T) {
4258   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4259     return !Record->isInvalidDecl();
4260 
4261   return true;
4262 }
4263 
4264 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4265 /// determine whether they are reference-related,
4266 /// reference-compatible, reference-compatible with added
4267 /// qualification, or incompatible, for use in C++ initialization by
4268 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4269 /// type, and the first type (T1) is the pointee type of the reference
4270 /// type being initialized.
4271 Sema::ReferenceCompareResult
4272 Sema::CompareReferenceRelationship(SourceLocation Loc,
4273                                    QualType OrigT1, QualType OrigT2,
4274                                    bool &DerivedToBase,
4275                                    bool &ObjCConversion,
4276                                    bool &ObjCLifetimeConversion) {
4277   assert(!OrigT1->isReferenceType() &&
4278     "T1 must be the pointee type of the reference type");
4279   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4280 
4281   QualType T1 = Context.getCanonicalType(OrigT1);
4282   QualType T2 = Context.getCanonicalType(OrigT2);
4283   Qualifiers T1Quals, T2Quals;
4284   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4285   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4286 
4287   // C++ [dcl.init.ref]p4:
4288   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4289   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4290   //   T1 is a base class of T2.
4291   DerivedToBase = false;
4292   ObjCConversion = false;
4293   ObjCLifetimeConversion = false;
4294   QualType ConvertedT2;
4295   if (UnqualT1 == UnqualT2) {
4296     // Nothing to do.
4297   } else if (isCompleteType(Loc, OrigT2) &&
4298              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4299              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4300     DerivedToBase = true;
4301   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4302            UnqualT2->isObjCObjectOrInterfaceType() &&
4303            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4304     ObjCConversion = true;
4305   else if (UnqualT2->isFunctionType() &&
4306            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4307     // C++1z [dcl.init.ref]p4:
4308     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4309     //   function" and T1 is "function"
4310     //
4311     // We extend this to also apply to 'noreturn', so allow any function
4312     // conversion between function types.
4313     return Ref_Compatible;
4314   else
4315     return Ref_Incompatible;
4316 
4317   // At this point, we know that T1 and T2 are reference-related (at
4318   // least).
4319 
4320   // If the type is an array type, promote the element qualifiers to the type
4321   // for comparison.
4322   if (isa<ArrayType>(T1) && T1Quals)
4323     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4324   if (isa<ArrayType>(T2) && T2Quals)
4325     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4326 
4327   // C++ [dcl.init.ref]p4:
4328   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4329   //   reference-related to T2 and cv1 is the same cv-qualification
4330   //   as, or greater cv-qualification than, cv2. For purposes of
4331   //   overload resolution, cases for which cv1 is greater
4332   //   cv-qualification than cv2 are identified as
4333   //   reference-compatible with added qualification (see 13.3.3.2).
4334   //
4335   // Note that we also require equivalence of Objective-C GC and address-space
4336   // qualifiers when performing these computations, so that e.g., an int in
4337   // address space 1 is not reference-compatible with an int in address
4338   // space 2.
4339   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4340       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4341     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4342       ObjCLifetimeConversion = true;
4343 
4344     T1Quals.removeObjCLifetime();
4345     T2Quals.removeObjCLifetime();
4346   }
4347 
4348   // MS compiler ignores __unaligned qualifier for references; do the same.
4349   T1Quals.removeUnaligned();
4350   T2Quals.removeUnaligned();
4351 
4352   if (T1Quals.compatiblyIncludes(T2Quals))
4353     return Ref_Compatible;
4354   else
4355     return Ref_Related;
4356 }
4357 
4358 /// Look for a user-defined conversion to a value reference-compatible
4359 ///        with DeclType. Return true if something definite is found.
4360 static bool
4361 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4362                          QualType DeclType, SourceLocation DeclLoc,
4363                          Expr *Init, QualType T2, bool AllowRvalues,
4364                          bool AllowExplicit) {
4365   assert(T2->isRecordType() && "Can only find conversions of record types.");
4366   CXXRecordDecl *T2RecordDecl
4367     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4368 
4369   OverloadCandidateSet CandidateSet(
4370       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4371   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4372   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4373     NamedDecl *D = *I;
4374     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4375     if (isa<UsingShadowDecl>(D))
4376       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4377 
4378     FunctionTemplateDecl *ConvTemplate
4379       = dyn_cast<FunctionTemplateDecl>(D);
4380     CXXConversionDecl *Conv;
4381     if (ConvTemplate)
4382       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4383     else
4384       Conv = cast<CXXConversionDecl>(D);
4385 
4386     // If this is an explicit conversion, and we're not allowed to consider
4387     // explicit conversions, skip it.
4388     if (!AllowExplicit && Conv->isExplicit())
4389       continue;
4390 
4391     if (AllowRvalues) {
4392       bool DerivedToBase = false;
4393       bool ObjCConversion = false;
4394       bool ObjCLifetimeConversion = false;
4395 
4396       // If we are initializing an rvalue reference, don't permit conversion
4397       // functions that return lvalues.
4398       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4399         const ReferenceType *RefType
4400           = Conv->getConversionType()->getAs<LValueReferenceType>();
4401         if (RefType && !RefType->getPointeeType()->isFunctionType())
4402           continue;
4403       }
4404 
4405       if (!ConvTemplate &&
4406           S.CompareReferenceRelationship(
4407             DeclLoc,
4408             Conv->getConversionType().getNonReferenceType()
4409               .getUnqualifiedType(),
4410             DeclType.getNonReferenceType().getUnqualifiedType(),
4411             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4412           Sema::Ref_Incompatible)
4413         continue;
4414     } else {
4415       // If the conversion function doesn't return a reference type,
4416       // it can't be considered for this conversion. An rvalue reference
4417       // is only acceptable if its referencee is a function type.
4418 
4419       const ReferenceType *RefType =
4420         Conv->getConversionType()->getAs<ReferenceType>();
4421       if (!RefType ||
4422           (!RefType->isLValueReferenceType() &&
4423            !RefType->getPointeeType()->isFunctionType()))
4424         continue;
4425     }
4426 
4427     if (ConvTemplate)
4428       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4429                                        Init, DeclType, CandidateSet,
4430                                        /*AllowObjCConversionOnExplicit=*/false);
4431     else
4432       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4433                                DeclType, CandidateSet,
4434                                /*AllowObjCConversionOnExplicit=*/false);
4435   }
4436 
4437   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4438 
4439   OverloadCandidateSet::iterator Best;
4440   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4441   case OR_Success:
4442     // C++ [over.ics.ref]p1:
4443     //
4444     //   [...] If the parameter binds directly to the result of
4445     //   applying a conversion function to the argument
4446     //   expression, the implicit conversion sequence is a
4447     //   user-defined conversion sequence (13.3.3.1.2), with the
4448     //   second standard conversion sequence either an identity
4449     //   conversion or, if the conversion function returns an
4450     //   entity of a type that is a derived class of the parameter
4451     //   type, a derived-to-base Conversion.
4452     if (!Best->FinalConversion.DirectBinding)
4453       return false;
4454 
4455     ICS.setUserDefined();
4456     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4457     ICS.UserDefined.After = Best->FinalConversion;
4458     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4459     ICS.UserDefined.ConversionFunction = Best->Function;
4460     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4461     ICS.UserDefined.EllipsisConversion = false;
4462     assert(ICS.UserDefined.After.ReferenceBinding &&
4463            ICS.UserDefined.After.DirectBinding &&
4464            "Expected a direct reference binding!");
4465     return true;
4466 
4467   case OR_Ambiguous:
4468     ICS.setAmbiguous();
4469     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4470          Cand != CandidateSet.end(); ++Cand)
4471       if (Cand->Viable)
4472         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4473     return true;
4474 
4475   case OR_No_Viable_Function:
4476   case OR_Deleted:
4477     // There was no suitable conversion, or we found a deleted
4478     // conversion; continue with other checks.
4479     return false;
4480   }
4481 
4482   llvm_unreachable("Invalid OverloadResult!");
4483 }
4484 
4485 /// Compute an implicit conversion sequence for reference
4486 /// initialization.
4487 static ImplicitConversionSequence
4488 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4489                  SourceLocation DeclLoc,
4490                  bool SuppressUserConversions,
4491                  bool AllowExplicit) {
4492   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4493 
4494   // Most paths end in a failed conversion.
4495   ImplicitConversionSequence ICS;
4496   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4497 
4498   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4499   QualType T2 = Init->getType();
4500 
4501   // If the initializer is the address of an overloaded function, try
4502   // to resolve the overloaded function. If all goes well, T2 is the
4503   // type of the resulting function.
4504   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4505     DeclAccessPair Found;
4506     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4507                                                                 false, Found))
4508       T2 = Fn->getType();
4509   }
4510 
4511   // Compute some basic properties of the types and the initializer.
4512   bool isRValRef = DeclType->isRValueReferenceType();
4513   bool DerivedToBase = false;
4514   bool ObjCConversion = false;
4515   bool ObjCLifetimeConversion = false;
4516   Expr::Classification InitCategory = Init->Classify(S.Context);
4517   Sema::ReferenceCompareResult RefRelationship
4518     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4519                                      ObjCConversion, ObjCLifetimeConversion);
4520 
4521 
4522   // C++0x [dcl.init.ref]p5:
4523   //   A reference to type "cv1 T1" is initialized by an expression
4524   //   of type "cv2 T2" as follows:
4525 
4526   //     -- If reference is an lvalue reference and the initializer expression
4527   if (!isRValRef) {
4528     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4529     //        reference-compatible with "cv2 T2," or
4530     //
4531     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4532     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4533       // C++ [over.ics.ref]p1:
4534       //   When a parameter of reference type binds directly (8.5.3)
4535       //   to an argument expression, the implicit conversion sequence
4536       //   is the identity conversion, unless the argument expression
4537       //   has a type that is a derived class of the parameter type,
4538       //   in which case the implicit conversion sequence is a
4539       //   derived-to-base Conversion (13.3.3.1).
4540       ICS.setStandard();
4541       ICS.Standard.First = ICK_Identity;
4542       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4543                          : ObjCConversion? ICK_Compatible_Conversion
4544                          : ICK_Identity;
4545       ICS.Standard.Third = ICK_Identity;
4546       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4547       ICS.Standard.setToType(0, T2);
4548       ICS.Standard.setToType(1, T1);
4549       ICS.Standard.setToType(2, T1);
4550       ICS.Standard.ReferenceBinding = true;
4551       ICS.Standard.DirectBinding = true;
4552       ICS.Standard.IsLvalueReference = !isRValRef;
4553       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4554       ICS.Standard.BindsToRvalue = false;
4555       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4556       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4557       ICS.Standard.CopyConstructor = nullptr;
4558       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4559 
4560       // Nothing more to do: the inaccessibility/ambiguity check for
4561       // derived-to-base conversions is suppressed when we're
4562       // computing the implicit conversion sequence (C++
4563       // [over.best.ics]p2).
4564       return ICS;
4565     }
4566 
4567     //       -- has a class type (i.e., T2 is a class type), where T1 is
4568     //          not reference-related to T2, and can be implicitly
4569     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4570     //          is reference-compatible with "cv3 T3" 92) (this
4571     //          conversion is selected by enumerating the applicable
4572     //          conversion functions (13.3.1.6) and choosing the best
4573     //          one through overload resolution (13.3)),
4574     if (!SuppressUserConversions && T2->isRecordType() &&
4575         S.isCompleteType(DeclLoc, T2) &&
4576         RefRelationship == Sema::Ref_Incompatible) {
4577       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4578                                    Init, T2, /*AllowRvalues=*/false,
4579                                    AllowExplicit))
4580         return ICS;
4581     }
4582   }
4583 
4584   //     -- Otherwise, the reference shall be an lvalue reference to a
4585   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4586   //        shall be an rvalue reference.
4587   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4588     return ICS;
4589 
4590   //       -- If the initializer expression
4591   //
4592   //            -- is an xvalue, class prvalue, array prvalue or function
4593   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4594   if (RefRelationship == Sema::Ref_Compatible &&
4595       (InitCategory.isXValue() ||
4596        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4597        (InitCategory.isLValue() && T2->isFunctionType()))) {
4598     ICS.setStandard();
4599     ICS.Standard.First = ICK_Identity;
4600     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4601                       : ObjCConversion? ICK_Compatible_Conversion
4602                       : ICK_Identity;
4603     ICS.Standard.Third = ICK_Identity;
4604     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4605     ICS.Standard.setToType(0, T2);
4606     ICS.Standard.setToType(1, T1);
4607     ICS.Standard.setToType(2, T1);
4608     ICS.Standard.ReferenceBinding = true;
4609     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4610     // binding unless we're binding to a class prvalue.
4611     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4612     // allow the use of rvalue references in C++98/03 for the benefit of
4613     // standard library implementors; therefore, we need the xvalue check here.
4614     ICS.Standard.DirectBinding =
4615       S.getLangOpts().CPlusPlus11 ||
4616       !(InitCategory.isPRValue() || T2->isRecordType());
4617     ICS.Standard.IsLvalueReference = !isRValRef;
4618     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4619     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4620     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4621     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4622     ICS.Standard.CopyConstructor = nullptr;
4623     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4624     return ICS;
4625   }
4626 
4627   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4628   //               reference-related to T2, and can be implicitly converted to
4629   //               an xvalue, class prvalue, or function lvalue of type
4630   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4631   //               "cv3 T3",
4632   //
4633   //          then the reference is bound to the value of the initializer
4634   //          expression in the first case and to the result of the conversion
4635   //          in the second case (or, in either case, to an appropriate base
4636   //          class subobject).
4637   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4638       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4639       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4640                                Init, T2, /*AllowRvalues=*/true,
4641                                AllowExplicit)) {
4642     // In the second case, if the reference is an rvalue reference
4643     // and the second standard conversion sequence of the
4644     // user-defined conversion sequence includes an lvalue-to-rvalue
4645     // conversion, the program is ill-formed.
4646     if (ICS.isUserDefined() && isRValRef &&
4647         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4648       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4649 
4650     return ICS;
4651   }
4652 
4653   // A temporary of function type cannot be created; don't even try.
4654   if (T1->isFunctionType())
4655     return ICS;
4656 
4657   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4658   //          initialized from the initializer expression using the
4659   //          rules for a non-reference copy initialization (8.5). The
4660   //          reference is then bound to the temporary. If T1 is
4661   //          reference-related to T2, cv1 must be the same
4662   //          cv-qualification as, or greater cv-qualification than,
4663   //          cv2; otherwise, the program is ill-formed.
4664   if (RefRelationship == Sema::Ref_Related) {
4665     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4666     // we would be reference-compatible or reference-compatible with
4667     // added qualification. But that wasn't the case, so the reference
4668     // initialization fails.
4669     //
4670     // Note that we only want to check address spaces and cvr-qualifiers here.
4671     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4672     Qualifiers T1Quals = T1.getQualifiers();
4673     Qualifiers T2Quals = T2.getQualifiers();
4674     T1Quals.removeObjCGCAttr();
4675     T1Quals.removeObjCLifetime();
4676     T2Quals.removeObjCGCAttr();
4677     T2Quals.removeObjCLifetime();
4678     // MS compiler ignores __unaligned qualifier for references; do the same.
4679     T1Quals.removeUnaligned();
4680     T2Quals.removeUnaligned();
4681     if (!T1Quals.compatiblyIncludes(T2Quals))
4682       return ICS;
4683   }
4684 
4685   // If at least one of the types is a class type, the types are not
4686   // related, and we aren't allowed any user conversions, the
4687   // reference binding fails. This case is important for breaking
4688   // recursion, since TryImplicitConversion below will attempt to
4689   // create a temporary through the use of a copy constructor.
4690   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4691       (T1->isRecordType() || T2->isRecordType()))
4692     return ICS;
4693 
4694   // If T1 is reference-related to T2 and the reference is an rvalue
4695   // reference, the initializer expression shall not be an lvalue.
4696   if (RefRelationship >= Sema::Ref_Related &&
4697       isRValRef && Init->Classify(S.Context).isLValue())
4698     return ICS;
4699 
4700   // C++ [over.ics.ref]p2:
4701   //   When a parameter of reference type is not bound directly to
4702   //   an argument expression, the conversion sequence is the one
4703   //   required to convert the argument expression to the
4704   //   underlying type of the reference according to
4705   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4706   //   to copy-initializing a temporary of the underlying type with
4707   //   the argument expression. Any difference in top-level
4708   //   cv-qualification is subsumed by the initialization itself
4709   //   and does not constitute a conversion.
4710   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4711                               /*AllowExplicit=*/false,
4712                               /*InOverloadResolution=*/false,
4713                               /*CStyle=*/false,
4714                               /*AllowObjCWritebackConversion=*/false,
4715                               /*AllowObjCConversionOnExplicit=*/false);
4716 
4717   // Of course, that's still a reference binding.
4718   if (ICS.isStandard()) {
4719     ICS.Standard.ReferenceBinding = true;
4720     ICS.Standard.IsLvalueReference = !isRValRef;
4721     ICS.Standard.BindsToFunctionLvalue = false;
4722     ICS.Standard.BindsToRvalue = true;
4723     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4724     ICS.Standard.ObjCLifetimeConversionBinding = false;
4725   } else if (ICS.isUserDefined()) {
4726     const ReferenceType *LValRefType =
4727         ICS.UserDefined.ConversionFunction->getReturnType()
4728             ->getAs<LValueReferenceType>();
4729 
4730     // C++ [over.ics.ref]p3:
4731     //   Except for an implicit object parameter, for which see 13.3.1, a
4732     //   standard conversion sequence cannot be formed if it requires [...]
4733     //   binding an rvalue reference to an lvalue other than a function
4734     //   lvalue.
4735     // Note that the function case is not possible here.
4736     if (DeclType->isRValueReferenceType() && LValRefType) {
4737       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4738       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4739       // reference to an rvalue!
4740       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4741       return ICS;
4742     }
4743 
4744     ICS.UserDefined.After.ReferenceBinding = true;
4745     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4746     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4747     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4748     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4749     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4750   }
4751 
4752   return ICS;
4753 }
4754 
4755 static ImplicitConversionSequence
4756 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4757                       bool SuppressUserConversions,
4758                       bool InOverloadResolution,
4759                       bool AllowObjCWritebackConversion,
4760                       bool AllowExplicit = false);
4761 
4762 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4763 /// initializer list From.
4764 static ImplicitConversionSequence
4765 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4766                   bool SuppressUserConversions,
4767                   bool InOverloadResolution,
4768                   bool AllowObjCWritebackConversion) {
4769   // C++11 [over.ics.list]p1:
4770   //   When an argument is an initializer list, it is not an expression and
4771   //   special rules apply for converting it to a parameter type.
4772 
4773   ImplicitConversionSequence Result;
4774   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4775 
4776   // We need a complete type for what follows. Incomplete types can never be
4777   // initialized from init lists.
4778   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4779     return Result;
4780 
4781   // Per DR1467:
4782   //   If the parameter type is a class X and the initializer list has a single
4783   //   element of type cv U, where U is X or a class derived from X, the
4784   //   implicit conversion sequence is the one required to convert the element
4785   //   to the parameter type.
4786   //
4787   //   Otherwise, if the parameter type is a character array [... ]
4788   //   and the initializer list has a single element that is an
4789   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4790   //   implicit conversion sequence is the identity conversion.
4791   if (From->getNumInits() == 1) {
4792     if (ToType->isRecordType()) {
4793       QualType InitType = From->getInit(0)->getType();
4794       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4795           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4796         return TryCopyInitialization(S, From->getInit(0), ToType,
4797                                      SuppressUserConversions,
4798                                      InOverloadResolution,
4799                                      AllowObjCWritebackConversion);
4800     }
4801     // FIXME: Check the other conditions here: array of character type,
4802     // initializer is a string literal.
4803     if (ToType->isArrayType()) {
4804       InitializedEntity Entity =
4805         InitializedEntity::InitializeParameter(S.Context, ToType,
4806                                                /*Consumed=*/false);
4807       if (S.CanPerformCopyInitialization(Entity, From)) {
4808         Result.setStandard();
4809         Result.Standard.setAsIdentityConversion();
4810         Result.Standard.setFromType(ToType);
4811         Result.Standard.setAllToTypes(ToType);
4812         return Result;
4813       }
4814     }
4815   }
4816 
4817   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4818   // C++11 [over.ics.list]p2:
4819   //   If the parameter type is std::initializer_list<X> or "array of X" and
4820   //   all the elements can be implicitly converted to X, the implicit
4821   //   conversion sequence is the worst conversion necessary to convert an
4822   //   element of the list to X.
4823   //
4824   // C++14 [over.ics.list]p3:
4825   //   Otherwise, if the parameter type is "array of N X", if the initializer
4826   //   list has exactly N elements or if it has fewer than N elements and X is
4827   //   default-constructible, and if all the elements of the initializer list
4828   //   can be implicitly converted to X, the implicit conversion sequence is
4829   //   the worst conversion necessary to convert an element of the list to X.
4830   //
4831   // FIXME: We're missing a lot of these checks.
4832   bool toStdInitializerList = false;
4833   QualType X;
4834   if (ToType->isArrayType())
4835     X = S.Context.getAsArrayType(ToType)->getElementType();
4836   else
4837     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4838   if (!X.isNull()) {
4839     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4840       Expr *Init = From->getInit(i);
4841       ImplicitConversionSequence ICS =
4842           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4843                                 InOverloadResolution,
4844                                 AllowObjCWritebackConversion);
4845       // If a single element isn't convertible, fail.
4846       if (ICS.isBad()) {
4847         Result = ICS;
4848         break;
4849       }
4850       // Otherwise, look for the worst conversion.
4851       if (Result.isBad() || CompareImplicitConversionSequences(
4852                                 S, From->getBeginLoc(), ICS, Result) ==
4853                                 ImplicitConversionSequence::Worse)
4854         Result = ICS;
4855     }
4856 
4857     // For an empty list, we won't have computed any conversion sequence.
4858     // Introduce the identity conversion sequence.
4859     if (From->getNumInits() == 0) {
4860       Result.setStandard();
4861       Result.Standard.setAsIdentityConversion();
4862       Result.Standard.setFromType(ToType);
4863       Result.Standard.setAllToTypes(ToType);
4864     }
4865 
4866     Result.setStdInitializerListElement(toStdInitializerList);
4867     return Result;
4868   }
4869 
4870   // C++14 [over.ics.list]p4:
4871   // C++11 [over.ics.list]p3:
4872   //   Otherwise, if the parameter is a non-aggregate class X and overload
4873   //   resolution chooses a single best constructor [...] the implicit
4874   //   conversion sequence is a user-defined conversion sequence. If multiple
4875   //   constructors are viable but none is better than the others, the
4876   //   implicit conversion sequence is a user-defined conversion sequence.
4877   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4878     // This function can deal with initializer lists.
4879     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4880                                     /*AllowExplicit=*/false,
4881                                     InOverloadResolution, /*CStyle=*/false,
4882                                     AllowObjCWritebackConversion,
4883                                     /*AllowObjCConversionOnExplicit=*/false);
4884   }
4885 
4886   // C++14 [over.ics.list]p5:
4887   // C++11 [over.ics.list]p4:
4888   //   Otherwise, if the parameter has an aggregate type which can be
4889   //   initialized from the initializer list [...] the implicit conversion
4890   //   sequence is a user-defined conversion sequence.
4891   if (ToType->isAggregateType()) {
4892     // Type is an aggregate, argument is an init list. At this point it comes
4893     // down to checking whether the initialization works.
4894     // FIXME: Find out whether this parameter is consumed or not.
4895     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4896     // need to call into the initialization code here; overload resolution
4897     // should not be doing that.
4898     InitializedEntity Entity =
4899         InitializedEntity::InitializeParameter(S.Context, ToType,
4900                                                /*Consumed=*/false);
4901     if (S.CanPerformCopyInitialization(Entity, From)) {
4902       Result.setUserDefined();
4903       Result.UserDefined.Before.setAsIdentityConversion();
4904       // Initializer lists don't have a type.
4905       Result.UserDefined.Before.setFromType(QualType());
4906       Result.UserDefined.Before.setAllToTypes(QualType());
4907 
4908       Result.UserDefined.After.setAsIdentityConversion();
4909       Result.UserDefined.After.setFromType(ToType);
4910       Result.UserDefined.After.setAllToTypes(ToType);
4911       Result.UserDefined.ConversionFunction = nullptr;
4912     }
4913     return Result;
4914   }
4915 
4916   // C++14 [over.ics.list]p6:
4917   // C++11 [over.ics.list]p5:
4918   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4919   if (ToType->isReferenceType()) {
4920     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4921     // mention initializer lists in any way. So we go by what list-
4922     // initialization would do and try to extrapolate from that.
4923 
4924     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4925 
4926     // If the initializer list has a single element that is reference-related
4927     // to the parameter type, we initialize the reference from that.
4928     if (From->getNumInits() == 1) {
4929       Expr *Init = From->getInit(0);
4930 
4931       QualType T2 = Init->getType();
4932 
4933       // If the initializer is the address of an overloaded function, try
4934       // to resolve the overloaded function. If all goes well, T2 is the
4935       // type of the resulting function.
4936       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4937         DeclAccessPair Found;
4938         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4939                                    Init, ToType, false, Found))
4940           T2 = Fn->getType();
4941       }
4942 
4943       // Compute some basic properties of the types and the initializer.
4944       bool dummy1 = false;
4945       bool dummy2 = false;
4946       bool dummy3 = false;
4947       Sema::ReferenceCompareResult RefRelationship =
4948           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4949                                          dummy2, dummy3);
4950 
4951       if (RefRelationship >= Sema::Ref_Related) {
4952         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4953                                 SuppressUserConversions,
4954                                 /*AllowExplicit=*/false);
4955       }
4956     }
4957 
4958     // Otherwise, we bind the reference to a temporary created from the
4959     // initializer list.
4960     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4961                                InOverloadResolution,
4962                                AllowObjCWritebackConversion);
4963     if (Result.isFailure())
4964       return Result;
4965     assert(!Result.isEllipsis() &&
4966            "Sub-initialization cannot result in ellipsis conversion.");
4967 
4968     // Can we even bind to a temporary?
4969     if (ToType->isRValueReferenceType() ||
4970         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4971       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4972                                             Result.UserDefined.After;
4973       SCS.ReferenceBinding = true;
4974       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4975       SCS.BindsToRvalue = true;
4976       SCS.BindsToFunctionLvalue = false;
4977       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4978       SCS.ObjCLifetimeConversionBinding = false;
4979     } else
4980       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4981                     From, ToType);
4982     return Result;
4983   }
4984 
4985   // C++14 [over.ics.list]p7:
4986   // C++11 [over.ics.list]p6:
4987   //   Otherwise, if the parameter type is not a class:
4988   if (!ToType->isRecordType()) {
4989     //    - if the initializer list has one element that is not itself an
4990     //      initializer list, the implicit conversion sequence is the one
4991     //      required to convert the element to the parameter type.
4992     unsigned NumInits = From->getNumInits();
4993     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4994       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4995                                      SuppressUserConversions,
4996                                      InOverloadResolution,
4997                                      AllowObjCWritebackConversion);
4998     //    - if the initializer list has no elements, the implicit conversion
4999     //      sequence is the identity conversion.
5000     else if (NumInits == 0) {
5001       Result.setStandard();
5002       Result.Standard.setAsIdentityConversion();
5003       Result.Standard.setFromType(ToType);
5004       Result.Standard.setAllToTypes(ToType);
5005     }
5006     return Result;
5007   }
5008 
5009   // C++14 [over.ics.list]p8:
5010   // C++11 [over.ics.list]p7:
5011   //   In all cases other than those enumerated above, no conversion is possible
5012   return Result;
5013 }
5014 
5015 /// TryCopyInitialization - Try to copy-initialize a value of type
5016 /// ToType from the expression From. Return the implicit conversion
5017 /// sequence required to pass this argument, which may be a bad
5018 /// conversion sequence (meaning that the argument cannot be passed to
5019 /// a parameter of this type). If @p SuppressUserConversions, then we
5020 /// do not permit any user-defined conversion sequences.
5021 static ImplicitConversionSequence
5022 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5023                       bool SuppressUserConversions,
5024                       bool InOverloadResolution,
5025                       bool AllowObjCWritebackConversion,
5026                       bool AllowExplicit) {
5027   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5028     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5029                              InOverloadResolution,AllowObjCWritebackConversion);
5030 
5031   if (ToType->isReferenceType())
5032     return TryReferenceInit(S, From, ToType,
5033                             /*FIXME:*/ From->getBeginLoc(),
5034                             SuppressUserConversions, AllowExplicit);
5035 
5036   return TryImplicitConversion(S, From, ToType,
5037                                SuppressUserConversions,
5038                                /*AllowExplicit=*/false,
5039                                InOverloadResolution,
5040                                /*CStyle=*/false,
5041                                AllowObjCWritebackConversion,
5042                                /*AllowObjCConversionOnExplicit=*/false);
5043 }
5044 
5045 static bool TryCopyInitialization(const CanQualType FromQTy,
5046                                   const CanQualType ToQTy,
5047                                   Sema &S,
5048                                   SourceLocation Loc,
5049                                   ExprValueKind FromVK) {
5050   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5051   ImplicitConversionSequence ICS =
5052     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5053 
5054   return !ICS.isBad();
5055 }
5056 
5057 /// TryObjectArgumentInitialization - Try to initialize the object
5058 /// parameter of the given member function (@c Method) from the
5059 /// expression @p From.
5060 static ImplicitConversionSequence
5061 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5062                                 Expr::Classification FromClassification,
5063                                 CXXMethodDecl *Method,
5064                                 CXXRecordDecl *ActingContext) {
5065   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5066   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5067   //                 const volatile object.
5068   Qualifiers Quals;
5069   if (isa<CXXDestructorDecl>(Method)) {
5070     Quals.addConst();
5071     Quals.addVolatile();
5072   } else {
5073     Quals = Method->getTypeQualifiers();
5074   }
5075 
5076   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5077 
5078   // Set up the conversion sequence as a "bad" conversion, to allow us
5079   // to exit early.
5080   ImplicitConversionSequence ICS;
5081 
5082   // We need to have an object of class type.
5083   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5084     FromType = PT->getPointeeType();
5085 
5086     // When we had a pointer, it's implicitly dereferenced, so we
5087     // better have an lvalue.
5088     assert(FromClassification.isLValue());
5089   }
5090 
5091   assert(FromType->isRecordType());
5092 
5093   // C++0x [over.match.funcs]p4:
5094   //   For non-static member functions, the type of the implicit object
5095   //   parameter is
5096   //
5097   //     - "lvalue reference to cv X" for functions declared without a
5098   //        ref-qualifier or with the & ref-qualifier
5099   //     - "rvalue reference to cv X" for functions declared with the &&
5100   //        ref-qualifier
5101   //
5102   // where X is the class of which the function is a member and cv is the
5103   // cv-qualification on the member function declaration.
5104   //
5105   // However, when finding an implicit conversion sequence for the argument, we
5106   // are not allowed to perform user-defined conversions
5107   // (C++ [over.match.funcs]p5). We perform a simplified version of
5108   // reference binding here, that allows class rvalues to bind to
5109   // non-constant references.
5110 
5111   // First check the qualifiers.
5112   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5113   if (ImplicitParamType.getCVRQualifiers()
5114                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5115       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5116     ICS.setBad(BadConversionSequence::bad_qualifiers,
5117                FromType, ImplicitParamType);
5118     return ICS;
5119   }
5120 
5121   // Check that we have either the same type or a derived type. It
5122   // affects the conversion rank.
5123   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5124   ImplicitConversionKind SecondKind;
5125   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5126     SecondKind = ICK_Identity;
5127   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5128     SecondKind = ICK_Derived_To_Base;
5129   else {
5130     ICS.setBad(BadConversionSequence::unrelated_class,
5131                FromType, ImplicitParamType);
5132     return ICS;
5133   }
5134 
5135   // Check the ref-qualifier.
5136   switch (Method->getRefQualifier()) {
5137   case RQ_None:
5138     // Do nothing; we don't care about lvalueness or rvalueness.
5139     break;
5140 
5141   case RQ_LValue:
5142     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5143       // non-const lvalue reference cannot bind to an rvalue
5144       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5145                  ImplicitParamType);
5146       return ICS;
5147     }
5148     break;
5149 
5150   case RQ_RValue:
5151     if (!FromClassification.isRValue()) {
5152       // rvalue reference cannot bind to an lvalue
5153       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5154                  ImplicitParamType);
5155       return ICS;
5156     }
5157     break;
5158   }
5159 
5160   // Success. Mark this as a reference binding.
5161   ICS.setStandard();
5162   ICS.Standard.setAsIdentityConversion();
5163   ICS.Standard.Second = SecondKind;
5164   ICS.Standard.setFromType(FromType);
5165   ICS.Standard.setAllToTypes(ImplicitParamType);
5166   ICS.Standard.ReferenceBinding = true;
5167   ICS.Standard.DirectBinding = true;
5168   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5169   ICS.Standard.BindsToFunctionLvalue = false;
5170   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5171   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5172     = (Method->getRefQualifier() == RQ_None);
5173   return ICS;
5174 }
5175 
5176 /// PerformObjectArgumentInitialization - Perform initialization of
5177 /// the implicit object parameter for the given Method with the given
5178 /// expression.
5179 ExprResult
5180 Sema::PerformObjectArgumentInitialization(Expr *From,
5181                                           NestedNameSpecifier *Qualifier,
5182                                           NamedDecl *FoundDecl,
5183                                           CXXMethodDecl *Method) {
5184   QualType FromRecordType, DestType;
5185   QualType ImplicitParamRecordType  =
5186     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5187 
5188   Expr::Classification FromClassification;
5189   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5190     FromRecordType = PT->getPointeeType();
5191     DestType = Method->getThisType(Context);
5192     FromClassification = Expr::Classification::makeSimpleLValue();
5193   } else {
5194     FromRecordType = From->getType();
5195     DestType = ImplicitParamRecordType;
5196     FromClassification = From->Classify(Context);
5197 
5198     // When performing member access on an rvalue, materialize a temporary.
5199     if (From->isRValue()) {
5200       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5201                                             Method->getRefQualifier() !=
5202                                                 RefQualifierKind::RQ_RValue);
5203     }
5204   }
5205 
5206   // Note that we always use the true parent context when performing
5207   // the actual argument initialization.
5208   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5209       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5210       Method->getParent());
5211   if (ICS.isBad()) {
5212     switch (ICS.Bad.Kind) {
5213     case BadConversionSequence::bad_qualifiers: {
5214       Qualifiers FromQs = FromRecordType.getQualifiers();
5215       Qualifiers ToQs = DestType.getQualifiers();
5216       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5217       if (CVR) {
5218         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5219             << Method->getDeclName() << FromRecordType << (CVR - 1)
5220             << From->getSourceRange();
5221         Diag(Method->getLocation(), diag::note_previous_decl)
5222           << Method->getDeclName();
5223         return ExprError();
5224       }
5225       break;
5226     }
5227 
5228     case BadConversionSequence::lvalue_ref_to_rvalue:
5229     case BadConversionSequence::rvalue_ref_to_lvalue: {
5230       bool IsRValueQualified =
5231         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5232       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5233           << Method->getDeclName() << FromClassification.isRValue()
5234           << IsRValueQualified;
5235       Diag(Method->getLocation(), diag::note_previous_decl)
5236         << Method->getDeclName();
5237       return ExprError();
5238     }
5239 
5240     case BadConversionSequence::no_conversion:
5241     case BadConversionSequence::unrelated_class:
5242       break;
5243     }
5244 
5245     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5246            << ImplicitParamRecordType << FromRecordType
5247            << From->getSourceRange();
5248   }
5249 
5250   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5251     ExprResult FromRes =
5252       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5253     if (FromRes.isInvalid())
5254       return ExprError();
5255     From = FromRes.get();
5256   }
5257 
5258   if (!Context.hasSameType(From->getType(), DestType)) {
5259     if (From->getType().getAddressSpace() != DestType.getAddressSpace())
5260       From = ImpCastExprToType(From, DestType, CK_AddressSpaceConversion,
5261                              From->getValueKind()).get();
5262     else
5263       From = ImpCastExprToType(From, DestType, CK_NoOp,
5264                              From->getValueKind()).get();
5265   }
5266   return From;
5267 }
5268 
5269 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5270 /// expression From to bool (C++0x [conv]p3).
5271 static ImplicitConversionSequence
5272 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5273   return TryImplicitConversion(S, From, S.Context.BoolTy,
5274                                /*SuppressUserConversions=*/false,
5275                                /*AllowExplicit=*/true,
5276                                /*InOverloadResolution=*/false,
5277                                /*CStyle=*/false,
5278                                /*AllowObjCWritebackConversion=*/false,
5279                                /*AllowObjCConversionOnExplicit=*/false);
5280 }
5281 
5282 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5283 /// of the expression From to bool (C++0x [conv]p3).
5284 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5285   if (checkPlaceholderForOverload(*this, From))
5286     return ExprError();
5287 
5288   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5289   if (!ICS.isBad())
5290     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5291 
5292   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5293     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5294            << From->getType() << From->getSourceRange();
5295   return ExprError();
5296 }
5297 
5298 /// Check that the specified conversion is permitted in a converted constant
5299 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5300 /// is acceptable.
5301 static bool CheckConvertedConstantConversions(Sema &S,
5302                                               StandardConversionSequence &SCS) {
5303   // Since we know that the target type is an integral or unscoped enumeration
5304   // type, most conversion kinds are impossible. All possible First and Third
5305   // conversions are fine.
5306   switch (SCS.Second) {
5307   case ICK_Identity:
5308   case ICK_Function_Conversion:
5309   case ICK_Integral_Promotion:
5310   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5311   case ICK_Zero_Queue_Conversion:
5312     return true;
5313 
5314   case ICK_Boolean_Conversion:
5315     // Conversion from an integral or unscoped enumeration type to bool is
5316     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5317     // conversion, so we allow it in a converted constant expression.
5318     //
5319     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5320     // a lot of popular code. We should at least add a warning for this
5321     // (non-conforming) extension.
5322     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5323            SCS.getToType(2)->isBooleanType();
5324 
5325   case ICK_Pointer_Conversion:
5326   case ICK_Pointer_Member:
5327     // C++1z: null pointer conversions and null member pointer conversions are
5328     // only permitted if the source type is std::nullptr_t.
5329     return SCS.getFromType()->isNullPtrType();
5330 
5331   case ICK_Floating_Promotion:
5332   case ICK_Complex_Promotion:
5333   case ICK_Floating_Conversion:
5334   case ICK_Complex_Conversion:
5335   case ICK_Floating_Integral:
5336   case ICK_Compatible_Conversion:
5337   case ICK_Derived_To_Base:
5338   case ICK_Vector_Conversion:
5339   case ICK_Vector_Splat:
5340   case ICK_Complex_Real:
5341   case ICK_Block_Pointer_Conversion:
5342   case ICK_TransparentUnionConversion:
5343   case ICK_Writeback_Conversion:
5344   case ICK_Zero_Event_Conversion:
5345   case ICK_C_Only_Conversion:
5346   case ICK_Incompatible_Pointer_Conversion:
5347     return false;
5348 
5349   case ICK_Lvalue_To_Rvalue:
5350   case ICK_Array_To_Pointer:
5351   case ICK_Function_To_Pointer:
5352     llvm_unreachable("found a first conversion kind in Second");
5353 
5354   case ICK_Qualification:
5355     llvm_unreachable("found a third conversion kind in Second");
5356 
5357   case ICK_Num_Conversion_Kinds:
5358     break;
5359   }
5360 
5361   llvm_unreachable("unknown conversion kind");
5362 }
5363 
5364 /// CheckConvertedConstantExpression - Check that the expression From is a
5365 /// converted constant expression of type T, perform the conversion and produce
5366 /// the converted expression, per C++11 [expr.const]p3.
5367 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5368                                                    QualType T, APValue &Value,
5369                                                    Sema::CCEKind CCE,
5370                                                    bool RequireInt) {
5371   assert(S.getLangOpts().CPlusPlus11 &&
5372          "converted constant expression outside C++11");
5373 
5374   if (checkPlaceholderForOverload(S, From))
5375     return ExprError();
5376 
5377   // C++1z [expr.const]p3:
5378   //  A converted constant expression of type T is an expression,
5379   //  implicitly converted to type T, where the converted
5380   //  expression is a constant expression and the implicit conversion
5381   //  sequence contains only [... list of conversions ...].
5382   // C++1z [stmt.if]p2:
5383   //  If the if statement is of the form if constexpr, the value of the
5384   //  condition shall be a contextually converted constant expression of type
5385   //  bool.
5386   ImplicitConversionSequence ICS =
5387       CCE == Sema::CCEK_ConstexprIf
5388           ? TryContextuallyConvertToBool(S, From)
5389           : TryCopyInitialization(S, From, T,
5390                                   /*SuppressUserConversions=*/false,
5391                                   /*InOverloadResolution=*/false,
5392                                   /*AllowObjcWritebackConversion=*/false,
5393                                   /*AllowExplicit=*/false);
5394   StandardConversionSequence *SCS = nullptr;
5395   switch (ICS.getKind()) {
5396   case ImplicitConversionSequence::StandardConversion:
5397     SCS = &ICS.Standard;
5398     break;
5399   case ImplicitConversionSequence::UserDefinedConversion:
5400     // We are converting to a non-class type, so the Before sequence
5401     // must be trivial.
5402     SCS = &ICS.UserDefined.After;
5403     break;
5404   case ImplicitConversionSequence::AmbiguousConversion:
5405   case ImplicitConversionSequence::BadConversion:
5406     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5407       return S.Diag(From->getBeginLoc(),
5408                     diag::err_typecheck_converted_constant_expression)
5409              << From->getType() << From->getSourceRange() << T;
5410     return ExprError();
5411 
5412   case ImplicitConversionSequence::EllipsisConversion:
5413     llvm_unreachable("ellipsis conversion in converted constant expression");
5414   }
5415 
5416   // Check that we would only use permitted conversions.
5417   if (!CheckConvertedConstantConversions(S, *SCS)) {
5418     return S.Diag(From->getBeginLoc(),
5419                   diag::err_typecheck_converted_constant_expression_disallowed)
5420            << From->getType() << From->getSourceRange() << T;
5421   }
5422   // [...] and where the reference binding (if any) binds directly.
5423   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5424     return S.Diag(From->getBeginLoc(),
5425                   diag::err_typecheck_converted_constant_expression_indirect)
5426            << From->getType() << From->getSourceRange() << T;
5427   }
5428 
5429   ExprResult Result =
5430       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5431   if (Result.isInvalid())
5432     return Result;
5433 
5434   // Check for a narrowing implicit conversion.
5435   APValue PreNarrowingValue;
5436   QualType PreNarrowingType;
5437   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5438                                 PreNarrowingType)) {
5439   case NK_Dependent_Narrowing:
5440     // Implicit conversion to a narrower type, but the expression is
5441     // value-dependent so we can't tell whether it's actually narrowing.
5442   case NK_Variable_Narrowing:
5443     // Implicit conversion to a narrower type, and the value is not a constant
5444     // expression. We'll diagnose this in a moment.
5445   case NK_Not_Narrowing:
5446     break;
5447 
5448   case NK_Constant_Narrowing:
5449     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5450         << CCE << /*Constant*/ 1
5451         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5452     break;
5453 
5454   case NK_Type_Narrowing:
5455     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5456         << CCE << /*Constant*/ 0 << From->getType() << T;
5457     break;
5458   }
5459 
5460   if (Result.get()->isValueDependent()) {
5461     Value = APValue();
5462     return Result;
5463   }
5464 
5465   // Check the expression is a constant expression.
5466   SmallVector<PartialDiagnosticAt, 8> Notes;
5467   Expr::EvalResult Eval;
5468   Eval.Diag = &Notes;
5469   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5470                                    ? Expr::EvaluateForMangling
5471                                    : Expr::EvaluateForCodeGen;
5472 
5473   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5474       (RequireInt && !Eval.Val.isInt())) {
5475     // The expression can't be folded, so we can't keep it at this position in
5476     // the AST.
5477     Result = ExprError();
5478   } else {
5479     Value = Eval.Val;
5480 
5481     if (Notes.empty()) {
5482       // It's a constant expression.
5483       return ConstantExpr::Create(S.Context, Result.get());
5484     }
5485   }
5486 
5487   // It's not a constant expression. Produce an appropriate diagnostic.
5488   if (Notes.size() == 1 &&
5489       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5490     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5491   else {
5492     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5493         << CCE << From->getSourceRange();
5494     for (unsigned I = 0; I < Notes.size(); ++I)
5495       S.Diag(Notes[I].first, Notes[I].second);
5496   }
5497   return ExprError();
5498 }
5499 
5500 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5501                                                   APValue &Value, CCEKind CCE) {
5502   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5503 }
5504 
5505 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5506                                                   llvm::APSInt &Value,
5507                                                   CCEKind CCE) {
5508   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5509 
5510   APValue V;
5511   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5512   if (!R.isInvalid() && !R.get()->isValueDependent())
5513     Value = V.getInt();
5514   return R;
5515 }
5516 
5517 
5518 /// dropPointerConversions - If the given standard conversion sequence
5519 /// involves any pointer conversions, remove them.  This may change
5520 /// the result type of the conversion sequence.
5521 static void dropPointerConversion(StandardConversionSequence &SCS) {
5522   if (SCS.Second == ICK_Pointer_Conversion) {
5523     SCS.Second = ICK_Identity;
5524     SCS.Third = ICK_Identity;
5525     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5526   }
5527 }
5528 
5529 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5530 /// convert the expression From to an Objective-C pointer type.
5531 static ImplicitConversionSequence
5532 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5533   // Do an implicit conversion to 'id'.
5534   QualType Ty = S.Context.getObjCIdType();
5535   ImplicitConversionSequence ICS
5536     = TryImplicitConversion(S, From, Ty,
5537                             // FIXME: Are these flags correct?
5538                             /*SuppressUserConversions=*/false,
5539                             /*AllowExplicit=*/true,
5540                             /*InOverloadResolution=*/false,
5541                             /*CStyle=*/false,
5542                             /*AllowObjCWritebackConversion=*/false,
5543                             /*AllowObjCConversionOnExplicit=*/true);
5544 
5545   // Strip off any final conversions to 'id'.
5546   switch (ICS.getKind()) {
5547   case ImplicitConversionSequence::BadConversion:
5548   case ImplicitConversionSequence::AmbiguousConversion:
5549   case ImplicitConversionSequence::EllipsisConversion:
5550     break;
5551 
5552   case ImplicitConversionSequence::UserDefinedConversion:
5553     dropPointerConversion(ICS.UserDefined.After);
5554     break;
5555 
5556   case ImplicitConversionSequence::StandardConversion:
5557     dropPointerConversion(ICS.Standard);
5558     break;
5559   }
5560 
5561   return ICS;
5562 }
5563 
5564 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5565 /// conversion of the expression From to an Objective-C pointer type.
5566 /// Returns a valid but null ExprResult if no conversion sequence exists.
5567 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5568   if (checkPlaceholderForOverload(*this, From))
5569     return ExprError();
5570 
5571   QualType Ty = Context.getObjCIdType();
5572   ImplicitConversionSequence ICS =
5573     TryContextuallyConvertToObjCPointer(*this, From);
5574   if (!ICS.isBad())
5575     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5576   return ExprResult();
5577 }
5578 
5579 /// Determine whether the provided type is an integral type, or an enumeration
5580 /// type of a permitted flavor.
5581 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5582   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5583                                  : T->isIntegralOrUnscopedEnumerationType();
5584 }
5585 
5586 static ExprResult
5587 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5588                             Sema::ContextualImplicitConverter &Converter,
5589                             QualType T, UnresolvedSetImpl &ViableConversions) {
5590 
5591   if (Converter.Suppress)
5592     return ExprError();
5593 
5594   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5595   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5596     CXXConversionDecl *Conv =
5597         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5598     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5599     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5600   }
5601   return From;
5602 }
5603 
5604 static bool
5605 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5606                            Sema::ContextualImplicitConverter &Converter,
5607                            QualType T, bool HadMultipleCandidates,
5608                            UnresolvedSetImpl &ExplicitConversions) {
5609   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5610     DeclAccessPair Found = ExplicitConversions[0];
5611     CXXConversionDecl *Conversion =
5612         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5613 
5614     // The user probably meant to invoke the given explicit
5615     // conversion; use it.
5616     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5617     std::string TypeStr;
5618     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5619 
5620     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5621         << FixItHint::CreateInsertion(From->getBeginLoc(),
5622                                       "static_cast<" + TypeStr + ">(")
5623         << FixItHint::CreateInsertion(
5624                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5625     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5626 
5627     // If we aren't in a SFINAE context, build a call to the
5628     // explicit conversion function.
5629     if (SemaRef.isSFINAEContext())
5630       return true;
5631 
5632     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5633     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5634                                                        HadMultipleCandidates);
5635     if (Result.isInvalid())
5636       return true;
5637     // Record usage of conversion in an implicit cast.
5638     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5639                                     CK_UserDefinedConversion, Result.get(),
5640                                     nullptr, Result.get()->getValueKind());
5641   }
5642   return false;
5643 }
5644 
5645 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5646                              Sema::ContextualImplicitConverter &Converter,
5647                              QualType T, bool HadMultipleCandidates,
5648                              DeclAccessPair &Found) {
5649   CXXConversionDecl *Conversion =
5650       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5651   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5652 
5653   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5654   if (!Converter.SuppressConversion) {
5655     if (SemaRef.isSFINAEContext())
5656       return true;
5657 
5658     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5659         << From->getSourceRange();
5660   }
5661 
5662   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5663                                                      HadMultipleCandidates);
5664   if (Result.isInvalid())
5665     return true;
5666   // Record usage of conversion in an implicit cast.
5667   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5668                                   CK_UserDefinedConversion, Result.get(),
5669                                   nullptr, Result.get()->getValueKind());
5670   return false;
5671 }
5672 
5673 static ExprResult finishContextualImplicitConversion(
5674     Sema &SemaRef, SourceLocation Loc, Expr *From,
5675     Sema::ContextualImplicitConverter &Converter) {
5676   if (!Converter.match(From->getType()) && !Converter.Suppress)
5677     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5678         << From->getSourceRange();
5679 
5680   return SemaRef.DefaultLvalueConversion(From);
5681 }
5682 
5683 static void
5684 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5685                                   UnresolvedSetImpl &ViableConversions,
5686                                   OverloadCandidateSet &CandidateSet) {
5687   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5688     DeclAccessPair FoundDecl = ViableConversions[I];
5689     NamedDecl *D = FoundDecl.getDecl();
5690     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5691     if (isa<UsingShadowDecl>(D))
5692       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5693 
5694     CXXConversionDecl *Conv;
5695     FunctionTemplateDecl *ConvTemplate;
5696     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5697       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5698     else
5699       Conv = cast<CXXConversionDecl>(D);
5700 
5701     if (ConvTemplate)
5702       SemaRef.AddTemplateConversionCandidate(
5703         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5704         /*AllowObjCConversionOnExplicit=*/false);
5705     else
5706       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5707                                      ToType, CandidateSet,
5708                                      /*AllowObjCConversionOnExplicit=*/false);
5709   }
5710 }
5711 
5712 /// Attempt to convert the given expression to a type which is accepted
5713 /// by the given converter.
5714 ///
5715 /// This routine will attempt to convert an expression of class type to a
5716 /// type accepted by the specified converter. In C++11 and before, the class
5717 /// must have a single non-explicit conversion function converting to a matching
5718 /// type. In C++1y, there can be multiple such conversion functions, but only
5719 /// one target type.
5720 ///
5721 /// \param Loc The source location of the construct that requires the
5722 /// conversion.
5723 ///
5724 /// \param From The expression we're converting from.
5725 ///
5726 /// \param Converter Used to control and diagnose the conversion process.
5727 ///
5728 /// \returns The expression, converted to an integral or enumeration type if
5729 /// successful.
5730 ExprResult Sema::PerformContextualImplicitConversion(
5731     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5732   // We can't perform any more checking for type-dependent expressions.
5733   if (From->isTypeDependent())
5734     return From;
5735 
5736   // Process placeholders immediately.
5737   if (From->hasPlaceholderType()) {
5738     ExprResult result = CheckPlaceholderExpr(From);
5739     if (result.isInvalid())
5740       return result;
5741     From = result.get();
5742   }
5743 
5744   // If the expression already has a matching type, we're golden.
5745   QualType T = From->getType();
5746   if (Converter.match(T))
5747     return DefaultLvalueConversion(From);
5748 
5749   // FIXME: Check for missing '()' if T is a function type?
5750 
5751   // We can only perform contextual implicit conversions on objects of class
5752   // type.
5753   const RecordType *RecordTy = T->getAs<RecordType>();
5754   if (!RecordTy || !getLangOpts().CPlusPlus) {
5755     if (!Converter.Suppress)
5756       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5757     return From;
5758   }
5759 
5760   // We must have a complete class type.
5761   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5762     ContextualImplicitConverter &Converter;
5763     Expr *From;
5764 
5765     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5766         : Converter(Converter), From(From) {}
5767 
5768     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5769       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5770     }
5771   } IncompleteDiagnoser(Converter, From);
5772 
5773   if (Converter.Suppress ? !isCompleteType(Loc, T)
5774                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5775     return From;
5776 
5777   // Look for a conversion to an integral or enumeration type.
5778   UnresolvedSet<4>
5779       ViableConversions; // These are *potentially* viable in C++1y.
5780   UnresolvedSet<4> ExplicitConversions;
5781   const auto &Conversions =
5782       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5783 
5784   bool HadMultipleCandidates =
5785       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5786 
5787   // To check that there is only one target type, in C++1y:
5788   QualType ToType;
5789   bool HasUniqueTargetType = true;
5790 
5791   // Collect explicit or viable (potentially in C++1y) conversions.
5792   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5793     NamedDecl *D = (*I)->getUnderlyingDecl();
5794     CXXConversionDecl *Conversion;
5795     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5796     if (ConvTemplate) {
5797       if (getLangOpts().CPlusPlus14)
5798         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5799       else
5800         continue; // C++11 does not consider conversion operator templates(?).
5801     } else
5802       Conversion = cast<CXXConversionDecl>(D);
5803 
5804     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5805            "Conversion operator templates are considered potentially "
5806            "viable in C++1y");
5807 
5808     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5809     if (Converter.match(CurToType) || ConvTemplate) {
5810 
5811       if (Conversion->isExplicit()) {
5812         // FIXME: For C++1y, do we need this restriction?
5813         // cf. diagnoseNoViableConversion()
5814         if (!ConvTemplate)
5815           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5816       } else {
5817         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5818           if (ToType.isNull())
5819             ToType = CurToType.getUnqualifiedType();
5820           else if (HasUniqueTargetType &&
5821                    (CurToType.getUnqualifiedType() != ToType))
5822             HasUniqueTargetType = false;
5823         }
5824         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5825       }
5826     }
5827   }
5828 
5829   if (getLangOpts().CPlusPlus14) {
5830     // C++1y [conv]p6:
5831     // ... An expression e of class type E appearing in such a context
5832     // is said to be contextually implicitly converted to a specified
5833     // type T and is well-formed if and only if e can be implicitly
5834     // converted to a type T that is determined as follows: E is searched
5835     // for conversion functions whose return type is cv T or reference to
5836     // cv T such that T is allowed by the context. There shall be
5837     // exactly one such T.
5838 
5839     // If no unique T is found:
5840     if (ToType.isNull()) {
5841       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5842                                      HadMultipleCandidates,
5843                                      ExplicitConversions))
5844         return ExprError();
5845       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5846     }
5847 
5848     // If more than one unique Ts are found:
5849     if (!HasUniqueTargetType)
5850       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5851                                          ViableConversions);
5852 
5853     // If one unique T is found:
5854     // First, build a candidate set from the previously recorded
5855     // potentially viable conversions.
5856     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5857     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5858                                       CandidateSet);
5859 
5860     // Then, perform overload resolution over the candidate set.
5861     OverloadCandidateSet::iterator Best;
5862     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5863     case OR_Success: {
5864       // Apply this conversion.
5865       DeclAccessPair Found =
5866           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5867       if (recordConversion(*this, Loc, From, Converter, T,
5868                            HadMultipleCandidates, Found))
5869         return ExprError();
5870       break;
5871     }
5872     case OR_Ambiguous:
5873       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5874                                          ViableConversions);
5875     case OR_No_Viable_Function:
5876       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5877                                      HadMultipleCandidates,
5878                                      ExplicitConversions))
5879         return ExprError();
5880       LLVM_FALLTHROUGH;
5881     case OR_Deleted:
5882       // We'll complain below about a non-integral condition type.
5883       break;
5884     }
5885   } else {
5886     switch (ViableConversions.size()) {
5887     case 0: {
5888       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5889                                      HadMultipleCandidates,
5890                                      ExplicitConversions))
5891         return ExprError();
5892 
5893       // We'll complain below about a non-integral condition type.
5894       break;
5895     }
5896     case 1: {
5897       // Apply this conversion.
5898       DeclAccessPair Found = ViableConversions[0];
5899       if (recordConversion(*this, Loc, From, Converter, T,
5900                            HadMultipleCandidates, Found))
5901         return ExprError();
5902       break;
5903     }
5904     default:
5905       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5906                                          ViableConversions);
5907     }
5908   }
5909 
5910   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5911 }
5912 
5913 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5914 /// an acceptable non-member overloaded operator for a call whose
5915 /// arguments have types T1 (and, if non-empty, T2). This routine
5916 /// implements the check in C++ [over.match.oper]p3b2 concerning
5917 /// enumeration types.
5918 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5919                                                    FunctionDecl *Fn,
5920                                                    ArrayRef<Expr *> Args) {
5921   QualType T1 = Args[0]->getType();
5922   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5923 
5924   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5925     return true;
5926 
5927   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5928     return true;
5929 
5930   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5931   if (Proto->getNumParams() < 1)
5932     return false;
5933 
5934   if (T1->isEnumeralType()) {
5935     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5936     if (Context.hasSameUnqualifiedType(T1, ArgType))
5937       return true;
5938   }
5939 
5940   if (Proto->getNumParams() < 2)
5941     return false;
5942 
5943   if (!T2.isNull() && T2->isEnumeralType()) {
5944     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5945     if (Context.hasSameUnqualifiedType(T2, ArgType))
5946       return true;
5947   }
5948 
5949   return false;
5950 }
5951 
5952 /// AddOverloadCandidate - Adds the given function to the set of
5953 /// candidate functions, using the given function call arguments.  If
5954 /// @p SuppressUserConversions, then don't allow user-defined
5955 /// conversions via constructors or conversion operators.
5956 ///
5957 /// \param PartialOverloading true if we are performing "partial" overloading
5958 /// based on an incomplete set of function arguments. This feature is used by
5959 /// code completion.
5960 void Sema::AddOverloadCandidate(FunctionDecl *Function,
5961                                 DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
5962                                 OverloadCandidateSet &CandidateSet,
5963                                 bool SuppressUserConversions,
5964                                 bool PartialOverloading, bool AllowExplicit,
5965                                 ADLCallKind IsADLCandidate,
5966                                 ConversionSequenceList EarlyConversions) {
5967   const FunctionProtoType *Proto
5968     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5969   assert(Proto && "Functions without a prototype cannot be overloaded");
5970   assert(!Function->getDescribedFunctionTemplate() &&
5971          "Use AddTemplateOverloadCandidate for function templates");
5972 
5973   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5974     if (!isa<CXXConstructorDecl>(Method)) {
5975       // If we get here, it's because we're calling a member function
5976       // that is named without a member access expression (e.g.,
5977       // "this->f") that was either written explicitly or created
5978       // implicitly. This can happen with a qualified call to a member
5979       // function, e.g., X::f(). We use an empty type for the implied
5980       // object argument (C++ [over.call.func]p3), and the acting context
5981       // is irrelevant.
5982       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5983                          Expr::Classification::makeSimpleLValue(), Args,
5984                          CandidateSet, SuppressUserConversions,
5985                          PartialOverloading, EarlyConversions);
5986       return;
5987     }
5988     // We treat a constructor like a non-member function, since its object
5989     // argument doesn't participate in overload resolution.
5990   }
5991 
5992   if (!CandidateSet.isNewCandidate(Function))
5993     return;
5994 
5995   // C++ [over.match.oper]p3:
5996   //   if no operand has a class type, only those non-member functions in the
5997   //   lookup set that have a first parameter of type T1 or "reference to
5998   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5999   //   is a right operand) a second parameter of type T2 or "reference to
6000   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6001   //   candidate functions.
6002   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6003       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6004     return;
6005 
6006   // C++11 [class.copy]p11: [DR1402]
6007   //   A defaulted move constructor that is defined as deleted is ignored by
6008   //   overload resolution.
6009   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6010   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6011       Constructor->isMoveConstructor())
6012     return;
6013 
6014   // Overload resolution is always an unevaluated context.
6015   EnterExpressionEvaluationContext Unevaluated(
6016       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6017 
6018   // Add this candidate
6019   OverloadCandidate &Candidate =
6020       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6021   Candidate.FoundDecl = FoundDecl;
6022   Candidate.Function = Function;
6023   Candidate.Viable = true;
6024   Candidate.IsSurrogate = false;
6025   Candidate.IsADLCandidate = IsADLCandidate;
6026   Candidate.IgnoreObjectArgument = false;
6027   Candidate.ExplicitCallArguments = Args.size();
6028 
6029   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6030       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6031     Candidate.Viable = false;
6032     Candidate.FailureKind = ovl_non_default_multiversion_function;
6033     return;
6034   }
6035 
6036   if (Constructor) {
6037     // C++ [class.copy]p3:
6038     //   A member function template is never instantiated to perform the copy
6039     //   of a class object to an object of its class type.
6040     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6041     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6042         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6043          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6044                        ClassType))) {
6045       Candidate.Viable = false;
6046       Candidate.FailureKind = ovl_fail_illegal_constructor;
6047       return;
6048     }
6049 
6050     // C++ [over.match.funcs]p8: (proposed DR resolution)
6051     //   A constructor inherited from class type C that has a first parameter
6052     //   of type "reference to P" (including such a constructor instantiated
6053     //   from a template) is excluded from the set of candidate functions when
6054     //   constructing an object of type cv D if the argument list has exactly
6055     //   one argument and D is reference-related to P and P is reference-related
6056     //   to C.
6057     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6058     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6059         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6060       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6061       QualType C = Context.getRecordType(Constructor->getParent());
6062       QualType D = Context.getRecordType(Shadow->getParent());
6063       SourceLocation Loc = Args.front()->getExprLoc();
6064       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6065           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6066         Candidate.Viable = false;
6067         Candidate.FailureKind = ovl_fail_inhctor_slice;
6068         return;
6069       }
6070     }
6071   }
6072 
6073   unsigned NumParams = Proto->getNumParams();
6074 
6075   // (C++ 13.3.2p2): A candidate function having fewer than m
6076   // parameters is viable only if it has an ellipsis in its parameter
6077   // list (8.3.5).
6078   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6079       !Proto->isVariadic()) {
6080     Candidate.Viable = false;
6081     Candidate.FailureKind = ovl_fail_too_many_arguments;
6082     return;
6083   }
6084 
6085   // (C++ 13.3.2p2): A candidate function having more than m parameters
6086   // is viable only if the (m+1)st parameter has a default argument
6087   // (8.3.6). For the purposes of overload resolution, the
6088   // parameter list is truncated on the right, so that there are
6089   // exactly m parameters.
6090   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6091   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6092     // Not enough arguments.
6093     Candidate.Viable = false;
6094     Candidate.FailureKind = ovl_fail_too_few_arguments;
6095     return;
6096   }
6097 
6098   // (CUDA B.1): Check for invalid calls between targets.
6099   if (getLangOpts().CUDA)
6100     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6101       // Skip the check for callers that are implicit members, because in this
6102       // case we may not yet know what the member's target is; the target is
6103       // inferred for the member automatically, based on the bases and fields of
6104       // the class.
6105       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6106         Candidate.Viable = false;
6107         Candidate.FailureKind = ovl_fail_bad_target;
6108         return;
6109       }
6110 
6111   // Determine the implicit conversion sequences for each of the
6112   // arguments.
6113   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6114     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6115       // We already formed a conversion sequence for this parameter during
6116       // template argument deduction.
6117     } else if (ArgIdx < NumParams) {
6118       // (C++ 13.3.2p3): for F to be a viable function, there shall
6119       // exist for each argument an implicit conversion sequence
6120       // (13.3.3.1) that converts that argument to the corresponding
6121       // parameter of F.
6122       QualType ParamType = Proto->getParamType(ArgIdx);
6123       Candidate.Conversions[ArgIdx]
6124         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6125                                 SuppressUserConversions,
6126                                 /*InOverloadResolution=*/true,
6127                                 /*AllowObjCWritebackConversion=*/
6128                                   getLangOpts().ObjCAutoRefCount,
6129                                 AllowExplicit);
6130       if (Candidate.Conversions[ArgIdx].isBad()) {
6131         Candidate.Viable = false;
6132         Candidate.FailureKind = ovl_fail_bad_conversion;
6133         return;
6134       }
6135     } else {
6136       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6137       // argument for which there is no corresponding parameter is
6138       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6139       Candidate.Conversions[ArgIdx].setEllipsis();
6140     }
6141   }
6142 
6143   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6144     Candidate.Viable = false;
6145     Candidate.FailureKind = ovl_fail_enable_if;
6146     Candidate.DeductionFailure.Data = FailedAttr;
6147     return;
6148   }
6149 
6150   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6151     Candidate.Viable = false;
6152     Candidate.FailureKind = ovl_fail_ext_disabled;
6153     return;
6154   }
6155 }
6156 
6157 ObjCMethodDecl *
6158 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6159                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6160   if (Methods.size() <= 1)
6161     return nullptr;
6162 
6163   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6164     bool Match = true;
6165     ObjCMethodDecl *Method = Methods[b];
6166     unsigned NumNamedArgs = Sel.getNumArgs();
6167     // Method might have more arguments than selector indicates. This is due
6168     // to addition of c-style arguments in method.
6169     if (Method->param_size() > NumNamedArgs)
6170       NumNamedArgs = Method->param_size();
6171     if (Args.size() < NumNamedArgs)
6172       continue;
6173 
6174     for (unsigned i = 0; i < NumNamedArgs; i++) {
6175       // We can't do any type-checking on a type-dependent argument.
6176       if (Args[i]->isTypeDependent()) {
6177         Match = false;
6178         break;
6179       }
6180 
6181       ParmVarDecl *param = Method->parameters()[i];
6182       Expr *argExpr = Args[i];
6183       assert(argExpr && "SelectBestMethod(): missing expression");
6184 
6185       // Strip the unbridged-cast placeholder expression off unless it's
6186       // a consumed argument.
6187       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6188           !param->hasAttr<CFConsumedAttr>())
6189         argExpr = stripARCUnbridgedCast(argExpr);
6190 
6191       // If the parameter is __unknown_anytype, move on to the next method.
6192       if (param->getType() == Context.UnknownAnyTy) {
6193         Match = false;
6194         break;
6195       }
6196 
6197       ImplicitConversionSequence ConversionState
6198         = TryCopyInitialization(*this, argExpr, param->getType(),
6199                                 /*SuppressUserConversions*/false,
6200                                 /*InOverloadResolution=*/true,
6201                                 /*AllowObjCWritebackConversion=*/
6202                                 getLangOpts().ObjCAutoRefCount,
6203                                 /*AllowExplicit*/false);
6204       // This function looks for a reasonably-exact match, so we consider
6205       // incompatible pointer conversions to be a failure here.
6206       if (ConversionState.isBad() ||
6207           (ConversionState.isStandard() &&
6208            ConversionState.Standard.Second ==
6209                ICK_Incompatible_Pointer_Conversion)) {
6210         Match = false;
6211         break;
6212       }
6213     }
6214     // Promote additional arguments to variadic methods.
6215     if (Match && Method->isVariadic()) {
6216       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6217         if (Args[i]->isTypeDependent()) {
6218           Match = false;
6219           break;
6220         }
6221         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6222                                                           nullptr);
6223         if (Arg.isInvalid()) {
6224           Match = false;
6225           break;
6226         }
6227       }
6228     } else {
6229       // Check for extra arguments to non-variadic methods.
6230       if (Args.size() != NumNamedArgs)
6231         Match = false;
6232       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6233         // Special case when selectors have no argument. In this case, select
6234         // one with the most general result type of 'id'.
6235         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6236           QualType ReturnT = Methods[b]->getReturnType();
6237           if (ReturnT->isObjCIdType())
6238             return Methods[b];
6239         }
6240       }
6241     }
6242 
6243     if (Match)
6244       return Method;
6245   }
6246   return nullptr;
6247 }
6248 
6249 static bool
6250 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6251                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6252                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6253                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6254   if (ThisArg) {
6255     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6256     assert(!isa<CXXConstructorDecl>(Method) &&
6257            "Shouldn't have `this` for ctors!");
6258     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6259     ExprResult R = S.PerformObjectArgumentInitialization(
6260         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6261     if (R.isInvalid())
6262       return false;
6263     ConvertedThis = R.get();
6264   } else {
6265     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6266       (void)MD;
6267       assert((MissingImplicitThis || MD->isStatic() ||
6268               isa<CXXConstructorDecl>(MD)) &&
6269              "Expected `this` for non-ctor instance methods");
6270     }
6271     ConvertedThis = nullptr;
6272   }
6273 
6274   // Ignore any variadic arguments. Converting them is pointless, since the
6275   // user can't refer to them in the function condition.
6276   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6277 
6278   // Convert the arguments.
6279   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6280     ExprResult R;
6281     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6282                                         S.Context, Function->getParamDecl(I)),
6283                                     SourceLocation(), Args[I]);
6284 
6285     if (R.isInvalid())
6286       return false;
6287 
6288     ConvertedArgs.push_back(R.get());
6289   }
6290 
6291   if (Trap.hasErrorOccurred())
6292     return false;
6293 
6294   // Push default arguments if needed.
6295   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6296     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6297       ParmVarDecl *P = Function->getParamDecl(i);
6298       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6299                          ? P->getUninstantiatedDefaultArg()
6300                          : P->getDefaultArg();
6301       // This can only happen in code completion, i.e. when PartialOverloading
6302       // is true.
6303       if (!DefArg)
6304         return false;
6305       ExprResult R =
6306           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6307                                           S.Context, Function->getParamDecl(i)),
6308                                       SourceLocation(), DefArg);
6309       if (R.isInvalid())
6310         return false;
6311       ConvertedArgs.push_back(R.get());
6312     }
6313 
6314     if (Trap.hasErrorOccurred())
6315       return false;
6316   }
6317   return true;
6318 }
6319 
6320 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6321                                   bool MissingImplicitThis) {
6322   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6323   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6324     return nullptr;
6325 
6326   SFINAETrap Trap(*this);
6327   SmallVector<Expr *, 16> ConvertedArgs;
6328   // FIXME: We should look into making enable_if late-parsed.
6329   Expr *DiscardedThis;
6330   if (!convertArgsForAvailabilityChecks(
6331           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6332           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6333     return *EnableIfAttrs.begin();
6334 
6335   for (auto *EIA : EnableIfAttrs) {
6336     APValue Result;
6337     // FIXME: This doesn't consider value-dependent cases, because doing so is
6338     // very difficult. Ideally, we should handle them more gracefully.
6339     if (!EIA->getCond()->EvaluateWithSubstitution(
6340             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6341       return EIA;
6342 
6343     if (!Result.isInt() || !Result.getInt().getBoolValue())
6344       return EIA;
6345   }
6346   return nullptr;
6347 }
6348 
6349 template <typename CheckFn>
6350 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6351                                         bool ArgDependent, SourceLocation Loc,
6352                                         CheckFn &&IsSuccessful) {
6353   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6354   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6355     if (ArgDependent == DIA->getArgDependent())
6356       Attrs.push_back(DIA);
6357   }
6358 
6359   // Common case: No diagnose_if attributes, so we can quit early.
6360   if (Attrs.empty())
6361     return false;
6362 
6363   auto WarningBegin = std::stable_partition(
6364       Attrs.begin(), Attrs.end(),
6365       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6366 
6367   // Note that diagnose_if attributes are late-parsed, so they appear in the
6368   // correct order (unlike enable_if attributes).
6369   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6370                                IsSuccessful);
6371   if (ErrAttr != WarningBegin) {
6372     const DiagnoseIfAttr *DIA = *ErrAttr;
6373     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6374     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6375         << DIA->getParent() << DIA->getCond()->getSourceRange();
6376     return true;
6377   }
6378 
6379   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6380     if (IsSuccessful(DIA)) {
6381       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6382       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6383           << DIA->getParent() << DIA->getCond()->getSourceRange();
6384     }
6385 
6386   return false;
6387 }
6388 
6389 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6390                                                const Expr *ThisArg,
6391                                                ArrayRef<const Expr *> Args,
6392                                                SourceLocation Loc) {
6393   return diagnoseDiagnoseIfAttrsWith(
6394       *this, Function, /*ArgDependent=*/true, Loc,
6395       [&](const DiagnoseIfAttr *DIA) {
6396         APValue Result;
6397         // It's sane to use the same Args for any redecl of this function, since
6398         // EvaluateWithSubstitution only cares about the position of each
6399         // argument in the arg list, not the ParmVarDecl* it maps to.
6400         if (!DIA->getCond()->EvaluateWithSubstitution(
6401                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6402           return false;
6403         return Result.isInt() && Result.getInt().getBoolValue();
6404       });
6405 }
6406 
6407 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6408                                                  SourceLocation Loc) {
6409   return diagnoseDiagnoseIfAttrsWith(
6410       *this, ND, /*ArgDependent=*/false, Loc,
6411       [&](const DiagnoseIfAttr *DIA) {
6412         bool Result;
6413         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6414                Result;
6415       });
6416 }
6417 
6418 /// Add all of the function declarations in the given function set to
6419 /// the overload candidate set.
6420 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6421                                  ArrayRef<Expr *> Args,
6422                                  OverloadCandidateSet &CandidateSet,
6423                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6424                                  bool SuppressUserConversions,
6425                                  bool PartialOverloading,
6426                                  bool FirstArgumentIsBase) {
6427   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6428     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6429     ArrayRef<Expr *> FunctionArgs = Args;
6430 
6431     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6432     FunctionDecl *FD =
6433         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6434 
6435     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6436       QualType ObjectType;
6437       Expr::Classification ObjectClassification;
6438       if (Args.size() > 0) {
6439         if (Expr *E = Args[0]) {
6440           // Use the explicit base to restrict the lookup:
6441           ObjectType = E->getType();
6442           // Pointers in the object arguments are implicitly dereferenced, so we
6443           // always classify them as l-values.
6444           if (!ObjectType.isNull() && ObjectType->isPointerType())
6445             ObjectClassification = Expr::Classification::makeSimpleLValue();
6446           else
6447             ObjectClassification = E->Classify(Context);
6448         } // .. else there is an implicit base.
6449         FunctionArgs = Args.slice(1);
6450       }
6451       if (FunTmpl) {
6452         AddMethodTemplateCandidate(
6453             FunTmpl, F.getPair(),
6454             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6455             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6456             FunctionArgs, CandidateSet, SuppressUserConversions,
6457             PartialOverloading);
6458       } else {
6459         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6460                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6461                            ObjectClassification, FunctionArgs, CandidateSet,
6462                            SuppressUserConversions, PartialOverloading);
6463       }
6464     } else {
6465       // This branch handles both standalone functions and static methods.
6466 
6467       // Slice the first argument (which is the base) when we access
6468       // static method as non-static.
6469       if (Args.size() > 0 &&
6470           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6471                         !isa<CXXConstructorDecl>(FD)))) {
6472         assert(cast<CXXMethodDecl>(FD)->isStatic());
6473         FunctionArgs = Args.slice(1);
6474       }
6475       if (FunTmpl) {
6476         AddTemplateOverloadCandidate(
6477             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6478             CandidateSet, SuppressUserConversions, PartialOverloading);
6479       } else {
6480         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6481                              SuppressUserConversions, PartialOverloading);
6482       }
6483     }
6484   }
6485 }
6486 
6487 /// AddMethodCandidate - Adds a named decl (which is some kind of
6488 /// method) as a method candidate to the given overload set.
6489 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6490                               QualType ObjectType,
6491                               Expr::Classification ObjectClassification,
6492                               ArrayRef<Expr *> Args,
6493                               OverloadCandidateSet& CandidateSet,
6494                               bool SuppressUserConversions) {
6495   NamedDecl *Decl = FoundDecl.getDecl();
6496   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6497 
6498   if (isa<UsingShadowDecl>(Decl))
6499     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6500 
6501   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6502     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6503            "Expected a member function template");
6504     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6505                                /*ExplicitArgs*/ nullptr, ObjectType,
6506                                ObjectClassification, Args, CandidateSet,
6507                                SuppressUserConversions);
6508   } else {
6509     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6510                        ObjectType, ObjectClassification, Args, CandidateSet,
6511                        SuppressUserConversions);
6512   }
6513 }
6514 
6515 /// AddMethodCandidate - Adds the given C++ member function to the set
6516 /// of candidate functions, using the given function call arguments
6517 /// and the object argument (@c Object). For example, in a call
6518 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6519 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6520 /// allow user-defined conversions via constructors or conversion
6521 /// operators.
6522 void
6523 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6524                          CXXRecordDecl *ActingContext, QualType ObjectType,
6525                          Expr::Classification ObjectClassification,
6526                          ArrayRef<Expr *> Args,
6527                          OverloadCandidateSet &CandidateSet,
6528                          bool SuppressUserConversions,
6529                          bool PartialOverloading,
6530                          ConversionSequenceList EarlyConversions) {
6531   const FunctionProtoType *Proto
6532     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6533   assert(Proto && "Methods without a prototype cannot be overloaded");
6534   assert(!isa<CXXConstructorDecl>(Method) &&
6535          "Use AddOverloadCandidate for constructors");
6536 
6537   if (!CandidateSet.isNewCandidate(Method))
6538     return;
6539 
6540   // C++11 [class.copy]p23: [DR1402]
6541   //   A defaulted move assignment operator that is defined as deleted is
6542   //   ignored by overload resolution.
6543   if (Method->isDefaulted() && Method->isDeleted() &&
6544       Method->isMoveAssignmentOperator())
6545     return;
6546 
6547   // Overload resolution is always an unevaluated context.
6548   EnterExpressionEvaluationContext Unevaluated(
6549       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6550 
6551   // Add this candidate
6552   OverloadCandidate &Candidate =
6553       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6554   Candidate.FoundDecl = FoundDecl;
6555   Candidate.Function = Method;
6556   Candidate.IsSurrogate = false;
6557   Candidate.IgnoreObjectArgument = false;
6558   Candidate.ExplicitCallArguments = Args.size();
6559 
6560   unsigned NumParams = Proto->getNumParams();
6561 
6562   // (C++ 13.3.2p2): A candidate function having fewer than m
6563   // parameters is viable only if it has an ellipsis in its parameter
6564   // list (8.3.5).
6565   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6566       !Proto->isVariadic()) {
6567     Candidate.Viable = false;
6568     Candidate.FailureKind = ovl_fail_too_many_arguments;
6569     return;
6570   }
6571 
6572   // (C++ 13.3.2p2): A candidate function having more than m parameters
6573   // is viable only if the (m+1)st parameter has a default argument
6574   // (8.3.6). For the purposes of overload resolution, the
6575   // parameter list is truncated on the right, so that there are
6576   // exactly m parameters.
6577   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6578   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6579     // Not enough arguments.
6580     Candidate.Viable = false;
6581     Candidate.FailureKind = ovl_fail_too_few_arguments;
6582     return;
6583   }
6584 
6585   Candidate.Viable = true;
6586 
6587   if (Method->isStatic() || ObjectType.isNull())
6588     // The implicit object argument is ignored.
6589     Candidate.IgnoreObjectArgument = true;
6590   else {
6591     // Determine the implicit conversion sequence for the object
6592     // parameter.
6593     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6594         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6595         Method, ActingContext);
6596     if (Candidate.Conversions[0].isBad()) {
6597       Candidate.Viable = false;
6598       Candidate.FailureKind = ovl_fail_bad_conversion;
6599       return;
6600     }
6601   }
6602 
6603   // (CUDA B.1): Check for invalid calls between targets.
6604   if (getLangOpts().CUDA)
6605     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6606       if (!IsAllowedCUDACall(Caller, Method)) {
6607         Candidate.Viable = false;
6608         Candidate.FailureKind = ovl_fail_bad_target;
6609         return;
6610       }
6611 
6612   // Determine the implicit conversion sequences for each of the
6613   // arguments.
6614   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6615     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6616       // We already formed a conversion sequence for this parameter during
6617       // template argument deduction.
6618     } else if (ArgIdx < NumParams) {
6619       // (C++ 13.3.2p3): for F to be a viable function, there shall
6620       // exist for each argument an implicit conversion sequence
6621       // (13.3.3.1) that converts that argument to the corresponding
6622       // parameter of F.
6623       QualType ParamType = Proto->getParamType(ArgIdx);
6624       Candidate.Conversions[ArgIdx + 1]
6625         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6626                                 SuppressUserConversions,
6627                                 /*InOverloadResolution=*/true,
6628                                 /*AllowObjCWritebackConversion=*/
6629                                   getLangOpts().ObjCAutoRefCount);
6630       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6631         Candidate.Viable = false;
6632         Candidate.FailureKind = ovl_fail_bad_conversion;
6633         return;
6634       }
6635     } else {
6636       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6637       // argument for which there is no corresponding parameter is
6638       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6639       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6640     }
6641   }
6642 
6643   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6644     Candidate.Viable = false;
6645     Candidate.FailureKind = ovl_fail_enable_if;
6646     Candidate.DeductionFailure.Data = FailedAttr;
6647     return;
6648   }
6649 
6650   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6651       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6652     Candidate.Viable = false;
6653     Candidate.FailureKind = ovl_non_default_multiversion_function;
6654   }
6655 }
6656 
6657 /// Add a C++ member function template as a candidate to the candidate
6658 /// set, using template argument deduction to produce an appropriate member
6659 /// function template specialization.
6660 void
6661 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6662                                  DeclAccessPair FoundDecl,
6663                                  CXXRecordDecl *ActingContext,
6664                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6665                                  QualType ObjectType,
6666                                  Expr::Classification ObjectClassification,
6667                                  ArrayRef<Expr *> Args,
6668                                  OverloadCandidateSet& CandidateSet,
6669                                  bool SuppressUserConversions,
6670                                  bool PartialOverloading) {
6671   if (!CandidateSet.isNewCandidate(MethodTmpl))
6672     return;
6673 
6674   // C++ [over.match.funcs]p7:
6675   //   In each case where a candidate is a function template, candidate
6676   //   function template specializations are generated using template argument
6677   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6678   //   candidate functions in the usual way.113) A given name can refer to one
6679   //   or more function templates and also to a set of overloaded non-template
6680   //   functions. In such a case, the candidate functions generated from each
6681   //   function template are combined with the set of non-template candidate
6682   //   functions.
6683   TemplateDeductionInfo Info(CandidateSet.getLocation());
6684   FunctionDecl *Specialization = nullptr;
6685   ConversionSequenceList Conversions;
6686   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6687           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6688           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6689             return CheckNonDependentConversions(
6690                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6691                 SuppressUserConversions, ActingContext, ObjectType,
6692                 ObjectClassification);
6693           })) {
6694     OverloadCandidate &Candidate =
6695         CandidateSet.addCandidate(Conversions.size(), Conversions);
6696     Candidate.FoundDecl = FoundDecl;
6697     Candidate.Function = MethodTmpl->getTemplatedDecl();
6698     Candidate.Viable = false;
6699     Candidate.IsSurrogate = false;
6700     Candidate.IgnoreObjectArgument =
6701         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6702         ObjectType.isNull();
6703     Candidate.ExplicitCallArguments = Args.size();
6704     if (Result == TDK_NonDependentConversionFailure)
6705       Candidate.FailureKind = ovl_fail_bad_conversion;
6706     else {
6707       Candidate.FailureKind = ovl_fail_bad_deduction;
6708       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6709                                                             Info);
6710     }
6711     return;
6712   }
6713 
6714   // Add the function template specialization produced by template argument
6715   // deduction as a candidate.
6716   assert(Specialization && "Missing member function template specialization?");
6717   assert(isa<CXXMethodDecl>(Specialization) &&
6718          "Specialization is not a member function?");
6719   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6720                      ActingContext, ObjectType, ObjectClassification, Args,
6721                      CandidateSet, SuppressUserConversions, PartialOverloading,
6722                      Conversions);
6723 }
6724 
6725 /// Add a C++ function template specialization as a candidate
6726 /// in the candidate set, using template argument deduction to produce
6727 /// an appropriate function template specialization.
6728 void Sema::AddTemplateOverloadCandidate(
6729     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6730     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6731     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6732     bool PartialOverloading, ADLCallKind IsADLCandidate) {
6733   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6734     return;
6735 
6736   // C++ [over.match.funcs]p7:
6737   //   In each case where a candidate is a function template, candidate
6738   //   function template specializations are generated using template argument
6739   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6740   //   candidate functions in the usual way.113) A given name can refer to one
6741   //   or more function templates and also to a set of overloaded non-template
6742   //   functions. In such a case, the candidate functions generated from each
6743   //   function template are combined with the set of non-template candidate
6744   //   functions.
6745   TemplateDeductionInfo Info(CandidateSet.getLocation());
6746   FunctionDecl *Specialization = nullptr;
6747   ConversionSequenceList Conversions;
6748   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6749           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6750           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6751             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6752                                                 Args, CandidateSet, Conversions,
6753                                                 SuppressUserConversions);
6754           })) {
6755     OverloadCandidate &Candidate =
6756         CandidateSet.addCandidate(Conversions.size(), Conversions);
6757     Candidate.FoundDecl = FoundDecl;
6758     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6759     Candidate.Viable = false;
6760     Candidate.IsSurrogate = false;
6761     Candidate.IsADLCandidate = IsADLCandidate;
6762     // Ignore the object argument if there is one, since we don't have an object
6763     // type.
6764     Candidate.IgnoreObjectArgument =
6765         isa<CXXMethodDecl>(Candidate.Function) &&
6766         !isa<CXXConstructorDecl>(Candidate.Function);
6767     Candidate.ExplicitCallArguments = Args.size();
6768     if (Result == TDK_NonDependentConversionFailure)
6769       Candidate.FailureKind = ovl_fail_bad_conversion;
6770     else {
6771       Candidate.FailureKind = ovl_fail_bad_deduction;
6772       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6773                                                             Info);
6774     }
6775     return;
6776   }
6777 
6778   // Add the function template specialization produced by template argument
6779   // deduction as a candidate.
6780   assert(Specialization && "Missing function template specialization?");
6781   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6782                        SuppressUserConversions, PartialOverloading,
6783                        /*AllowExplicit*/ false, IsADLCandidate, Conversions);
6784 }
6785 
6786 /// Check that implicit conversion sequences can be formed for each argument
6787 /// whose corresponding parameter has a non-dependent type, per DR1391's
6788 /// [temp.deduct.call]p10.
6789 bool Sema::CheckNonDependentConversions(
6790     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6791     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6792     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6793     CXXRecordDecl *ActingContext, QualType ObjectType,
6794     Expr::Classification ObjectClassification) {
6795   // FIXME: The cases in which we allow explicit conversions for constructor
6796   // arguments never consider calling a constructor template. It's not clear
6797   // that is correct.
6798   const bool AllowExplicit = false;
6799 
6800   auto *FD = FunctionTemplate->getTemplatedDecl();
6801   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6802   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6803   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6804 
6805   Conversions =
6806       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6807 
6808   // Overload resolution is always an unevaluated context.
6809   EnterExpressionEvaluationContext Unevaluated(
6810       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6811 
6812   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6813   // require that, but this check should never result in a hard error, and
6814   // overload resolution is permitted to sidestep instantiations.
6815   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6816       !ObjectType.isNull()) {
6817     Conversions[0] = TryObjectArgumentInitialization(
6818         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6819         Method, ActingContext);
6820     if (Conversions[0].isBad())
6821       return true;
6822   }
6823 
6824   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6825        ++I) {
6826     QualType ParamType = ParamTypes[I];
6827     if (!ParamType->isDependentType()) {
6828       Conversions[ThisConversions + I]
6829         = TryCopyInitialization(*this, Args[I], ParamType,
6830                                 SuppressUserConversions,
6831                                 /*InOverloadResolution=*/true,
6832                                 /*AllowObjCWritebackConversion=*/
6833                                   getLangOpts().ObjCAutoRefCount,
6834                                 AllowExplicit);
6835       if (Conversions[ThisConversions + I].isBad())
6836         return true;
6837     }
6838   }
6839 
6840   return false;
6841 }
6842 
6843 /// Determine whether this is an allowable conversion from the result
6844 /// of an explicit conversion operator to the expected type, per C++
6845 /// [over.match.conv]p1 and [over.match.ref]p1.
6846 ///
6847 /// \param ConvType The return type of the conversion function.
6848 ///
6849 /// \param ToType The type we are converting to.
6850 ///
6851 /// \param AllowObjCPointerConversion Allow a conversion from one
6852 /// Objective-C pointer to another.
6853 ///
6854 /// \returns true if the conversion is allowable, false otherwise.
6855 static bool isAllowableExplicitConversion(Sema &S,
6856                                           QualType ConvType, QualType ToType,
6857                                           bool AllowObjCPointerConversion) {
6858   QualType ToNonRefType = ToType.getNonReferenceType();
6859 
6860   // Easy case: the types are the same.
6861   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6862     return true;
6863 
6864   // Allow qualification conversions.
6865   bool ObjCLifetimeConversion;
6866   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6867                                   ObjCLifetimeConversion))
6868     return true;
6869 
6870   // If we're not allowed to consider Objective-C pointer conversions,
6871   // we're done.
6872   if (!AllowObjCPointerConversion)
6873     return false;
6874 
6875   // Is this an Objective-C pointer conversion?
6876   bool IncompatibleObjC = false;
6877   QualType ConvertedType;
6878   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6879                                    IncompatibleObjC);
6880 }
6881 
6882 /// AddConversionCandidate - Add a C++ conversion function as a
6883 /// candidate in the candidate set (C++ [over.match.conv],
6884 /// C++ [over.match.copy]). From is the expression we're converting from,
6885 /// and ToType is the type that we're eventually trying to convert to
6886 /// (which may or may not be the same type as the type that the
6887 /// conversion function produces).
6888 void
6889 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6890                              DeclAccessPair FoundDecl,
6891                              CXXRecordDecl *ActingContext,
6892                              Expr *From, QualType ToType,
6893                              OverloadCandidateSet& CandidateSet,
6894                              bool AllowObjCConversionOnExplicit,
6895                              bool AllowResultConversion) {
6896   assert(!Conversion->getDescribedFunctionTemplate() &&
6897          "Conversion function templates use AddTemplateConversionCandidate");
6898   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6899   if (!CandidateSet.isNewCandidate(Conversion))
6900     return;
6901 
6902   // If the conversion function has an undeduced return type, trigger its
6903   // deduction now.
6904   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6905     if (DeduceReturnType(Conversion, From->getExprLoc()))
6906       return;
6907     ConvType = Conversion->getConversionType().getNonReferenceType();
6908   }
6909 
6910   // If we don't allow any conversion of the result type, ignore conversion
6911   // functions that don't convert to exactly (possibly cv-qualified) T.
6912   if (!AllowResultConversion &&
6913       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6914     return;
6915 
6916   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6917   // operator is only a candidate if its return type is the target type or
6918   // can be converted to the target type with a qualification conversion.
6919   if (Conversion->isExplicit() &&
6920       !isAllowableExplicitConversion(*this, ConvType, ToType,
6921                                      AllowObjCConversionOnExplicit))
6922     return;
6923 
6924   // Overload resolution is always an unevaluated context.
6925   EnterExpressionEvaluationContext Unevaluated(
6926       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6927 
6928   // Add this candidate
6929   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6930   Candidate.FoundDecl = FoundDecl;
6931   Candidate.Function = Conversion;
6932   Candidate.IsSurrogate = false;
6933   Candidate.IgnoreObjectArgument = false;
6934   Candidate.FinalConversion.setAsIdentityConversion();
6935   Candidate.FinalConversion.setFromType(ConvType);
6936   Candidate.FinalConversion.setAllToTypes(ToType);
6937   Candidate.Viable = true;
6938   Candidate.ExplicitCallArguments = 1;
6939 
6940   // C++ [over.match.funcs]p4:
6941   //   For conversion functions, the function is considered to be a member of
6942   //   the class of the implicit implied object argument for the purpose of
6943   //   defining the type of the implicit object parameter.
6944   //
6945   // Determine the implicit conversion sequence for the implicit
6946   // object parameter.
6947   QualType ImplicitParamType = From->getType();
6948   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6949     ImplicitParamType = FromPtrType->getPointeeType();
6950   CXXRecordDecl *ConversionContext
6951     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6952 
6953   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6954       *this, CandidateSet.getLocation(), From->getType(),
6955       From->Classify(Context), Conversion, ConversionContext);
6956 
6957   if (Candidate.Conversions[0].isBad()) {
6958     Candidate.Viable = false;
6959     Candidate.FailureKind = ovl_fail_bad_conversion;
6960     return;
6961   }
6962 
6963   // We won't go through a user-defined type conversion function to convert a
6964   // derived to base as such conversions are given Conversion Rank. They only
6965   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6966   QualType FromCanon
6967     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6968   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6969   if (FromCanon == ToCanon ||
6970       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6971     Candidate.Viable = false;
6972     Candidate.FailureKind = ovl_fail_trivial_conversion;
6973     return;
6974   }
6975 
6976   // To determine what the conversion from the result of calling the
6977   // conversion function to the type we're eventually trying to
6978   // convert to (ToType), we need to synthesize a call to the
6979   // conversion function and attempt copy initialization from it. This
6980   // makes sure that we get the right semantics with respect to
6981   // lvalues/rvalues and the type. Fortunately, we can allocate this
6982   // call on the stack and we don't need its arguments to be
6983   // well-formed.
6984   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
6985                             VK_LValue, From->getBeginLoc());
6986   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6987                                 Context.getPointerType(Conversion->getType()),
6988                                 CK_FunctionToPointerDecay,
6989                                 &ConversionRef, VK_RValue);
6990 
6991   QualType ConversionType = Conversion->getConversionType();
6992   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
6993     Candidate.Viable = false;
6994     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6995     return;
6996   }
6997 
6998   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6999 
7000   // Note that it is safe to allocate CallExpr on the stack here because
7001   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7002   // allocator).
7003   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7004 
7005   llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)>
7006       Buffer;
7007   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7008       Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7009 
7010   ImplicitConversionSequence ICS =
7011       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7012                             /*SuppressUserConversions=*/true,
7013                             /*InOverloadResolution=*/false,
7014                             /*AllowObjCWritebackConversion=*/false);
7015 
7016   switch (ICS.getKind()) {
7017   case ImplicitConversionSequence::StandardConversion:
7018     Candidate.FinalConversion = ICS.Standard;
7019 
7020     // C++ [over.ics.user]p3:
7021     //   If the user-defined conversion is specified by a specialization of a
7022     //   conversion function template, the second standard conversion sequence
7023     //   shall have exact match rank.
7024     if (Conversion->getPrimaryTemplate() &&
7025         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7026       Candidate.Viable = false;
7027       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7028       return;
7029     }
7030 
7031     // C++0x [dcl.init.ref]p5:
7032     //    In the second case, if the reference is an rvalue reference and
7033     //    the second standard conversion sequence of the user-defined
7034     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7035     //    program is ill-formed.
7036     if (ToType->isRValueReferenceType() &&
7037         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7038       Candidate.Viable = false;
7039       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7040       return;
7041     }
7042     break;
7043 
7044   case ImplicitConversionSequence::BadConversion:
7045     Candidate.Viable = false;
7046     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7047     return;
7048 
7049   default:
7050     llvm_unreachable(
7051            "Can only end up with a standard conversion sequence or failure");
7052   }
7053 
7054   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7055     Candidate.Viable = false;
7056     Candidate.FailureKind = ovl_fail_enable_if;
7057     Candidate.DeductionFailure.Data = FailedAttr;
7058     return;
7059   }
7060 
7061   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7062       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7063     Candidate.Viable = false;
7064     Candidate.FailureKind = ovl_non_default_multiversion_function;
7065   }
7066 }
7067 
7068 /// Adds a conversion function template specialization
7069 /// candidate to the overload set, using template argument deduction
7070 /// to deduce the template arguments of the conversion function
7071 /// template from the type that we are converting to (C++
7072 /// [temp.deduct.conv]).
7073 void
7074 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7075                                      DeclAccessPair FoundDecl,
7076                                      CXXRecordDecl *ActingDC,
7077                                      Expr *From, QualType ToType,
7078                                      OverloadCandidateSet &CandidateSet,
7079                                      bool AllowObjCConversionOnExplicit,
7080                                      bool AllowResultConversion) {
7081   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7082          "Only conversion function templates permitted here");
7083 
7084   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7085     return;
7086 
7087   TemplateDeductionInfo Info(CandidateSet.getLocation());
7088   CXXConversionDecl *Specialization = nullptr;
7089   if (TemplateDeductionResult Result
7090         = DeduceTemplateArguments(FunctionTemplate, ToType,
7091                                   Specialization, Info)) {
7092     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7093     Candidate.FoundDecl = FoundDecl;
7094     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7095     Candidate.Viable = false;
7096     Candidate.FailureKind = ovl_fail_bad_deduction;
7097     Candidate.IsSurrogate = false;
7098     Candidate.IgnoreObjectArgument = false;
7099     Candidate.ExplicitCallArguments = 1;
7100     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7101                                                           Info);
7102     return;
7103   }
7104 
7105   // Add the conversion function template specialization produced by
7106   // template argument deduction as a candidate.
7107   assert(Specialization && "Missing function template specialization?");
7108   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7109                          CandidateSet, AllowObjCConversionOnExplicit,
7110                          AllowResultConversion);
7111 }
7112 
7113 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7114 /// converts the given @c Object to a function pointer via the
7115 /// conversion function @c Conversion, and then attempts to call it
7116 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7117 /// the type of function that we'll eventually be calling.
7118 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7119                                  DeclAccessPair FoundDecl,
7120                                  CXXRecordDecl *ActingContext,
7121                                  const FunctionProtoType *Proto,
7122                                  Expr *Object,
7123                                  ArrayRef<Expr *> Args,
7124                                  OverloadCandidateSet& CandidateSet) {
7125   if (!CandidateSet.isNewCandidate(Conversion))
7126     return;
7127 
7128   // Overload resolution is always an unevaluated context.
7129   EnterExpressionEvaluationContext Unevaluated(
7130       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7131 
7132   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7133   Candidate.FoundDecl = FoundDecl;
7134   Candidate.Function = nullptr;
7135   Candidate.Surrogate = Conversion;
7136   Candidate.Viable = true;
7137   Candidate.IsSurrogate = true;
7138   Candidate.IgnoreObjectArgument = false;
7139   Candidate.ExplicitCallArguments = Args.size();
7140 
7141   // Determine the implicit conversion sequence for the implicit
7142   // object parameter.
7143   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7144       *this, CandidateSet.getLocation(), Object->getType(),
7145       Object->Classify(Context), Conversion, ActingContext);
7146   if (ObjectInit.isBad()) {
7147     Candidate.Viable = false;
7148     Candidate.FailureKind = ovl_fail_bad_conversion;
7149     Candidate.Conversions[0] = ObjectInit;
7150     return;
7151   }
7152 
7153   // The first conversion is actually a user-defined conversion whose
7154   // first conversion is ObjectInit's standard conversion (which is
7155   // effectively a reference binding). Record it as such.
7156   Candidate.Conversions[0].setUserDefined();
7157   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7158   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7159   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7160   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7161   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7162   Candidate.Conversions[0].UserDefined.After
7163     = Candidate.Conversions[0].UserDefined.Before;
7164   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7165 
7166   // Find the
7167   unsigned NumParams = Proto->getNumParams();
7168 
7169   // (C++ 13.3.2p2): A candidate function having fewer than m
7170   // parameters is viable only if it has an ellipsis in its parameter
7171   // list (8.3.5).
7172   if (Args.size() > NumParams && !Proto->isVariadic()) {
7173     Candidate.Viable = false;
7174     Candidate.FailureKind = ovl_fail_too_many_arguments;
7175     return;
7176   }
7177 
7178   // Function types don't have any default arguments, so just check if
7179   // we have enough arguments.
7180   if (Args.size() < NumParams) {
7181     // Not enough arguments.
7182     Candidate.Viable = false;
7183     Candidate.FailureKind = ovl_fail_too_few_arguments;
7184     return;
7185   }
7186 
7187   // Determine the implicit conversion sequences for each of the
7188   // arguments.
7189   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7190     if (ArgIdx < NumParams) {
7191       // (C++ 13.3.2p3): for F to be a viable function, there shall
7192       // exist for each argument an implicit conversion sequence
7193       // (13.3.3.1) that converts that argument to the corresponding
7194       // parameter of F.
7195       QualType ParamType = Proto->getParamType(ArgIdx);
7196       Candidate.Conversions[ArgIdx + 1]
7197         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7198                                 /*SuppressUserConversions=*/false,
7199                                 /*InOverloadResolution=*/false,
7200                                 /*AllowObjCWritebackConversion=*/
7201                                   getLangOpts().ObjCAutoRefCount);
7202       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7203         Candidate.Viable = false;
7204         Candidate.FailureKind = ovl_fail_bad_conversion;
7205         return;
7206       }
7207     } else {
7208       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7209       // argument for which there is no corresponding parameter is
7210       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7211       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7212     }
7213   }
7214 
7215   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7216     Candidate.Viable = false;
7217     Candidate.FailureKind = ovl_fail_enable_if;
7218     Candidate.DeductionFailure.Data = FailedAttr;
7219     return;
7220   }
7221 }
7222 
7223 /// Add overload candidates for overloaded operators that are
7224 /// member functions.
7225 ///
7226 /// Add the overloaded operator candidates that are member functions
7227 /// for the operator Op that was used in an operator expression such
7228 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7229 /// CandidateSet will store the added overload candidates. (C++
7230 /// [over.match.oper]).
7231 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7232                                        SourceLocation OpLoc,
7233                                        ArrayRef<Expr *> Args,
7234                                        OverloadCandidateSet& CandidateSet,
7235                                        SourceRange OpRange) {
7236   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7237 
7238   // C++ [over.match.oper]p3:
7239   //   For a unary operator @ with an operand of a type whose
7240   //   cv-unqualified version is T1, and for a binary operator @ with
7241   //   a left operand of a type whose cv-unqualified version is T1 and
7242   //   a right operand of a type whose cv-unqualified version is T2,
7243   //   three sets of candidate functions, designated member
7244   //   candidates, non-member candidates and built-in candidates, are
7245   //   constructed as follows:
7246   QualType T1 = Args[0]->getType();
7247 
7248   //     -- If T1 is a complete class type or a class currently being
7249   //        defined, the set of member candidates is the result of the
7250   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7251   //        the set of member candidates is empty.
7252   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7253     // Complete the type if it can be completed.
7254     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7255       return;
7256     // If the type is neither complete nor being defined, bail out now.
7257     if (!T1Rec->getDecl()->getDefinition())
7258       return;
7259 
7260     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7261     LookupQualifiedName(Operators, T1Rec->getDecl());
7262     Operators.suppressDiagnostics();
7263 
7264     for (LookupResult::iterator Oper = Operators.begin(),
7265                              OperEnd = Operators.end();
7266          Oper != OperEnd;
7267          ++Oper)
7268       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7269                          Args[0]->Classify(Context), Args.slice(1),
7270                          CandidateSet, /*SuppressUserConversions=*/false);
7271   }
7272 }
7273 
7274 /// AddBuiltinCandidate - Add a candidate for a built-in
7275 /// operator. ResultTy and ParamTys are the result and parameter types
7276 /// of the built-in candidate, respectively. Args and NumArgs are the
7277 /// arguments being passed to the candidate. IsAssignmentOperator
7278 /// should be true when this built-in candidate is an assignment
7279 /// operator. NumContextualBoolArguments is the number of arguments
7280 /// (at the beginning of the argument list) that will be contextually
7281 /// converted to bool.
7282 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7283                                OverloadCandidateSet& CandidateSet,
7284                                bool IsAssignmentOperator,
7285                                unsigned NumContextualBoolArguments) {
7286   // Overload resolution is always an unevaluated context.
7287   EnterExpressionEvaluationContext Unevaluated(
7288       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7289 
7290   // Add this candidate
7291   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7292   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7293   Candidate.Function = nullptr;
7294   Candidate.IsSurrogate = false;
7295   Candidate.IgnoreObjectArgument = false;
7296   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7297 
7298   // Determine the implicit conversion sequences for each of the
7299   // arguments.
7300   Candidate.Viable = true;
7301   Candidate.ExplicitCallArguments = Args.size();
7302   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7303     // C++ [over.match.oper]p4:
7304     //   For the built-in assignment operators, conversions of the
7305     //   left operand are restricted as follows:
7306     //     -- no temporaries are introduced to hold the left operand, and
7307     //     -- no user-defined conversions are applied to the left
7308     //        operand to achieve a type match with the left-most
7309     //        parameter of a built-in candidate.
7310     //
7311     // We block these conversions by turning off user-defined
7312     // conversions, since that is the only way that initialization of
7313     // a reference to a non-class type can occur from something that
7314     // is not of the same type.
7315     if (ArgIdx < NumContextualBoolArguments) {
7316       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7317              "Contextual conversion to bool requires bool type");
7318       Candidate.Conversions[ArgIdx]
7319         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7320     } else {
7321       Candidate.Conversions[ArgIdx]
7322         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7323                                 ArgIdx == 0 && IsAssignmentOperator,
7324                                 /*InOverloadResolution=*/false,
7325                                 /*AllowObjCWritebackConversion=*/
7326                                   getLangOpts().ObjCAutoRefCount);
7327     }
7328     if (Candidate.Conversions[ArgIdx].isBad()) {
7329       Candidate.Viable = false;
7330       Candidate.FailureKind = ovl_fail_bad_conversion;
7331       break;
7332     }
7333   }
7334 }
7335 
7336 namespace {
7337 
7338 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7339 /// candidate operator functions for built-in operators (C++
7340 /// [over.built]). The types are separated into pointer types and
7341 /// enumeration types.
7342 class BuiltinCandidateTypeSet  {
7343   /// TypeSet - A set of types.
7344   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7345                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7346 
7347   /// PointerTypes - The set of pointer types that will be used in the
7348   /// built-in candidates.
7349   TypeSet PointerTypes;
7350 
7351   /// MemberPointerTypes - The set of member pointer types that will be
7352   /// used in the built-in candidates.
7353   TypeSet MemberPointerTypes;
7354 
7355   /// EnumerationTypes - The set of enumeration types that will be
7356   /// used in the built-in candidates.
7357   TypeSet EnumerationTypes;
7358 
7359   /// The set of vector types that will be used in the built-in
7360   /// candidates.
7361   TypeSet VectorTypes;
7362 
7363   /// A flag indicating non-record types are viable candidates
7364   bool HasNonRecordTypes;
7365 
7366   /// A flag indicating whether either arithmetic or enumeration types
7367   /// were present in the candidate set.
7368   bool HasArithmeticOrEnumeralTypes;
7369 
7370   /// A flag indicating whether the nullptr type was present in the
7371   /// candidate set.
7372   bool HasNullPtrType;
7373 
7374   /// Sema - The semantic analysis instance where we are building the
7375   /// candidate type set.
7376   Sema &SemaRef;
7377 
7378   /// Context - The AST context in which we will build the type sets.
7379   ASTContext &Context;
7380 
7381   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7382                                                const Qualifiers &VisibleQuals);
7383   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7384 
7385 public:
7386   /// iterator - Iterates through the types that are part of the set.
7387   typedef TypeSet::iterator iterator;
7388 
7389   BuiltinCandidateTypeSet(Sema &SemaRef)
7390     : HasNonRecordTypes(false),
7391       HasArithmeticOrEnumeralTypes(false),
7392       HasNullPtrType(false),
7393       SemaRef(SemaRef),
7394       Context(SemaRef.Context) { }
7395 
7396   void AddTypesConvertedFrom(QualType Ty,
7397                              SourceLocation Loc,
7398                              bool AllowUserConversions,
7399                              bool AllowExplicitConversions,
7400                              const Qualifiers &VisibleTypeConversionsQuals);
7401 
7402   /// pointer_begin - First pointer type found;
7403   iterator pointer_begin() { return PointerTypes.begin(); }
7404 
7405   /// pointer_end - Past the last pointer type found;
7406   iterator pointer_end() { return PointerTypes.end(); }
7407 
7408   /// member_pointer_begin - First member pointer type found;
7409   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7410 
7411   /// member_pointer_end - Past the last member pointer type found;
7412   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7413 
7414   /// enumeration_begin - First enumeration type found;
7415   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7416 
7417   /// enumeration_end - Past the last enumeration type found;
7418   iterator enumeration_end() { return EnumerationTypes.end(); }
7419 
7420   iterator vector_begin() { return VectorTypes.begin(); }
7421   iterator vector_end() { return VectorTypes.end(); }
7422 
7423   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7424   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7425   bool hasNullPtrType() const { return HasNullPtrType; }
7426 };
7427 
7428 } // end anonymous namespace
7429 
7430 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7431 /// the set of pointer types along with any more-qualified variants of
7432 /// that type. For example, if @p Ty is "int const *", this routine
7433 /// will add "int const *", "int const volatile *", "int const
7434 /// restrict *", and "int const volatile restrict *" to the set of
7435 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7436 /// false otherwise.
7437 ///
7438 /// FIXME: what to do about extended qualifiers?
7439 bool
7440 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7441                                              const Qualifiers &VisibleQuals) {
7442 
7443   // Insert this type.
7444   if (!PointerTypes.insert(Ty))
7445     return false;
7446 
7447   QualType PointeeTy;
7448   const PointerType *PointerTy = Ty->getAs<PointerType>();
7449   bool buildObjCPtr = false;
7450   if (!PointerTy) {
7451     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7452     PointeeTy = PTy->getPointeeType();
7453     buildObjCPtr = true;
7454   } else {
7455     PointeeTy = PointerTy->getPointeeType();
7456   }
7457 
7458   // Don't add qualified variants of arrays. For one, they're not allowed
7459   // (the qualifier would sink to the element type), and for another, the
7460   // only overload situation where it matters is subscript or pointer +- int,
7461   // and those shouldn't have qualifier variants anyway.
7462   if (PointeeTy->isArrayType())
7463     return true;
7464 
7465   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7466   bool hasVolatile = VisibleQuals.hasVolatile();
7467   bool hasRestrict = VisibleQuals.hasRestrict();
7468 
7469   // Iterate through all strict supersets of BaseCVR.
7470   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7471     if ((CVR | BaseCVR) != CVR) continue;
7472     // Skip over volatile if no volatile found anywhere in the types.
7473     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7474 
7475     // Skip over restrict if no restrict found anywhere in the types, or if
7476     // the type cannot be restrict-qualified.
7477     if ((CVR & Qualifiers::Restrict) &&
7478         (!hasRestrict ||
7479          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7480       continue;
7481 
7482     // Build qualified pointee type.
7483     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7484 
7485     // Build qualified pointer type.
7486     QualType QPointerTy;
7487     if (!buildObjCPtr)
7488       QPointerTy = Context.getPointerType(QPointeeTy);
7489     else
7490       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7491 
7492     // Insert qualified pointer type.
7493     PointerTypes.insert(QPointerTy);
7494   }
7495 
7496   return true;
7497 }
7498 
7499 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7500 /// to the set of pointer types along with any more-qualified variants of
7501 /// that type. For example, if @p Ty is "int const *", this routine
7502 /// will add "int const *", "int const volatile *", "int const
7503 /// restrict *", and "int const volatile restrict *" to the set of
7504 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7505 /// false otherwise.
7506 ///
7507 /// FIXME: what to do about extended qualifiers?
7508 bool
7509 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7510     QualType Ty) {
7511   // Insert this type.
7512   if (!MemberPointerTypes.insert(Ty))
7513     return false;
7514 
7515   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7516   assert(PointerTy && "type was not a member pointer type!");
7517 
7518   QualType PointeeTy = PointerTy->getPointeeType();
7519   // Don't add qualified variants of arrays. For one, they're not allowed
7520   // (the qualifier would sink to the element type), and for another, the
7521   // only overload situation where it matters is subscript or pointer +- int,
7522   // and those shouldn't have qualifier variants anyway.
7523   if (PointeeTy->isArrayType())
7524     return true;
7525   const Type *ClassTy = PointerTy->getClass();
7526 
7527   // Iterate through all strict supersets of the pointee type's CVR
7528   // qualifiers.
7529   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7530   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7531     if ((CVR | BaseCVR) != CVR) continue;
7532 
7533     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7534     MemberPointerTypes.insert(
7535       Context.getMemberPointerType(QPointeeTy, ClassTy));
7536   }
7537 
7538   return true;
7539 }
7540 
7541 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7542 /// Ty can be implicit converted to the given set of @p Types. We're
7543 /// primarily interested in pointer types and enumeration types. We also
7544 /// take member pointer types, for the conditional operator.
7545 /// AllowUserConversions is true if we should look at the conversion
7546 /// functions of a class type, and AllowExplicitConversions if we
7547 /// should also include the explicit conversion functions of a class
7548 /// type.
7549 void
7550 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7551                                                SourceLocation Loc,
7552                                                bool AllowUserConversions,
7553                                                bool AllowExplicitConversions,
7554                                                const Qualifiers &VisibleQuals) {
7555   // Only deal with canonical types.
7556   Ty = Context.getCanonicalType(Ty);
7557 
7558   // Look through reference types; they aren't part of the type of an
7559   // expression for the purposes of conversions.
7560   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7561     Ty = RefTy->getPointeeType();
7562 
7563   // If we're dealing with an array type, decay to the pointer.
7564   if (Ty->isArrayType())
7565     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7566 
7567   // Otherwise, we don't care about qualifiers on the type.
7568   Ty = Ty.getLocalUnqualifiedType();
7569 
7570   // Flag if we ever add a non-record type.
7571   const RecordType *TyRec = Ty->getAs<RecordType>();
7572   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7573 
7574   // Flag if we encounter an arithmetic type.
7575   HasArithmeticOrEnumeralTypes =
7576     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7577 
7578   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7579     PointerTypes.insert(Ty);
7580   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7581     // Insert our type, and its more-qualified variants, into the set
7582     // of types.
7583     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7584       return;
7585   } else if (Ty->isMemberPointerType()) {
7586     // Member pointers are far easier, since the pointee can't be converted.
7587     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7588       return;
7589   } else if (Ty->isEnumeralType()) {
7590     HasArithmeticOrEnumeralTypes = true;
7591     EnumerationTypes.insert(Ty);
7592   } else if (Ty->isVectorType()) {
7593     // We treat vector types as arithmetic types in many contexts as an
7594     // extension.
7595     HasArithmeticOrEnumeralTypes = true;
7596     VectorTypes.insert(Ty);
7597   } else if (Ty->isNullPtrType()) {
7598     HasNullPtrType = true;
7599   } else if (AllowUserConversions && TyRec) {
7600     // No conversion functions in incomplete types.
7601     if (!SemaRef.isCompleteType(Loc, Ty))
7602       return;
7603 
7604     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7605     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7606       if (isa<UsingShadowDecl>(D))
7607         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7608 
7609       // Skip conversion function templates; they don't tell us anything
7610       // about which builtin types we can convert to.
7611       if (isa<FunctionTemplateDecl>(D))
7612         continue;
7613 
7614       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7615       if (AllowExplicitConversions || !Conv->isExplicit()) {
7616         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7617                               VisibleQuals);
7618       }
7619     }
7620   }
7621 }
7622 
7623 /// Helper function for AddBuiltinOperatorCandidates() that adds
7624 /// the volatile- and non-volatile-qualified assignment operators for the
7625 /// given type to the candidate set.
7626 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7627                                                    QualType T,
7628                                                    ArrayRef<Expr *> Args,
7629                                     OverloadCandidateSet &CandidateSet) {
7630   QualType ParamTypes[2];
7631 
7632   // T& operator=(T&, T)
7633   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7634   ParamTypes[1] = T;
7635   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7636                         /*IsAssignmentOperator=*/true);
7637 
7638   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7639     // volatile T& operator=(volatile T&, T)
7640     ParamTypes[0]
7641       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7642     ParamTypes[1] = T;
7643     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7644                           /*IsAssignmentOperator=*/true);
7645   }
7646 }
7647 
7648 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7649 /// if any, found in visible type conversion functions found in ArgExpr's type.
7650 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7651     Qualifiers VRQuals;
7652     const RecordType *TyRec;
7653     if (const MemberPointerType *RHSMPType =
7654         ArgExpr->getType()->getAs<MemberPointerType>())
7655       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7656     else
7657       TyRec = ArgExpr->getType()->getAs<RecordType>();
7658     if (!TyRec) {
7659       // Just to be safe, assume the worst case.
7660       VRQuals.addVolatile();
7661       VRQuals.addRestrict();
7662       return VRQuals;
7663     }
7664 
7665     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7666     if (!ClassDecl->hasDefinition())
7667       return VRQuals;
7668 
7669     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7670       if (isa<UsingShadowDecl>(D))
7671         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7672       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7673         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7674         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7675           CanTy = ResTypeRef->getPointeeType();
7676         // Need to go down the pointer/mempointer chain and add qualifiers
7677         // as see them.
7678         bool done = false;
7679         while (!done) {
7680           if (CanTy.isRestrictQualified())
7681             VRQuals.addRestrict();
7682           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7683             CanTy = ResTypePtr->getPointeeType();
7684           else if (const MemberPointerType *ResTypeMPtr =
7685                 CanTy->getAs<MemberPointerType>())
7686             CanTy = ResTypeMPtr->getPointeeType();
7687           else
7688             done = true;
7689           if (CanTy.isVolatileQualified())
7690             VRQuals.addVolatile();
7691           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7692             return VRQuals;
7693         }
7694       }
7695     }
7696     return VRQuals;
7697 }
7698 
7699 namespace {
7700 
7701 /// Helper class to manage the addition of builtin operator overload
7702 /// candidates. It provides shared state and utility methods used throughout
7703 /// the process, as well as a helper method to add each group of builtin
7704 /// operator overloads from the standard to a candidate set.
7705 class BuiltinOperatorOverloadBuilder {
7706   // Common instance state available to all overload candidate addition methods.
7707   Sema &S;
7708   ArrayRef<Expr *> Args;
7709   Qualifiers VisibleTypeConversionsQuals;
7710   bool HasArithmeticOrEnumeralCandidateType;
7711   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7712   OverloadCandidateSet &CandidateSet;
7713 
7714   static constexpr int ArithmeticTypesCap = 24;
7715   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7716 
7717   // Define some indices used to iterate over the arithemetic types in
7718   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7719   // types are that preserved by promotion (C++ [over.built]p2).
7720   unsigned FirstIntegralType,
7721            LastIntegralType;
7722   unsigned FirstPromotedIntegralType,
7723            LastPromotedIntegralType;
7724   unsigned FirstPromotedArithmeticType,
7725            LastPromotedArithmeticType;
7726   unsigned NumArithmeticTypes;
7727 
7728   void InitArithmeticTypes() {
7729     // Start of promoted types.
7730     FirstPromotedArithmeticType = 0;
7731     ArithmeticTypes.push_back(S.Context.FloatTy);
7732     ArithmeticTypes.push_back(S.Context.DoubleTy);
7733     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7734     if (S.Context.getTargetInfo().hasFloat128Type())
7735       ArithmeticTypes.push_back(S.Context.Float128Ty);
7736 
7737     // Start of integral types.
7738     FirstIntegralType = ArithmeticTypes.size();
7739     FirstPromotedIntegralType = ArithmeticTypes.size();
7740     ArithmeticTypes.push_back(S.Context.IntTy);
7741     ArithmeticTypes.push_back(S.Context.LongTy);
7742     ArithmeticTypes.push_back(S.Context.LongLongTy);
7743     if (S.Context.getTargetInfo().hasInt128Type())
7744       ArithmeticTypes.push_back(S.Context.Int128Ty);
7745     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7746     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7747     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7748     if (S.Context.getTargetInfo().hasInt128Type())
7749       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7750     LastPromotedIntegralType = ArithmeticTypes.size();
7751     LastPromotedArithmeticType = ArithmeticTypes.size();
7752     // End of promoted types.
7753 
7754     ArithmeticTypes.push_back(S.Context.BoolTy);
7755     ArithmeticTypes.push_back(S.Context.CharTy);
7756     ArithmeticTypes.push_back(S.Context.WCharTy);
7757     if (S.Context.getLangOpts().Char8)
7758       ArithmeticTypes.push_back(S.Context.Char8Ty);
7759     ArithmeticTypes.push_back(S.Context.Char16Ty);
7760     ArithmeticTypes.push_back(S.Context.Char32Ty);
7761     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7762     ArithmeticTypes.push_back(S.Context.ShortTy);
7763     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7764     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7765     LastIntegralType = ArithmeticTypes.size();
7766     NumArithmeticTypes = ArithmeticTypes.size();
7767     // End of integral types.
7768     // FIXME: What about complex? What about half?
7769 
7770     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7771            "Enough inline storage for all arithmetic types.");
7772   }
7773 
7774   /// Helper method to factor out the common pattern of adding overloads
7775   /// for '++' and '--' builtin operators.
7776   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7777                                            bool HasVolatile,
7778                                            bool HasRestrict) {
7779     QualType ParamTypes[2] = {
7780       S.Context.getLValueReferenceType(CandidateTy),
7781       S.Context.IntTy
7782     };
7783 
7784     // Non-volatile version.
7785     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7786 
7787     // Use a heuristic to reduce number of builtin candidates in the set:
7788     // add volatile version only if there are conversions to a volatile type.
7789     if (HasVolatile) {
7790       ParamTypes[0] =
7791         S.Context.getLValueReferenceType(
7792           S.Context.getVolatileType(CandidateTy));
7793       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7794     }
7795 
7796     // Add restrict version only if there are conversions to a restrict type
7797     // and our candidate type is a non-restrict-qualified pointer.
7798     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7799         !CandidateTy.isRestrictQualified()) {
7800       ParamTypes[0]
7801         = S.Context.getLValueReferenceType(
7802             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7803       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7804 
7805       if (HasVolatile) {
7806         ParamTypes[0]
7807           = S.Context.getLValueReferenceType(
7808               S.Context.getCVRQualifiedType(CandidateTy,
7809                                             (Qualifiers::Volatile |
7810                                              Qualifiers::Restrict)));
7811         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7812       }
7813     }
7814 
7815   }
7816 
7817 public:
7818   BuiltinOperatorOverloadBuilder(
7819     Sema &S, ArrayRef<Expr *> Args,
7820     Qualifiers VisibleTypeConversionsQuals,
7821     bool HasArithmeticOrEnumeralCandidateType,
7822     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7823     OverloadCandidateSet &CandidateSet)
7824     : S(S), Args(Args),
7825       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7826       HasArithmeticOrEnumeralCandidateType(
7827         HasArithmeticOrEnumeralCandidateType),
7828       CandidateTypes(CandidateTypes),
7829       CandidateSet(CandidateSet) {
7830 
7831     InitArithmeticTypes();
7832   }
7833 
7834   // Increment is deprecated for bool since C++17.
7835   //
7836   // C++ [over.built]p3:
7837   //
7838   //   For every pair (T, VQ), where T is an arithmetic type other
7839   //   than bool, and VQ is either volatile or empty, there exist
7840   //   candidate operator functions of the form
7841   //
7842   //       VQ T&      operator++(VQ T&);
7843   //       T          operator++(VQ T&, int);
7844   //
7845   // C++ [over.built]p4:
7846   //
7847   //   For every pair (T, VQ), where T is an arithmetic type other
7848   //   than bool, and VQ is either volatile or empty, there exist
7849   //   candidate operator functions of the form
7850   //
7851   //       VQ T&      operator--(VQ T&);
7852   //       T          operator--(VQ T&, int);
7853   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7854     if (!HasArithmeticOrEnumeralCandidateType)
7855       return;
7856 
7857     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7858       const auto TypeOfT = ArithmeticTypes[Arith];
7859       if (TypeOfT == S.Context.BoolTy) {
7860         if (Op == OO_MinusMinus)
7861           continue;
7862         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7863           continue;
7864       }
7865       addPlusPlusMinusMinusStyleOverloads(
7866         TypeOfT,
7867         VisibleTypeConversionsQuals.hasVolatile(),
7868         VisibleTypeConversionsQuals.hasRestrict());
7869     }
7870   }
7871 
7872   // C++ [over.built]p5:
7873   //
7874   //   For every pair (T, VQ), where T is a cv-qualified or
7875   //   cv-unqualified object type, and VQ is either volatile or
7876   //   empty, there exist candidate operator functions of the form
7877   //
7878   //       T*VQ&      operator++(T*VQ&);
7879   //       T*VQ&      operator--(T*VQ&);
7880   //       T*         operator++(T*VQ&, int);
7881   //       T*         operator--(T*VQ&, int);
7882   void addPlusPlusMinusMinusPointerOverloads() {
7883     for (BuiltinCandidateTypeSet::iterator
7884               Ptr = CandidateTypes[0].pointer_begin(),
7885            PtrEnd = CandidateTypes[0].pointer_end();
7886          Ptr != PtrEnd; ++Ptr) {
7887       // Skip pointer types that aren't pointers to object types.
7888       if (!(*Ptr)->getPointeeType()->isObjectType())
7889         continue;
7890 
7891       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7892         (!(*Ptr).isVolatileQualified() &&
7893          VisibleTypeConversionsQuals.hasVolatile()),
7894         (!(*Ptr).isRestrictQualified() &&
7895          VisibleTypeConversionsQuals.hasRestrict()));
7896     }
7897   }
7898 
7899   // C++ [over.built]p6:
7900   //   For every cv-qualified or cv-unqualified object type T, there
7901   //   exist candidate operator functions of the form
7902   //
7903   //       T&         operator*(T*);
7904   //
7905   // C++ [over.built]p7:
7906   //   For every function type T that does not have cv-qualifiers or a
7907   //   ref-qualifier, there exist candidate operator functions of the form
7908   //       T&         operator*(T*);
7909   void addUnaryStarPointerOverloads() {
7910     for (BuiltinCandidateTypeSet::iterator
7911               Ptr = CandidateTypes[0].pointer_begin(),
7912            PtrEnd = CandidateTypes[0].pointer_end();
7913          Ptr != PtrEnd; ++Ptr) {
7914       QualType ParamTy = *Ptr;
7915       QualType PointeeTy = ParamTy->getPointeeType();
7916       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7917         continue;
7918 
7919       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7920         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7921           continue;
7922 
7923       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7924     }
7925   }
7926 
7927   // C++ [over.built]p9:
7928   //  For every promoted arithmetic type T, there exist candidate
7929   //  operator functions of the form
7930   //
7931   //       T         operator+(T);
7932   //       T         operator-(T);
7933   void addUnaryPlusOrMinusArithmeticOverloads() {
7934     if (!HasArithmeticOrEnumeralCandidateType)
7935       return;
7936 
7937     for (unsigned Arith = FirstPromotedArithmeticType;
7938          Arith < LastPromotedArithmeticType; ++Arith) {
7939       QualType ArithTy = ArithmeticTypes[Arith];
7940       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7941     }
7942 
7943     // Extension: We also add these operators for vector types.
7944     for (BuiltinCandidateTypeSet::iterator
7945               Vec = CandidateTypes[0].vector_begin(),
7946            VecEnd = CandidateTypes[0].vector_end();
7947          Vec != VecEnd; ++Vec) {
7948       QualType VecTy = *Vec;
7949       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7950     }
7951   }
7952 
7953   // C++ [over.built]p8:
7954   //   For every type T, there exist candidate operator functions of
7955   //   the form
7956   //
7957   //       T*         operator+(T*);
7958   void addUnaryPlusPointerOverloads() {
7959     for (BuiltinCandidateTypeSet::iterator
7960               Ptr = CandidateTypes[0].pointer_begin(),
7961            PtrEnd = CandidateTypes[0].pointer_end();
7962          Ptr != PtrEnd; ++Ptr) {
7963       QualType ParamTy = *Ptr;
7964       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7965     }
7966   }
7967 
7968   // C++ [over.built]p10:
7969   //   For every promoted integral type T, there exist candidate
7970   //   operator functions of the form
7971   //
7972   //        T         operator~(T);
7973   void addUnaryTildePromotedIntegralOverloads() {
7974     if (!HasArithmeticOrEnumeralCandidateType)
7975       return;
7976 
7977     for (unsigned Int = FirstPromotedIntegralType;
7978          Int < LastPromotedIntegralType; ++Int) {
7979       QualType IntTy = ArithmeticTypes[Int];
7980       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7981     }
7982 
7983     // Extension: We also add this operator for vector types.
7984     for (BuiltinCandidateTypeSet::iterator
7985               Vec = CandidateTypes[0].vector_begin(),
7986            VecEnd = CandidateTypes[0].vector_end();
7987          Vec != VecEnd; ++Vec) {
7988       QualType VecTy = *Vec;
7989       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7990     }
7991   }
7992 
7993   // C++ [over.match.oper]p16:
7994   //   For every pointer to member type T or type std::nullptr_t, there
7995   //   exist candidate operator functions of the form
7996   //
7997   //        bool operator==(T,T);
7998   //        bool operator!=(T,T);
7999   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8000     /// Set of (canonical) types that we've already handled.
8001     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8002 
8003     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8004       for (BuiltinCandidateTypeSet::iterator
8005                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8006              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8007            MemPtr != MemPtrEnd;
8008            ++MemPtr) {
8009         // Don't add the same builtin candidate twice.
8010         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8011           continue;
8012 
8013         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8014         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8015       }
8016 
8017       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8018         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8019         if (AddedTypes.insert(NullPtrTy).second) {
8020           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8021           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8022         }
8023       }
8024     }
8025   }
8026 
8027   // C++ [over.built]p15:
8028   //
8029   //   For every T, where T is an enumeration type or a pointer type,
8030   //   there exist candidate operator functions of the form
8031   //
8032   //        bool       operator<(T, T);
8033   //        bool       operator>(T, T);
8034   //        bool       operator<=(T, T);
8035   //        bool       operator>=(T, T);
8036   //        bool       operator==(T, T);
8037   //        bool       operator!=(T, T);
8038   //           R       operator<=>(T, T)
8039   void addGenericBinaryPointerOrEnumeralOverloads() {
8040     // C++ [over.match.oper]p3:
8041     //   [...]the built-in candidates include all of the candidate operator
8042     //   functions defined in 13.6 that, compared to the given operator, [...]
8043     //   do not have the same parameter-type-list as any non-template non-member
8044     //   candidate.
8045     //
8046     // Note that in practice, this only affects enumeration types because there
8047     // aren't any built-in candidates of record type, and a user-defined operator
8048     // must have an operand of record or enumeration type. Also, the only other
8049     // overloaded operator with enumeration arguments, operator=,
8050     // cannot be overloaded for enumeration types, so this is the only place
8051     // where we must suppress candidates like this.
8052     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8053       UserDefinedBinaryOperators;
8054 
8055     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8056       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8057           CandidateTypes[ArgIdx].enumeration_end()) {
8058         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8059                                          CEnd = CandidateSet.end();
8060              C != CEnd; ++C) {
8061           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8062             continue;
8063 
8064           if (C->Function->isFunctionTemplateSpecialization())
8065             continue;
8066 
8067           QualType FirstParamType =
8068             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8069           QualType SecondParamType =
8070             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8071 
8072           // Skip if either parameter isn't of enumeral type.
8073           if (!FirstParamType->isEnumeralType() ||
8074               !SecondParamType->isEnumeralType())
8075             continue;
8076 
8077           // Add this operator to the set of known user-defined operators.
8078           UserDefinedBinaryOperators.insert(
8079             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8080                            S.Context.getCanonicalType(SecondParamType)));
8081         }
8082       }
8083     }
8084 
8085     /// Set of (canonical) types that we've already handled.
8086     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8087 
8088     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8089       for (BuiltinCandidateTypeSet::iterator
8090                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8091              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8092            Ptr != PtrEnd; ++Ptr) {
8093         // Don't add the same builtin candidate twice.
8094         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8095           continue;
8096 
8097         QualType ParamTypes[2] = { *Ptr, *Ptr };
8098         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8099       }
8100       for (BuiltinCandidateTypeSet::iterator
8101                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8102              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8103            Enum != EnumEnd; ++Enum) {
8104         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8105 
8106         // Don't add the same builtin candidate twice, or if a user defined
8107         // candidate exists.
8108         if (!AddedTypes.insert(CanonType).second ||
8109             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8110                                                             CanonType)))
8111           continue;
8112         QualType ParamTypes[2] = { *Enum, *Enum };
8113         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8114       }
8115     }
8116   }
8117 
8118   // C++ [over.built]p13:
8119   //
8120   //   For every cv-qualified or cv-unqualified object type T
8121   //   there exist candidate operator functions of the form
8122   //
8123   //      T*         operator+(T*, ptrdiff_t);
8124   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8125   //      T*         operator-(T*, ptrdiff_t);
8126   //      T*         operator+(ptrdiff_t, T*);
8127   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8128   //
8129   // C++ [over.built]p14:
8130   //
8131   //   For every T, where T is a pointer to object type, there
8132   //   exist candidate operator functions of the form
8133   //
8134   //      ptrdiff_t  operator-(T, T);
8135   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8136     /// Set of (canonical) types that we've already handled.
8137     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8138 
8139     for (int Arg = 0; Arg < 2; ++Arg) {
8140       QualType AsymmetricParamTypes[2] = {
8141         S.Context.getPointerDiffType(),
8142         S.Context.getPointerDiffType(),
8143       };
8144       for (BuiltinCandidateTypeSet::iterator
8145                 Ptr = CandidateTypes[Arg].pointer_begin(),
8146              PtrEnd = CandidateTypes[Arg].pointer_end();
8147            Ptr != PtrEnd; ++Ptr) {
8148         QualType PointeeTy = (*Ptr)->getPointeeType();
8149         if (!PointeeTy->isObjectType())
8150           continue;
8151 
8152         AsymmetricParamTypes[Arg] = *Ptr;
8153         if (Arg == 0 || Op == OO_Plus) {
8154           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8155           // T* operator+(ptrdiff_t, T*);
8156           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8157         }
8158         if (Op == OO_Minus) {
8159           // ptrdiff_t operator-(T, T);
8160           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8161             continue;
8162 
8163           QualType ParamTypes[2] = { *Ptr, *Ptr };
8164           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8165         }
8166       }
8167     }
8168   }
8169 
8170   // C++ [over.built]p12:
8171   //
8172   //   For every pair of promoted arithmetic types L and R, there
8173   //   exist candidate operator functions of the form
8174   //
8175   //        LR         operator*(L, R);
8176   //        LR         operator/(L, R);
8177   //        LR         operator+(L, R);
8178   //        LR         operator-(L, R);
8179   //        bool       operator<(L, R);
8180   //        bool       operator>(L, R);
8181   //        bool       operator<=(L, R);
8182   //        bool       operator>=(L, R);
8183   //        bool       operator==(L, R);
8184   //        bool       operator!=(L, R);
8185   //
8186   //   where LR is the result of the usual arithmetic conversions
8187   //   between types L and R.
8188   //
8189   // C++ [over.built]p24:
8190   //
8191   //   For every pair of promoted arithmetic types L and R, there exist
8192   //   candidate operator functions of the form
8193   //
8194   //        LR       operator?(bool, L, R);
8195   //
8196   //   where LR is the result of the usual arithmetic conversions
8197   //   between types L and R.
8198   // Our candidates ignore the first parameter.
8199   void addGenericBinaryArithmeticOverloads() {
8200     if (!HasArithmeticOrEnumeralCandidateType)
8201       return;
8202 
8203     for (unsigned Left = FirstPromotedArithmeticType;
8204          Left < LastPromotedArithmeticType; ++Left) {
8205       for (unsigned Right = FirstPromotedArithmeticType;
8206            Right < LastPromotedArithmeticType; ++Right) {
8207         QualType LandR[2] = { ArithmeticTypes[Left],
8208                               ArithmeticTypes[Right] };
8209         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8210       }
8211     }
8212 
8213     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8214     // conditional operator for vector types.
8215     for (BuiltinCandidateTypeSet::iterator
8216               Vec1 = CandidateTypes[0].vector_begin(),
8217            Vec1End = CandidateTypes[0].vector_end();
8218          Vec1 != Vec1End; ++Vec1) {
8219       for (BuiltinCandidateTypeSet::iterator
8220                 Vec2 = CandidateTypes[1].vector_begin(),
8221              Vec2End = CandidateTypes[1].vector_end();
8222            Vec2 != Vec2End; ++Vec2) {
8223         QualType LandR[2] = { *Vec1, *Vec2 };
8224         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8225       }
8226     }
8227   }
8228 
8229   // C++2a [over.built]p14:
8230   //
8231   //   For every integral type T there exists a candidate operator function
8232   //   of the form
8233   //
8234   //        std::strong_ordering operator<=>(T, T)
8235   //
8236   // C++2a [over.built]p15:
8237   //
8238   //   For every pair of floating-point types L and R, there exists a candidate
8239   //   operator function of the form
8240   //
8241   //       std::partial_ordering operator<=>(L, R);
8242   //
8243   // FIXME: The current specification for integral types doesn't play nice with
8244   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8245   // comparisons. Under the current spec this can lead to ambiguity during
8246   // overload resolution. For example:
8247   //
8248   //   enum A : int {a};
8249   //   auto x = (a <=> (long)42);
8250   //
8251   //   error: call is ambiguous for arguments 'A' and 'long'.
8252   //   note: candidate operator<=>(int, int)
8253   //   note: candidate operator<=>(long, long)
8254   //
8255   // To avoid this error, this function deviates from the specification and adds
8256   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8257   // arithmetic types (the same as the generic relational overloads).
8258   //
8259   // For now this function acts as a placeholder.
8260   void addThreeWayArithmeticOverloads() {
8261     addGenericBinaryArithmeticOverloads();
8262   }
8263 
8264   // C++ [over.built]p17:
8265   //
8266   //   For every pair of promoted integral types L and R, there
8267   //   exist candidate operator functions of the form
8268   //
8269   //      LR         operator%(L, R);
8270   //      LR         operator&(L, R);
8271   //      LR         operator^(L, R);
8272   //      LR         operator|(L, R);
8273   //      L          operator<<(L, R);
8274   //      L          operator>>(L, R);
8275   //
8276   //   where LR is the result of the usual arithmetic conversions
8277   //   between types L and R.
8278   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8279     if (!HasArithmeticOrEnumeralCandidateType)
8280       return;
8281 
8282     for (unsigned Left = FirstPromotedIntegralType;
8283          Left < LastPromotedIntegralType; ++Left) {
8284       for (unsigned Right = FirstPromotedIntegralType;
8285            Right < LastPromotedIntegralType; ++Right) {
8286         QualType LandR[2] = { ArithmeticTypes[Left],
8287                               ArithmeticTypes[Right] };
8288         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8289       }
8290     }
8291   }
8292 
8293   // C++ [over.built]p20:
8294   //
8295   //   For every pair (T, VQ), where T is an enumeration or
8296   //   pointer to member type and VQ is either volatile or
8297   //   empty, there exist candidate operator functions of the form
8298   //
8299   //        VQ T&      operator=(VQ T&, T);
8300   void addAssignmentMemberPointerOrEnumeralOverloads() {
8301     /// Set of (canonical) types that we've already handled.
8302     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8303 
8304     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8305       for (BuiltinCandidateTypeSet::iterator
8306                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8307              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8308            Enum != EnumEnd; ++Enum) {
8309         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8310           continue;
8311 
8312         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8313       }
8314 
8315       for (BuiltinCandidateTypeSet::iterator
8316                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8317              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8318            MemPtr != MemPtrEnd; ++MemPtr) {
8319         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8320           continue;
8321 
8322         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8323       }
8324     }
8325   }
8326 
8327   // C++ [over.built]p19:
8328   //
8329   //   For every pair (T, VQ), where T is any type and VQ is either
8330   //   volatile or empty, there exist candidate operator functions
8331   //   of the form
8332   //
8333   //        T*VQ&      operator=(T*VQ&, T*);
8334   //
8335   // C++ [over.built]p21:
8336   //
8337   //   For every pair (T, VQ), where T is a cv-qualified or
8338   //   cv-unqualified object type and VQ is either volatile or
8339   //   empty, there exist candidate operator functions of the form
8340   //
8341   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8342   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8343   void addAssignmentPointerOverloads(bool isEqualOp) {
8344     /// Set of (canonical) types that we've already handled.
8345     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8346 
8347     for (BuiltinCandidateTypeSet::iterator
8348               Ptr = CandidateTypes[0].pointer_begin(),
8349            PtrEnd = CandidateTypes[0].pointer_end();
8350          Ptr != PtrEnd; ++Ptr) {
8351       // If this is operator=, keep track of the builtin candidates we added.
8352       if (isEqualOp)
8353         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8354       else if (!(*Ptr)->getPointeeType()->isObjectType())
8355         continue;
8356 
8357       // non-volatile version
8358       QualType ParamTypes[2] = {
8359         S.Context.getLValueReferenceType(*Ptr),
8360         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8361       };
8362       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8363                             /*IsAssigmentOperator=*/ isEqualOp);
8364 
8365       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8366                           VisibleTypeConversionsQuals.hasVolatile();
8367       if (NeedVolatile) {
8368         // volatile version
8369         ParamTypes[0] =
8370           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8371         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8372                               /*IsAssigmentOperator=*/isEqualOp);
8373       }
8374 
8375       if (!(*Ptr).isRestrictQualified() &&
8376           VisibleTypeConversionsQuals.hasRestrict()) {
8377         // restrict version
8378         ParamTypes[0]
8379           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8380         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8381                               /*IsAssigmentOperator=*/isEqualOp);
8382 
8383         if (NeedVolatile) {
8384           // volatile restrict version
8385           ParamTypes[0]
8386             = S.Context.getLValueReferenceType(
8387                 S.Context.getCVRQualifiedType(*Ptr,
8388                                               (Qualifiers::Volatile |
8389                                                Qualifiers::Restrict)));
8390           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8391                                 /*IsAssigmentOperator=*/isEqualOp);
8392         }
8393       }
8394     }
8395 
8396     if (isEqualOp) {
8397       for (BuiltinCandidateTypeSet::iterator
8398                 Ptr = CandidateTypes[1].pointer_begin(),
8399              PtrEnd = CandidateTypes[1].pointer_end();
8400            Ptr != PtrEnd; ++Ptr) {
8401         // Make sure we don't add the same candidate twice.
8402         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8403           continue;
8404 
8405         QualType ParamTypes[2] = {
8406           S.Context.getLValueReferenceType(*Ptr),
8407           *Ptr,
8408         };
8409 
8410         // non-volatile version
8411         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8412                               /*IsAssigmentOperator=*/true);
8413 
8414         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8415                            VisibleTypeConversionsQuals.hasVolatile();
8416         if (NeedVolatile) {
8417           // volatile version
8418           ParamTypes[0] =
8419             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8420           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8421                                 /*IsAssigmentOperator=*/true);
8422         }
8423 
8424         if (!(*Ptr).isRestrictQualified() &&
8425             VisibleTypeConversionsQuals.hasRestrict()) {
8426           // restrict version
8427           ParamTypes[0]
8428             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8429           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8430                                 /*IsAssigmentOperator=*/true);
8431 
8432           if (NeedVolatile) {
8433             // volatile restrict version
8434             ParamTypes[0]
8435               = S.Context.getLValueReferenceType(
8436                   S.Context.getCVRQualifiedType(*Ptr,
8437                                                 (Qualifiers::Volatile |
8438                                                  Qualifiers::Restrict)));
8439             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8440                                   /*IsAssigmentOperator=*/true);
8441           }
8442         }
8443       }
8444     }
8445   }
8446 
8447   // C++ [over.built]p18:
8448   //
8449   //   For every triple (L, VQ, R), where L is an arithmetic type,
8450   //   VQ is either volatile or empty, and R is a promoted
8451   //   arithmetic type, there exist candidate operator functions of
8452   //   the form
8453   //
8454   //        VQ L&      operator=(VQ L&, R);
8455   //        VQ L&      operator*=(VQ L&, R);
8456   //        VQ L&      operator/=(VQ L&, R);
8457   //        VQ L&      operator+=(VQ L&, R);
8458   //        VQ L&      operator-=(VQ L&, R);
8459   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8460     if (!HasArithmeticOrEnumeralCandidateType)
8461       return;
8462 
8463     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8464       for (unsigned Right = FirstPromotedArithmeticType;
8465            Right < LastPromotedArithmeticType; ++Right) {
8466         QualType ParamTypes[2];
8467         ParamTypes[1] = ArithmeticTypes[Right];
8468 
8469         // Add this built-in operator as a candidate (VQ is empty).
8470         ParamTypes[0] =
8471           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8472         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8473                               /*IsAssigmentOperator=*/isEqualOp);
8474 
8475         // Add this built-in operator as a candidate (VQ is 'volatile').
8476         if (VisibleTypeConversionsQuals.hasVolatile()) {
8477           ParamTypes[0] =
8478             S.Context.getVolatileType(ArithmeticTypes[Left]);
8479           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8480           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8481                                 /*IsAssigmentOperator=*/isEqualOp);
8482         }
8483       }
8484     }
8485 
8486     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8487     for (BuiltinCandidateTypeSet::iterator
8488               Vec1 = CandidateTypes[0].vector_begin(),
8489            Vec1End = CandidateTypes[0].vector_end();
8490          Vec1 != Vec1End; ++Vec1) {
8491       for (BuiltinCandidateTypeSet::iterator
8492                 Vec2 = CandidateTypes[1].vector_begin(),
8493              Vec2End = CandidateTypes[1].vector_end();
8494            Vec2 != Vec2End; ++Vec2) {
8495         QualType ParamTypes[2];
8496         ParamTypes[1] = *Vec2;
8497         // Add this built-in operator as a candidate (VQ is empty).
8498         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8499         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8500                               /*IsAssigmentOperator=*/isEqualOp);
8501 
8502         // Add this built-in operator as a candidate (VQ is 'volatile').
8503         if (VisibleTypeConversionsQuals.hasVolatile()) {
8504           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8505           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8506           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8507                                 /*IsAssigmentOperator=*/isEqualOp);
8508         }
8509       }
8510     }
8511   }
8512 
8513   // C++ [over.built]p22:
8514   //
8515   //   For every triple (L, VQ, R), where L is an integral type, VQ
8516   //   is either volatile or empty, and R is a promoted integral
8517   //   type, there exist candidate operator functions of the form
8518   //
8519   //        VQ L&       operator%=(VQ L&, R);
8520   //        VQ L&       operator<<=(VQ L&, R);
8521   //        VQ L&       operator>>=(VQ L&, R);
8522   //        VQ L&       operator&=(VQ L&, R);
8523   //        VQ L&       operator^=(VQ L&, R);
8524   //        VQ L&       operator|=(VQ L&, R);
8525   void addAssignmentIntegralOverloads() {
8526     if (!HasArithmeticOrEnumeralCandidateType)
8527       return;
8528 
8529     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8530       for (unsigned Right = FirstPromotedIntegralType;
8531            Right < LastPromotedIntegralType; ++Right) {
8532         QualType ParamTypes[2];
8533         ParamTypes[1] = ArithmeticTypes[Right];
8534 
8535         // Add this built-in operator as a candidate (VQ is empty).
8536         ParamTypes[0] =
8537           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8538         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8539         if (VisibleTypeConversionsQuals.hasVolatile()) {
8540           // Add this built-in operator as a candidate (VQ is 'volatile').
8541           ParamTypes[0] = ArithmeticTypes[Left];
8542           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8543           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8544           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8545         }
8546       }
8547     }
8548   }
8549 
8550   // C++ [over.operator]p23:
8551   //
8552   //   There also exist candidate operator functions of the form
8553   //
8554   //        bool        operator!(bool);
8555   //        bool        operator&&(bool, bool);
8556   //        bool        operator||(bool, bool);
8557   void addExclaimOverload() {
8558     QualType ParamTy = S.Context.BoolTy;
8559     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8560                           /*IsAssignmentOperator=*/false,
8561                           /*NumContextualBoolArguments=*/1);
8562   }
8563   void addAmpAmpOrPipePipeOverload() {
8564     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8565     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8566                           /*IsAssignmentOperator=*/false,
8567                           /*NumContextualBoolArguments=*/2);
8568   }
8569 
8570   // C++ [over.built]p13:
8571   //
8572   //   For every cv-qualified or cv-unqualified object type T there
8573   //   exist candidate operator functions of the form
8574   //
8575   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8576   //        T&         operator[](T*, ptrdiff_t);
8577   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8578   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8579   //        T&         operator[](ptrdiff_t, T*);
8580   void addSubscriptOverloads() {
8581     for (BuiltinCandidateTypeSet::iterator
8582               Ptr = CandidateTypes[0].pointer_begin(),
8583            PtrEnd = CandidateTypes[0].pointer_end();
8584          Ptr != PtrEnd; ++Ptr) {
8585       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8586       QualType PointeeType = (*Ptr)->getPointeeType();
8587       if (!PointeeType->isObjectType())
8588         continue;
8589 
8590       // T& operator[](T*, ptrdiff_t)
8591       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8592     }
8593 
8594     for (BuiltinCandidateTypeSet::iterator
8595               Ptr = CandidateTypes[1].pointer_begin(),
8596            PtrEnd = CandidateTypes[1].pointer_end();
8597          Ptr != PtrEnd; ++Ptr) {
8598       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8599       QualType PointeeType = (*Ptr)->getPointeeType();
8600       if (!PointeeType->isObjectType())
8601         continue;
8602 
8603       // T& operator[](ptrdiff_t, T*)
8604       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8605     }
8606   }
8607 
8608   // C++ [over.built]p11:
8609   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8610   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8611   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8612   //    there exist candidate operator functions of the form
8613   //
8614   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8615   //
8616   //    where CV12 is the union of CV1 and CV2.
8617   void addArrowStarOverloads() {
8618     for (BuiltinCandidateTypeSet::iterator
8619              Ptr = CandidateTypes[0].pointer_begin(),
8620            PtrEnd = CandidateTypes[0].pointer_end();
8621          Ptr != PtrEnd; ++Ptr) {
8622       QualType C1Ty = (*Ptr);
8623       QualType C1;
8624       QualifierCollector Q1;
8625       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8626       if (!isa<RecordType>(C1))
8627         continue;
8628       // heuristic to reduce number of builtin candidates in the set.
8629       // Add volatile/restrict version only if there are conversions to a
8630       // volatile/restrict type.
8631       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8632         continue;
8633       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8634         continue;
8635       for (BuiltinCandidateTypeSet::iterator
8636                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8637              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8638            MemPtr != MemPtrEnd; ++MemPtr) {
8639         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8640         QualType C2 = QualType(mptr->getClass(), 0);
8641         C2 = C2.getUnqualifiedType();
8642         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8643           break;
8644         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8645         // build CV12 T&
8646         QualType T = mptr->getPointeeType();
8647         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8648             T.isVolatileQualified())
8649           continue;
8650         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8651             T.isRestrictQualified())
8652           continue;
8653         T = Q1.apply(S.Context, T);
8654         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8655       }
8656     }
8657   }
8658 
8659   // Note that we don't consider the first argument, since it has been
8660   // contextually converted to bool long ago. The candidates below are
8661   // therefore added as binary.
8662   //
8663   // C++ [over.built]p25:
8664   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8665   //   enumeration type, there exist candidate operator functions of the form
8666   //
8667   //        T        operator?(bool, T, T);
8668   //
8669   void addConditionalOperatorOverloads() {
8670     /// Set of (canonical) types that we've already handled.
8671     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8672 
8673     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8674       for (BuiltinCandidateTypeSet::iterator
8675                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8676              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8677            Ptr != PtrEnd; ++Ptr) {
8678         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8679           continue;
8680 
8681         QualType ParamTypes[2] = { *Ptr, *Ptr };
8682         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8683       }
8684 
8685       for (BuiltinCandidateTypeSet::iterator
8686                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8687              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8688            MemPtr != MemPtrEnd; ++MemPtr) {
8689         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8690           continue;
8691 
8692         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8693         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8694       }
8695 
8696       if (S.getLangOpts().CPlusPlus11) {
8697         for (BuiltinCandidateTypeSet::iterator
8698                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8699                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8700              Enum != EnumEnd; ++Enum) {
8701           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8702             continue;
8703 
8704           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8705             continue;
8706 
8707           QualType ParamTypes[2] = { *Enum, *Enum };
8708           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8709         }
8710       }
8711     }
8712   }
8713 };
8714 
8715 } // end anonymous namespace
8716 
8717 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8718 /// operator overloads to the candidate set (C++ [over.built]), based
8719 /// on the operator @p Op and the arguments given. For example, if the
8720 /// operator is a binary '+', this routine might add "int
8721 /// operator+(int, int)" to cover integer addition.
8722 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8723                                         SourceLocation OpLoc,
8724                                         ArrayRef<Expr *> Args,
8725                                         OverloadCandidateSet &CandidateSet) {
8726   // Find all of the types that the arguments can convert to, but only
8727   // if the operator we're looking at has built-in operator candidates
8728   // that make use of these types. Also record whether we encounter non-record
8729   // candidate types or either arithmetic or enumeral candidate types.
8730   Qualifiers VisibleTypeConversionsQuals;
8731   VisibleTypeConversionsQuals.addConst();
8732   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8733     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8734 
8735   bool HasNonRecordCandidateType = false;
8736   bool HasArithmeticOrEnumeralCandidateType = false;
8737   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8738   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8739     CandidateTypes.emplace_back(*this);
8740     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8741                                                  OpLoc,
8742                                                  true,
8743                                                  (Op == OO_Exclaim ||
8744                                                   Op == OO_AmpAmp ||
8745                                                   Op == OO_PipePipe),
8746                                                  VisibleTypeConversionsQuals);
8747     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8748         CandidateTypes[ArgIdx].hasNonRecordTypes();
8749     HasArithmeticOrEnumeralCandidateType =
8750         HasArithmeticOrEnumeralCandidateType ||
8751         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8752   }
8753 
8754   // Exit early when no non-record types have been added to the candidate set
8755   // for any of the arguments to the operator.
8756   //
8757   // We can't exit early for !, ||, or &&, since there we have always have
8758   // 'bool' overloads.
8759   if (!HasNonRecordCandidateType &&
8760       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8761     return;
8762 
8763   // Setup an object to manage the common state for building overloads.
8764   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8765                                            VisibleTypeConversionsQuals,
8766                                            HasArithmeticOrEnumeralCandidateType,
8767                                            CandidateTypes, CandidateSet);
8768 
8769   // Dispatch over the operation to add in only those overloads which apply.
8770   switch (Op) {
8771   case OO_None:
8772   case NUM_OVERLOADED_OPERATORS:
8773     llvm_unreachable("Expected an overloaded operator");
8774 
8775   case OO_New:
8776   case OO_Delete:
8777   case OO_Array_New:
8778   case OO_Array_Delete:
8779   case OO_Call:
8780     llvm_unreachable(
8781                     "Special operators don't use AddBuiltinOperatorCandidates");
8782 
8783   case OO_Comma:
8784   case OO_Arrow:
8785   case OO_Coawait:
8786     // C++ [over.match.oper]p3:
8787     //   -- For the operator ',', the unary operator '&', the
8788     //      operator '->', or the operator 'co_await', the
8789     //      built-in candidates set is empty.
8790     break;
8791 
8792   case OO_Plus: // '+' is either unary or binary
8793     if (Args.size() == 1)
8794       OpBuilder.addUnaryPlusPointerOverloads();
8795     LLVM_FALLTHROUGH;
8796 
8797   case OO_Minus: // '-' is either unary or binary
8798     if (Args.size() == 1) {
8799       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8800     } else {
8801       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8802       OpBuilder.addGenericBinaryArithmeticOverloads();
8803     }
8804     break;
8805 
8806   case OO_Star: // '*' is either unary or binary
8807     if (Args.size() == 1)
8808       OpBuilder.addUnaryStarPointerOverloads();
8809     else
8810       OpBuilder.addGenericBinaryArithmeticOverloads();
8811     break;
8812 
8813   case OO_Slash:
8814     OpBuilder.addGenericBinaryArithmeticOverloads();
8815     break;
8816 
8817   case OO_PlusPlus:
8818   case OO_MinusMinus:
8819     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8820     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8821     break;
8822 
8823   case OO_EqualEqual:
8824   case OO_ExclaimEqual:
8825     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8826     LLVM_FALLTHROUGH;
8827 
8828   case OO_Less:
8829   case OO_Greater:
8830   case OO_LessEqual:
8831   case OO_GreaterEqual:
8832     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8833     OpBuilder.addGenericBinaryArithmeticOverloads();
8834     break;
8835 
8836   case OO_Spaceship:
8837     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8838     OpBuilder.addThreeWayArithmeticOverloads();
8839     break;
8840 
8841   case OO_Percent:
8842   case OO_Caret:
8843   case OO_Pipe:
8844   case OO_LessLess:
8845   case OO_GreaterGreater:
8846     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8847     break;
8848 
8849   case OO_Amp: // '&' is either unary or binary
8850     if (Args.size() == 1)
8851       // C++ [over.match.oper]p3:
8852       //   -- For the operator ',', the unary operator '&', or the
8853       //      operator '->', the built-in candidates set is empty.
8854       break;
8855 
8856     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8857     break;
8858 
8859   case OO_Tilde:
8860     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8861     break;
8862 
8863   case OO_Equal:
8864     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8865     LLVM_FALLTHROUGH;
8866 
8867   case OO_PlusEqual:
8868   case OO_MinusEqual:
8869     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8870     LLVM_FALLTHROUGH;
8871 
8872   case OO_StarEqual:
8873   case OO_SlashEqual:
8874     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8875     break;
8876 
8877   case OO_PercentEqual:
8878   case OO_LessLessEqual:
8879   case OO_GreaterGreaterEqual:
8880   case OO_AmpEqual:
8881   case OO_CaretEqual:
8882   case OO_PipeEqual:
8883     OpBuilder.addAssignmentIntegralOverloads();
8884     break;
8885 
8886   case OO_Exclaim:
8887     OpBuilder.addExclaimOverload();
8888     break;
8889 
8890   case OO_AmpAmp:
8891   case OO_PipePipe:
8892     OpBuilder.addAmpAmpOrPipePipeOverload();
8893     break;
8894 
8895   case OO_Subscript:
8896     OpBuilder.addSubscriptOverloads();
8897     break;
8898 
8899   case OO_ArrowStar:
8900     OpBuilder.addArrowStarOverloads();
8901     break;
8902 
8903   case OO_Conditional:
8904     OpBuilder.addConditionalOperatorOverloads();
8905     OpBuilder.addGenericBinaryArithmeticOverloads();
8906     break;
8907   }
8908 }
8909 
8910 /// Add function candidates found via argument-dependent lookup
8911 /// to the set of overloading candidates.
8912 ///
8913 /// This routine performs argument-dependent name lookup based on the
8914 /// given function name (which may also be an operator name) and adds
8915 /// all of the overload candidates found by ADL to the overload
8916 /// candidate set (C++ [basic.lookup.argdep]).
8917 void
8918 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8919                                            SourceLocation Loc,
8920                                            ArrayRef<Expr *> Args,
8921                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8922                                            OverloadCandidateSet& CandidateSet,
8923                                            bool PartialOverloading) {
8924   ADLResult Fns;
8925 
8926   // FIXME: This approach for uniquing ADL results (and removing
8927   // redundant candidates from the set) relies on pointer-equality,
8928   // which means we need to key off the canonical decl.  However,
8929   // always going back to the canonical decl might not get us the
8930   // right set of default arguments.  What default arguments are
8931   // we supposed to consider on ADL candidates, anyway?
8932 
8933   // FIXME: Pass in the explicit template arguments?
8934   ArgumentDependentLookup(Name, Loc, Args, Fns);
8935 
8936   // Erase all of the candidates we already knew about.
8937   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8938                                    CandEnd = CandidateSet.end();
8939        Cand != CandEnd; ++Cand)
8940     if (Cand->Function) {
8941       Fns.erase(Cand->Function);
8942       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8943         Fns.erase(FunTmpl);
8944     }
8945 
8946   // For each of the ADL candidates we found, add it to the overload
8947   // set.
8948   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8949     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8950 
8951     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8952       if (ExplicitTemplateArgs)
8953         continue;
8954 
8955       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
8956                            /*SupressUserConversions=*/false, PartialOverloading,
8957                            /*AllowExplicit=*/false, ADLCallKind::UsesADL);
8958     } else {
8959       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl,
8960                                    ExplicitTemplateArgs, Args, CandidateSet,
8961                                    /*SupressUserConversions=*/false,
8962                                    PartialOverloading, ADLCallKind::UsesADL);
8963     }
8964   }
8965 }
8966 
8967 namespace {
8968 enum class Comparison { Equal, Better, Worse };
8969 }
8970 
8971 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8972 /// overload resolution.
8973 ///
8974 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8975 /// Cand1's first N enable_if attributes have precisely the same conditions as
8976 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8977 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8978 ///
8979 /// Note that you can have a pair of candidates such that Cand1's enable_if
8980 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8981 /// worse than Cand1's.
8982 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8983                                        const FunctionDecl *Cand2) {
8984   // Common case: One (or both) decls don't have enable_if attrs.
8985   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8986   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8987   if (!Cand1Attr || !Cand2Attr) {
8988     if (Cand1Attr == Cand2Attr)
8989       return Comparison::Equal;
8990     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8991   }
8992 
8993   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
8994   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
8995 
8996   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8997   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
8998     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
8999     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9000 
9001     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9002     // has fewer enable_if attributes than Cand2, and vice versa.
9003     if (!Cand1A)
9004       return Comparison::Worse;
9005     if (!Cand2A)
9006       return Comparison::Better;
9007 
9008     Cand1ID.clear();
9009     Cand2ID.clear();
9010 
9011     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9012     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9013     if (Cand1ID != Cand2ID)
9014       return Comparison::Worse;
9015   }
9016 
9017   return Comparison::Equal;
9018 }
9019 
9020 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9021                                           const OverloadCandidate &Cand2) {
9022   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9023       !Cand2.Function->isMultiVersion())
9024     return false;
9025 
9026   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9027   // is obviously better.
9028   if (Cand1.Function->isInvalidDecl()) return false;
9029   if (Cand2.Function->isInvalidDecl()) return true;
9030 
9031   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9032   // cpu_dispatch, else arbitrarily based on the identifiers.
9033   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9034   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9035   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9036   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9037 
9038   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9039     return false;
9040 
9041   if (Cand1CPUDisp && !Cand2CPUDisp)
9042     return true;
9043   if (Cand2CPUDisp && !Cand1CPUDisp)
9044     return false;
9045 
9046   if (Cand1CPUSpec && Cand2CPUSpec) {
9047     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9048       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9049 
9050     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9051         FirstDiff = std::mismatch(
9052             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9053             Cand2CPUSpec->cpus_begin(),
9054             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9055               return LHS->getName() == RHS->getName();
9056             });
9057 
9058     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9059            "Two different cpu-specific versions should not have the same "
9060            "identifier list, otherwise they'd be the same decl!");
9061     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9062   }
9063   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9064 }
9065 
9066 /// isBetterOverloadCandidate - Determines whether the first overload
9067 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9068 bool clang::isBetterOverloadCandidate(
9069     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9070     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9071   // Define viable functions to be better candidates than non-viable
9072   // functions.
9073   if (!Cand2.Viable)
9074     return Cand1.Viable;
9075   else if (!Cand1.Viable)
9076     return false;
9077 
9078   // C++ [over.match.best]p1:
9079   //
9080   //   -- if F is a static member function, ICS1(F) is defined such
9081   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9082   //      any function G, and, symmetrically, ICS1(G) is neither
9083   //      better nor worse than ICS1(F).
9084   unsigned StartArg = 0;
9085   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9086     StartArg = 1;
9087 
9088   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9089     // We don't allow incompatible pointer conversions in C++.
9090     if (!S.getLangOpts().CPlusPlus)
9091       return ICS.isStandard() &&
9092              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9093 
9094     // The only ill-formed conversion we allow in C++ is the string literal to
9095     // char* conversion, which is only considered ill-formed after C++11.
9096     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9097            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9098   };
9099 
9100   // Define functions that don't require ill-formed conversions for a given
9101   // argument to be better candidates than functions that do.
9102   unsigned NumArgs = Cand1.Conversions.size();
9103   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9104   bool HasBetterConversion = false;
9105   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9106     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9107     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9108     if (Cand1Bad != Cand2Bad) {
9109       if (Cand1Bad)
9110         return false;
9111       HasBetterConversion = true;
9112     }
9113   }
9114 
9115   if (HasBetterConversion)
9116     return true;
9117 
9118   // C++ [over.match.best]p1:
9119   //   A viable function F1 is defined to be a better function than another
9120   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9121   //   conversion sequence than ICSi(F2), and then...
9122   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9123     switch (CompareImplicitConversionSequences(S, Loc,
9124                                                Cand1.Conversions[ArgIdx],
9125                                                Cand2.Conversions[ArgIdx])) {
9126     case ImplicitConversionSequence::Better:
9127       // Cand1 has a better conversion sequence.
9128       HasBetterConversion = true;
9129       break;
9130 
9131     case ImplicitConversionSequence::Worse:
9132       // Cand1 can't be better than Cand2.
9133       return false;
9134 
9135     case ImplicitConversionSequence::Indistinguishable:
9136       // Do nothing.
9137       break;
9138     }
9139   }
9140 
9141   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9142   //       ICSj(F2), or, if not that,
9143   if (HasBetterConversion)
9144     return true;
9145 
9146   //   -- the context is an initialization by user-defined conversion
9147   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9148   //      from the return type of F1 to the destination type (i.e.,
9149   //      the type of the entity being initialized) is a better
9150   //      conversion sequence than the standard conversion sequence
9151   //      from the return type of F2 to the destination type.
9152   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9153       Cand1.Function && Cand2.Function &&
9154       isa<CXXConversionDecl>(Cand1.Function) &&
9155       isa<CXXConversionDecl>(Cand2.Function)) {
9156     // First check whether we prefer one of the conversion functions over the
9157     // other. This only distinguishes the results in non-standard, extension
9158     // cases such as the conversion from a lambda closure type to a function
9159     // pointer or block.
9160     ImplicitConversionSequence::CompareKind Result =
9161         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9162     if (Result == ImplicitConversionSequence::Indistinguishable)
9163       Result = CompareStandardConversionSequences(S, Loc,
9164                                                   Cand1.FinalConversion,
9165                                                   Cand2.FinalConversion);
9166 
9167     if (Result != ImplicitConversionSequence::Indistinguishable)
9168       return Result == ImplicitConversionSequence::Better;
9169 
9170     // FIXME: Compare kind of reference binding if conversion functions
9171     // convert to a reference type used in direct reference binding, per
9172     // C++14 [over.match.best]p1 section 2 bullet 3.
9173   }
9174 
9175   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9176   // as combined with the resolution to CWG issue 243.
9177   //
9178   // When the context is initialization by constructor ([over.match.ctor] or
9179   // either phase of [over.match.list]), a constructor is preferred over
9180   // a conversion function.
9181   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9182       Cand1.Function && Cand2.Function &&
9183       isa<CXXConstructorDecl>(Cand1.Function) !=
9184           isa<CXXConstructorDecl>(Cand2.Function))
9185     return isa<CXXConstructorDecl>(Cand1.Function);
9186 
9187   //    -- F1 is a non-template function and F2 is a function template
9188   //       specialization, or, if not that,
9189   bool Cand1IsSpecialization = Cand1.Function &&
9190                                Cand1.Function->getPrimaryTemplate();
9191   bool Cand2IsSpecialization = Cand2.Function &&
9192                                Cand2.Function->getPrimaryTemplate();
9193   if (Cand1IsSpecialization != Cand2IsSpecialization)
9194     return Cand2IsSpecialization;
9195 
9196   //   -- F1 and F2 are function template specializations, and the function
9197   //      template for F1 is more specialized than the template for F2
9198   //      according to the partial ordering rules described in 14.5.5.2, or,
9199   //      if not that,
9200   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9201     if (FunctionTemplateDecl *BetterTemplate
9202           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9203                                          Cand2.Function->getPrimaryTemplate(),
9204                                          Loc,
9205                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9206                                                              : TPOC_Call,
9207                                          Cand1.ExplicitCallArguments,
9208                                          Cand2.ExplicitCallArguments))
9209       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9210   }
9211 
9212   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9213   // A derived-class constructor beats an (inherited) base class constructor.
9214   bool Cand1IsInherited =
9215       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9216   bool Cand2IsInherited =
9217       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9218   if (Cand1IsInherited != Cand2IsInherited)
9219     return Cand2IsInherited;
9220   else if (Cand1IsInherited) {
9221     assert(Cand2IsInherited);
9222     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9223     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9224     if (Cand1Class->isDerivedFrom(Cand2Class))
9225       return true;
9226     if (Cand2Class->isDerivedFrom(Cand1Class))
9227       return false;
9228     // Inherited from sibling base classes: still ambiguous.
9229   }
9230 
9231   // Check C++17 tie-breakers for deduction guides.
9232   {
9233     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9234     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9235     if (Guide1 && Guide2) {
9236       //  -- F1 is generated from a deduction-guide and F2 is not
9237       if (Guide1->isImplicit() != Guide2->isImplicit())
9238         return Guide2->isImplicit();
9239 
9240       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9241       if (Guide1->isCopyDeductionCandidate())
9242         return true;
9243     }
9244   }
9245 
9246   // Check for enable_if value-based overload resolution.
9247   if (Cand1.Function && Cand2.Function) {
9248     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9249     if (Cmp != Comparison::Equal)
9250       return Cmp == Comparison::Better;
9251   }
9252 
9253   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9254     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9255     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9256            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9257   }
9258 
9259   bool HasPS1 = Cand1.Function != nullptr &&
9260                 functionHasPassObjectSizeParams(Cand1.Function);
9261   bool HasPS2 = Cand2.Function != nullptr &&
9262                 functionHasPassObjectSizeParams(Cand2.Function);
9263   if (HasPS1 != HasPS2 && HasPS1)
9264     return true;
9265 
9266   return isBetterMultiversionCandidate(Cand1, Cand2);
9267 }
9268 
9269 /// Determine whether two declarations are "equivalent" for the purposes of
9270 /// name lookup and overload resolution. This applies when the same internal/no
9271 /// linkage entity is defined by two modules (probably by textually including
9272 /// the same header). In such a case, we don't consider the declarations to
9273 /// declare the same entity, but we also don't want lookups with both
9274 /// declarations visible to be ambiguous in some cases (this happens when using
9275 /// a modularized libstdc++).
9276 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9277                                                   const NamedDecl *B) {
9278   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9279   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9280   if (!VA || !VB)
9281     return false;
9282 
9283   // The declarations must be declaring the same name as an internal linkage
9284   // entity in different modules.
9285   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9286           VB->getDeclContext()->getRedeclContext()) ||
9287       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9288           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9289       VA->isExternallyVisible() || VB->isExternallyVisible())
9290     return false;
9291 
9292   // Check that the declarations appear to be equivalent.
9293   //
9294   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9295   // For constants and functions, we should check the initializer or body is
9296   // the same. For non-constant variables, we shouldn't allow it at all.
9297   if (Context.hasSameType(VA->getType(), VB->getType()))
9298     return true;
9299 
9300   // Enum constants within unnamed enumerations will have different types, but
9301   // may still be similar enough to be interchangeable for our purposes.
9302   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9303     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9304       // Only handle anonymous enums. If the enumerations were named and
9305       // equivalent, they would have been merged to the same type.
9306       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9307       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9308       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9309           !Context.hasSameType(EnumA->getIntegerType(),
9310                                EnumB->getIntegerType()))
9311         return false;
9312       // Allow this only if the value is the same for both enumerators.
9313       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9314     }
9315   }
9316 
9317   // Nothing else is sufficiently similar.
9318   return false;
9319 }
9320 
9321 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9322     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9323   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9324 
9325   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9326   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9327       << !M << (M ? M->getFullModuleName() : "");
9328 
9329   for (auto *E : Equiv) {
9330     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9331     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9332         << !M << (M ? M->getFullModuleName() : "");
9333   }
9334 }
9335 
9336 /// Computes the best viable function (C++ 13.3.3)
9337 /// within an overload candidate set.
9338 ///
9339 /// \param Loc The location of the function name (or operator symbol) for
9340 /// which overload resolution occurs.
9341 ///
9342 /// \param Best If overload resolution was successful or found a deleted
9343 /// function, \p Best points to the candidate function found.
9344 ///
9345 /// \returns The result of overload resolution.
9346 OverloadingResult
9347 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9348                                          iterator &Best) {
9349   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9350   std::transform(begin(), end(), std::back_inserter(Candidates),
9351                  [](OverloadCandidate &Cand) { return &Cand; });
9352 
9353   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9354   // are accepted by both clang and NVCC. However, during a particular
9355   // compilation mode only one call variant is viable. We need to
9356   // exclude non-viable overload candidates from consideration based
9357   // only on their host/device attributes. Specifically, if one
9358   // candidate call is WrongSide and the other is SameSide, we ignore
9359   // the WrongSide candidate.
9360   if (S.getLangOpts().CUDA) {
9361     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9362     bool ContainsSameSideCandidate =
9363         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9364           return Cand->Function &&
9365                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9366                      Sema::CFP_SameSide;
9367         });
9368     if (ContainsSameSideCandidate) {
9369       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9370         return Cand->Function &&
9371                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9372                    Sema::CFP_WrongSide;
9373       };
9374       llvm::erase_if(Candidates, IsWrongSideCandidate);
9375     }
9376   }
9377 
9378   // Find the best viable function.
9379   Best = end();
9380   for (auto *Cand : Candidates)
9381     if (Cand->Viable)
9382       if (Best == end() ||
9383           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9384         Best = Cand;
9385 
9386   // If we didn't find any viable functions, abort.
9387   if (Best == end())
9388     return OR_No_Viable_Function;
9389 
9390   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9391 
9392   // Make sure that this function is better than every other viable
9393   // function. If not, we have an ambiguity.
9394   for (auto *Cand : Candidates) {
9395     if (Cand->Viable && Cand != Best &&
9396         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9397       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9398                                                    Cand->Function)) {
9399         EquivalentCands.push_back(Cand->Function);
9400         continue;
9401       }
9402 
9403       Best = end();
9404       return OR_Ambiguous;
9405     }
9406   }
9407 
9408   // Best is the best viable function.
9409   if (Best->Function &&
9410       (Best->Function->isDeleted() ||
9411        S.isFunctionConsideredUnavailable(Best->Function)))
9412     return OR_Deleted;
9413 
9414   if (!EquivalentCands.empty())
9415     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9416                                                     EquivalentCands);
9417 
9418   return OR_Success;
9419 }
9420 
9421 namespace {
9422 
9423 enum OverloadCandidateKind {
9424   oc_function,
9425   oc_method,
9426   oc_constructor,
9427   oc_implicit_default_constructor,
9428   oc_implicit_copy_constructor,
9429   oc_implicit_move_constructor,
9430   oc_implicit_copy_assignment,
9431   oc_implicit_move_assignment,
9432   oc_inherited_constructor
9433 };
9434 
9435 enum OverloadCandidateSelect {
9436   ocs_non_template,
9437   ocs_template,
9438   ocs_described_template,
9439 };
9440 
9441 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9442 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9443                           std::string &Description) {
9444 
9445   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9446   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9447     isTemplate = true;
9448     Description = S.getTemplateArgumentBindingsText(
9449         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9450   }
9451 
9452   OverloadCandidateSelect Select = [&]() {
9453     if (!Description.empty())
9454       return ocs_described_template;
9455     return isTemplate ? ocs_template : ocs_non_template;
9456   }();
9457 
9458   OverloadCandidateKind Kind = [&]() {
9459     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9460       if (!Ctor->isImplicit()) {
9461         if (isa<ConstructorUsingShadowDecl>(Found))
9462           return oc_inherited_constructor;
9463         else
9464           return oc_constructor;
9465       }
9466 
9467       if (Ctor->isDefaultConstructor())
9468         return oc_implicit_default_constructor;
9469 
9470       if (Ctor->isMoveConstructor())
9471         return oc_implicit_move_constructor;
9472 
9473       assert(Ctor->isCopyConstructor() &&
9474              "unexpected sort of implicit constructor");
9475       return oc_implicit_copy_constructor;
9476     }
9477 
9478     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9479       // This actually gets spelled 'candidate function' for now, but
9480       // it doesn't hurt to split it out.
9481       if (!Meth->isImplicit())
9482         return oc_method;
9483 
9484       if (Meth->isMoveAssignmentOperator())
9485         return oc_implicit_move_assignment;
9486 
9487       if (Meth->isCopyAssignmentOperator())
9488         return oc_implicit_copy_assignment;
9489 
9490       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9491       return oc_method;
9492     }
9493 
9494     return oc_function;
9495   }();
9496 
9497   return std::make_pair(Kind, Select);
9498 }
9499 
9500 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9501   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9502   // set.
9503   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9504     S.Diag(FoundDecl->getLocation(),
9505            diag::note_ovl_candidate_inherited_constructor)
9506       << Shadow->getNominatedBaseClass();
9507 }
9508 
9509 } // end anonymous namespace
9510 
9511 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9512                                     const FunctionDecl *FD) {
9513   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9514     bool AlwaysTrue;
9515     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9516       return false;
9517     if (!AlwaysTrue)
9518       return false;
9519   }
9520   return true;
9521 }
9522 
9523 /// Returns true if we can take the address of the function.
9524 ///
9525 /// \param Complain - If true, we'll emit a diagnostic
9526 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9527 ///   we in overload resolution?
9528 /// \param Loc - The location of the statement we're complaining about. Ignored
9529 ///   if we're not complaining, or if we're in overload resolution.
9530 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9531                                               bool Complain,
9532                                               bool InOverloadResolution,
9533                                               SourceLocation Loc) {
9534   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9535     if (Complain) {
9536       if (InOverloadResolution)
9537         S.Diag(FD->getBeginLoc(),
9538                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9539       else
9540         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9541     }
9542     return false;
9543   }
9544 
9545   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9546     return P->hasAttr<PassObjectSizeAttr>();
9547   });
9548   if (I == FD->param_end())
9549     return true;
9550 
9551   if (Complain) {
9552     // Add one to ParamNo because it's user-facing
9553     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9554     if (InOverloadResolution)
9555       S.Diag(FD->getLocation(),
9556              diag::note_ovl_candidate_has_pass_object_size_params)
9557           << ParamNo;
9558     else
9559       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9560           << FD << ParamNo;
9561   }
9562   return false;
9563 }
9564 
9565 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9566                                                const FunctionDecl *FD) {
9567   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9568                                            /*InOverloadResolution=*/true,
9569                                            /*Loc=*/SourceLocation());
9570 }
9571 
9572 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9573                                              bool Complain,
9574                                              SourceLocation Loc) {
9575   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9576                                              /*InOverloadResolution=*/false,
9577                                              Loc);
9578 }
9579 
9580 // Notes the location of an overload candidate.
9581 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9582                                  QualType DestType, bool TakingAddress) {
9583   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9584     return;
9585   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9586       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9587     return;
9588 
9589   std::string FnDesc;
9590   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9591       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9592   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9593                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9594                          << Fn << FnDesc;
9595 
9596   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9597   Diag(Fn->getLocation(), PD);
9598   MaybeEmitInheritedConstructorNote(*this, Found);
9599 }
9600 
9601 // Notes the location of all overload candidates designated through
9602 // OverloadedExpr
9603 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9604                                      bool TakingAddress) {
9605   assert(OverloadedExpr->getType() == Context.OverloadTy);
9606 
9607   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9608   OverloadExpr *OvlExpr = Ovl.Expression;
9609 
9610   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9611                             IEnd = OvlExpr->decls_end();
9612        I != IEnd; ++I) {
9613     if (FunctionTemplateDecl *FunTmpl =
9614                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9615       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9616                             TakingAddress);
9617     } else if (FunctionDecl *Fun
9618                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9619       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9620     }
9621   }
9622 }
9623 
9624 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9625 /// "lead" diagnostic; it will be given two arguments, the source and
9626 /// target types of the conversion.
9627 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9628                                  Sema &S,
9629                                  SourceLocation CaretLoc,
9630                                  const PartialDiagnostic &PDiag) const {
9631   S.Diag(CaretLoc, PDiag)
9632     << Ambiguous.getFromType() << Ambiguous.getToType();
9633   // FIXME: The note limiting machinery is borrowed from
9634   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9635   // refactoring here.
9636   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9637   unsigned CandsShown = 0;
9638   AmbiguousConversionSequence::const_iterator I, E;
9639   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9640     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9641       break;
9642     ++CandsShown;
9643     S.NoteOverloadCandidate(I->first, I->second);
9644   }
9645   if (I != E)
9646     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9647 }
9648 
9649 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9650                                   unsigned I, bool TakingCandidateAddress) {
9651   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9652   assert(Conv.isBad());
9653   assert(Cand->Function && "for now, candidate must be a function");
9654   FunctionDecl *Fn = Cand->Function;
9655 
9656   // There's a conversion slot for the object argument if this is a
9657   // non-constructor method.  Note that 'I' corresponds the
9658   // conversion-slot index.
9659   bool isObjectArgument = false;
9660   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9661     if (I == 0)
9662       isObjectArgument = true;
9663     else
9664       I--;
9665   }
9666 
9667   std::string FnDesc;
9668   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9669       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9670 
9671   Expr *FromExpr = Conv.Bad.FromExpr;
9672   QualType FromTy = Conv.Bad.getFromType();
9673   QualType ToTy = Conv.Bad.getToType();
9674 
9675   if (FromTy == S.Context.OverloadTy) {
9676     assert(FromExpr && "overload set argument came from implicit argument?");
9677     Expr *E = FromExpr->IgnoreParens();
9678     if (isa<UnaryOperator>(E))
9679       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9680     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9681 
9682     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9683         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9684         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9685         << Name << I + 1;
9686     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9687     return;
9688   }
9689 
9690   // Do some hand-waving analysis to see if the non-viability is due
9691   // to a qualifier mismatch.
9692   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9693   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9694   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9695     CToTy = RT->getPointeeType();
9696   else {
9697     // TODO: detect and diagnose the full richness of const mismatches.
9698     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9699       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9700         CFromTy = FromPT->getPointeeType();
9701         CToTy = ToPT->getPointeeType();
9702       }
9703   }
9704 
9705   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9706       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9707     Qualifiers FromQs = CFromTy.getQualifiers();
9708     Qualifiers ToQs = CToTy.getQualifiers();
9709 
9710     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9711       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9712           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9713           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9714           << ToTy << (unsigned)isObjectArgument << I + 1;
9715       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9716       return;
9717     }
9718 
9719     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9720       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9721           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9722           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9723           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9724           << (unsigned)isObjectArgument << I + 1;
9725       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9726       return;
9727     }
9728 
9729     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9730       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9731           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9732           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9733           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9734           << (unsigned)isObjectArgument << I + 1;
9735       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9736       return;
9737     }
9738 
9739     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9740       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9741           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9742           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9743           << FromQs.hasUnaligned() << I + 1;
9744       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9745       return;
9746     }
9747 
9748     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9749     assert(CVR && "unexpected qualifiers mismatch");
9750 
9751     if (isObjectArgument) {
9752       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9753           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9754           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9755           << (CVR - 1);
9756     } else {
9757       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9758           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9759           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9760           << (CVR - 1) << I + 1;
9761     }
9762     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9763     return;
9764   }
9765 
9766   // Special diagnostic for failure to convert an initializer list, since
9767   // telling the user that it has type void is not useful.
9768   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9769     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9770         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9771         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9772         << ToTy << (unsigned)isObjectArgument << I + 1;
9773     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9774     return;
9775   }
9776 
9777   // Diagnose references or pointers to incomplete types differently,
9778   // since it's far from impossible that the incompleteness triggered
9779   // the failure.
9780   QualType TempFromTy = FromTy.getNonReferenceType();
9781   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9782     TempFromTy = PTy->getPointeeType();
9783   if (TempFromTy->isIncompleteType()) {
9784     // Emit the generic diagnostic and, optionally, add the hints to it.
9785     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9786         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9787         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9788         << ToTy << (unsigned)isObjectArgument << I + 1
9789         << (unsigned)(Cand->Fix.Kind);
9790 
9791     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9792     return;
9793   }
9794 
9795   // Diagnose base -> derived pointer conversions.
9796   unsigned BaseToDerivedConversion = 0;
9797   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9798     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9799       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9800                                                FromPtrTy->getPointeeType()) &&
9801           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9802           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9803           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9804                           FromPtrTy->getPointeeType()))
9805         BaseToDerivedConversion = 1;
9806     }
9807   } else if (const ObjCObjectPointerType *FromPtrTy
9808                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9809     if (const ObjCObjectPointerType *ToPtrTy
9810                                         = ToTy->getAs<ObjCObjectPointerType>())
9811       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9812         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9813           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9814                                                 FromPtrTy->getPointeeType()) &&
9815               FromIface->isSuperClassOf(ToIface))
9816             BaseToDerivedConversion = 2;
9817   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9818     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9819         !FromTy->isIncompleteType() &&
9820         !ToRefTy->getPointeeType()->isIncompleteType() &&
9821         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9822       BaseToDerivedConversion = 3;
9823     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9824                ToTy.getNonReferenceType().getCanonicalType() ==
9825                FromTy.getNonReferenceType().getCanonicalType()) {
9826       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9827           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9828           << (unsigned)isObjectArgument << I + 1
9829           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9830       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9831       return;
9832     }
9833   }
9834 
9835   if (BaseToDerivedConversion) {
9836     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9837         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9838         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9839         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9840     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9841     return;
9842   }
9843 
9844   if (isa<ObjCObjectPointerType>(CFromTy) &&
9845       isa<PointerType>(CToTy)) {
9846       Qualifiers FromQs = CFromTy.getQualifiers();
9847       Qualifiers ToQs = CToTy.getQualifiers();
9848       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9849         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9850             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9851             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9852             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9853         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9854         return;
9855       }
9856   }
9857 
9858   if (TakingCandidateAddress &&
9859       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9860     return;
9861 
9862   // Emit the generic diagnostic and, optionally, add the hints to it.
9863   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9864   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9865         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9866         << ToTy << (unsigned)isObjectArgument << I + 1
9867         << (unsigned)(Cand->Fix.Kind);
9868 
9869   // If we can fix the conversion, suggest the FixIts.
9870   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9871        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9872     FDiag << *HI;
9873   S.Diag(Fn->getLocation(), FDiag);
9874 
9875   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9876 }
9877 
9878 /// Additional arity mismatch diagnosis specific to a function overload
9879 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9880 /// over a candidate in any candidate set.
9881 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9882                                unsigned NumArgs) {
9883   FunctionDecl *Fn = Cand->Function;
9884   unsigned MinParams = Fn->getMinRequiredArguments();
9885 
9886   // With invalid overloaded operators, it's possible that we think we
9887   // have an arity mismatch when in fact it looks like we have the
9888   // right number of arguments, because only overloaded operators have
9889   // the weird behavior of overloading member and non-member functions.
9890   // Just don't report anything.
9891   if (Fn->isInvalidDecl() &&
9892       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9893     return true;
9894 
9895   if (NumArgs < MinParams) {
9896     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9897            (Cand->FailureKind == ovl_fail_bad_deduction &&
9898             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9899   } else {
9900     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9901            (Cand->FailureKind == ovl_fail_bad_deduction &&
9902             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9903   }
9904 
9905   return false;
9906 }
9907 
9908 /// General arity mismatch diagnosis over a candidate in a candidate set.
9909 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9910                                   unsigned NumFormalArgs) {
9911   assert(isa<FunctionDecl>(D) &&
9912       "The templated declaration should at least be a function"
9913       " when diagnosing bad template argument deduction due to too many"
9914       " or too few arguments");
9915 
9916   FunctionDecl *Fn = cast<FunctionDecl>(D);
9917 
9918   // TODO: treat calls to a missing default constructor as a special case
9919   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9920   unsigned MinParams = Fn->getMinRequiredArguments();
9921 
9922   // at least / at most / exactly
9923   unsigned mode, modeCount;
9924   if (NumFormalArgs < MinParams) {
9925     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9926         FnTy->isTemplateVariadic())
9927       mode = 0; // "at least"
9928     else
9929       mode = 2; // "exactly"
9930     modeCount = MinParams;
9931   } else {
9932     if (MinParams != FnTy->getNumParams())
9933       mode = 1; // "at most"
9934     else
9935       mode = 2; // "exactly"
9936     modeCount = FnTy->getNumParams();
9937   }
9938 
9939   std::string Description;
9940   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9941       ClassifyOverloadCandidate(S, Found, Fn, Description);
9942 
9943   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9944     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9945         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9946         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9947   else
9948     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9949         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9950         << Description << mode << modeCount << NumFormalArgs;
9951 
9952   MaybeEmitInheritedConstructorNote(S, Found);
9953 }
9954 
9955 /// Arity mismatch diagnosis specific to a function overload candidate.
9956 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9957                                   unsigned NumFormalArgs) {
9958   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9959     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9960 }
9961 
9962 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9963   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9964     return TD;
9965   llvm_unreachable("Unsupported: Getting the described template declaration"
9966                    " for bad deduction diagnosis");
9967 }
9968 
9969 /// Diagnose a failed template-argument deduction.
9970 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9971                                  DeductionFailureInfo &DeductionFailure,
9972                                  unsigned NumArgs,
9973                                  bool TakingCandidateAddress) {
9974   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9975   NamedDecl *ParamD;
9976   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9977   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9978   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9979   switch (DeductionFailure.Result) {
9980   case Sema::TDK_Success:
9981     llvm_unreachable("TDK_success while diagnosing bad deduction");
9982 
9983   case Sema::TDK_Incomplete: {
9984     assert(ParamD && "no parameter found for incomplete deduction result");
9985     S.Diag(Templated->getLocation(),
9986            diag::note_ovl_candidate_incomplete_deduction)
9987         << ParamD->getDeclName();
9988     MaybeEmitInheritedConstructorNote(S, Found);
9989     return;
9990   }
9991 
9992   case Sema::TDK_IncompletePack: {
9993     assert(ParamD && "no parameter found for incomplete deduction result");
9994     S.Diag(Templated->getLocation(),
9995            diag::note_ovl_candidate_incomplete_deduction_pack)
9996         << ParamD->getDeclName()
9997         << (DeductionFailure.getFirstArg()->pack_size() + 1)
9998         << *DeductionFailure.getFirstArg();
9999     MaybeEmitInheritedConstructorNote(S, Found);
10000     return;
10001   }
10002 
10003   case Sema::TDK_Underqualified: {
10004     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10005     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10006 
10007     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10008 
10009     // Param will have been canonicalized, but it should just be a
10010     // qualified version of ParamD, so move the qualifiers to that.
10011     QualifierCollector Qs;
10012     Qs.strip(Param);
10013     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10014     assert(S.Context.hasSameType(Param, NonCanonParam));
10015 
10016     // Arg has also been canonicalized, but there's nothing we can do
10017     // about that.  It also doesn't matter as much, because it won't
10018     // have any template parameters in it (because deduction isn't
10019     // done on dependent types).
10020     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10021 
10022     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10023         << ParamD->getDeclName() << Arg << NonCanonParam;
10024     MaybeEmitInheritedConstructorNote(S, Found);
10025     return;
10026   }
10027 
10028   case Sema::TDK_Inconsistent: {
10029     assert(ParamD && "no parameter found for inconsistent deduction result");
10030     int which = 0;
10031     if (isa<TemplateTypeParmDecl>(ParamD))
10032       which = 0;
10033     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10034       // Deduction might have failed because we deduced arguments of two
10035       // different types for a non-type template parameter.
10036       // FIXME: Use a different TDK value for this.
10037       QualType T1 =
10038           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10039       QualType T2 =
10040           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10041       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10042         S.Diag(Templated->getLocation(),
10043                diag::note_ovl_candidate_inconsistent_deduction_types)
10044           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10045           << *DeductionFailure.getSecondArg() << T2;
10046         MaybeEmitInheritedConstructorNote(S, Found);
10047         return;
10048       }
10049 
10050       which = 1;
10051     } else {
10052       which = 2;
10053     }
10054 
10055     S.Diag(Templated->getLocation(),
10056            diag::note_ovl_candidate_inconsistent_deduction)
10057         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10058         << *DeductionFailure.getSecondArg();
10059     MaybeEmitInheritedConstructorNote(S, Found);
10060     return;
10061   }
10062 
10063   case Sema::TDK_InvalidExplicitArguments:
10064     assert(ParamD && "no parameter found for invalid explicit arguments");
10065     if (ParamD->getDeclName())
10066       S.Diag(Templated->getLocation(),
10067              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10068           << ParamD->getDeclName();
10069     else {
10070       int index = 0;
10071       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10072         index = TTP->getIndex();
10073       else if (NonTypeTemplateParmDecl *NTTP
10074                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10075         index = NTTP->getIndex();
10076       else
10077         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10078       S.Diag(Templated->getLocation(),
10079              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10080           << (index + 1);
10081     }
10082     MaybeEmitInheritedConstructorNote(S, Found);
10083     return;
10084 
10085   case Sema::TDK_TooManyArguments:
10086   case Sema::TDK_TooFewArguments:
10087     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10088     return;
10089 
10090   case Sema::TDK_InstantiationDepth:
10091     S.Diag(Templated->getLocation(),
10092            diag::note_ovl_candidate_instantiation_depth);
10093     MaybeEmitInheritedConstructorNote(S, Found);
10094     return;
10095 
10096   case Sema::TDK_SubstitutionFailure: {
10097     // Format the template argument list into the argument string.
10098     SmallString<128> TemplateArgString;
10099     if (TemplateArgumentList *Args =
10100             DeductionFailure.getTemplateArgumentList()) {
10101       TemplateArgString = " ";
10102       TemplateArgString += S.getTemplateArgumentBindingsText(
10103           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10104     }
10105 
10106     // If this candidate was disabled by enable_if, say so.
10107     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10108     if (PDiag && PDiag->second.getDiagID() ==
10109           diag::err_typename_nested_not_found_enable_if) {
10110       // FIXME: Use the source range of the condition, and the fully-qualified
10111       //        name of the enable_if template. These are both present in PDiag.
10112       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10113         << "'enable_if'" << TemplateArgString;
10114       return;
10115     }
10116 
10117     // We found a specific requirement that disabled the enable_if.
10118     if (PDiag && PDiag->second.getDiagID() ==
10119         diag::err_typename_nested_not_found_requirement) {
10120       S.Diag(Templated->getLocation(),
10121              diag::note_ovl_candidate_disabled_by_requirement)
10122         << PDiag->second.getStringArg(0) << TemplateArgString;
10123       return;
10124     }
10125 
10126     // Format the SFINAE diagnostic into the argument string.
10127     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10128     //        formatted message in another diagnostic.
10129     SmallString<128> SFINAEArgString;
10130     SourceRange R;
10131     if (PDiag) {
10132       SFINAEArgString = ": ";
10133       R = SourceRange(PDiag->first, PDiag->first);
10134       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10135     }
10136 
10137     S.Diag(Templated->getLocation(),
10138            diag::note_ovl_candidate_substitution_failure)
10139         << TemplateArgString << SFINAEArgString << R;
10140     MaybeEmitInheritedConstructorNote(S, Found);
10141     return;
10142   }
10143 
10144   case Sema::TDK_DeducedMismatch:
10145   case Sema::TDK_DeducedMismatchNested: {
10146     // Format the template argument list into the argument string.
10147     SmallString<128> TemplateArgString;
10148     if (TemplateArgumentList *Args =
10149             DeductionFailure.getTemplateArgumentList()) {
10150       TemplateArgString = " ";
10151       TemplateArgString += S.getTemplateArgumentBindingsText(
10152           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10153     }
10154 
10155     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10156         << (*DeductionFailure.getCallArgIndex() + 1)
10157         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10158         << TemplateArgString
10159         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10160     break;
10161   }
10162 
10163   case Sema::TDK_NonDeducedMismatch: {
10164     // FIXME: Provide a source location to indicate what we couldn't match.
10165     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10166     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10167     if (FirstTA.getKind() == TemplateArgument::Template &&
10168         SecondTA.getKind() == TemplateArgument::Template) {
10169       TemplateName FirstTN = FirstTA.getAsTemplate();
10170       TemplateName SecondTN = SecondTA.getAsTemplate();
10171       if (FirstTN.getKind() == TemplateName::Template &&
10172           SecondTN.getKind() == TemplateName::Template) {
10173         if (FirstTN.getAsTemplateDecl()->getName() ==
10174             SecondTN.getAsTemplateDecl()->getName()) {
10175           // FIXME: This fixes a bad diagnostic where both templates are named
10176           // the same.  This particular case is a bit difficult since:
10177           // 1) It is passed as a string to the diagnostic printer.
10178           // 2) The diagnostic printer only attempts to find a better
10179           //    name for types, not decls.
10180           // Ideally, this should folded into the diagnostic printer.
10181           S.Diag(Templated->getLocation(),
10182                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10183               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10184           return;
10185         }
10186       }
10187     }
10188 
10189     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10190         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10191       return;
10192 
10193     // FIXME: For generic lambda parameters, check if the function is a lambda
10194     // call operator, and if so, emit a prettier and more informative
10195     // diagnostic that mentions 'auto' and lambda in addition to
10196     // (or instead of?) the canonical template type parameters.
10197     S.Diag(Templated->getLocation(),
10198            diag::note_ovl_candidate_non_deduced_mismatch)
10199         << FirstTA << SecondTA;
10200     return;
10201   }
10202   // TODO: diagnose these individually, then kill off
10203   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10204   case Sema::TDK_MiscellaneousDeductionFailure:
10205     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10206     MaybeEmitInheritedConstructorNote(S, Found);
10207     return;
10208   case Sema::TDK_CUDATargetMismatch:
10209     S.Diag(Templated->getLocation(),
10210            diag::note_cuda_ovl_candidate_target_mismatch);
10211     return;
10212   }
10213 }
10214 
10215 /// Diagnose a failed template-argument deduction, for function calls.
10216 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10217                                  unsigned NumArgs,
10218                                  bool TakingCandidateAddress) {
10219   unsigned TDK = Cand->DeductionFailure.Result;
10220   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10221     if (CheckArityMismatch(S, Cand, NumArgs))
10222       return;
10223   }
10224   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10225                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10226 }
10227 
10228 /// CUDA: diagnose an invalid call across targets.
10229 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10230   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10231   FunctionDecl *Callee = Cand->Function;
10232 
10233   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10234                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10235 
10236   std::string FnDesc;
10237   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10238       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10239 
10240   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10241       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10242       << FnDesc /* Ignored */
10243       << CalleeTarget << CallerTarget;
10244 
10245   // This could be an implicit constructor for which we could not infer the
10246   // target due to a collsion. Diagnose that case.
10247   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10248   if (Meth != nullptr && Meth->isImplicit()) {
10249     CXXRecordDecl *ParentClass = Meth->getParent();
10250     Sema::CXXSpecialMember CSM;
10251 
10252     switch (FnKindPair.first) {
10253     default:
10254       return;
10255     case oc_implicit_default_constructor:
10256       CSM = Sema::CXXDefaultConstructor;
10257       break;
10258     case oc_implicit_copy_constructor:
10259       CSM = Sema::CXXCopyConstructor;
10260       break;
10261     case oc_implicit_move_constructor:
10262       CSM = Sema::CXXMoveConstructor;
10263       break;
10264     case oc_implicit_copy_assignment:
10265       CSM = Sema::CXXCopyAssignment;
10266       break;
10267     case oc_implicit_move_assignment:
10268       CSM = Sema::CXXMoveAssignment;
10269       break;
10270     };
10271 
10272     bool ConstRHS = false;
10273     if (Meth->getNumParams()) {
10274       if (const ReferenceType *RT =
10275               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10276         ConstRHS = RT->getPointeeType().isConstQualified();
10277       }
10278     }
10279 
10280     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10281                                               /* ConstRHS */ ConstRHS,
10282                                               /* Diagnose */ true);
10283   }
10284 }
10285 
10286 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10287   FunctionDecl *Callee = Cand->Function;
10288   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10289 
10290   S.Diag(Callee->getLocation(),
10291          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10292       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10293 }
10294 
10295 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10296   FunctionDecl *Callee = Cand->Function;
10297 
10298   S.Diag(Callee->getLocation(),
10299          diag::note_ovl_candidate_disabled_by_extension)
10300     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10301 }
10302 
10303 /// Generates a 'note' diagnostic for an overload candidate.  We've
10304 /// already generated a primary error at the call site.
10305 ///
10306 /// It really does need to be a single diagnostic with its caret
10307 /// pointed at the candidate declaration.  Yes, this creates some
10308 /// major challenges of technical writing.  Yes, this makes pointing
10309 /// out problems with specific arguments quite awkward.  It's still
10310 /// better than generating twenty screens of text for every failed
10311 /// overload.
10312 ///
10313 /// It would be great to be able to express per-candidate problems
10314 /// more richly for those diagnostic clients that cared, but we'd
10315 /// still have to be just as careful with the default diagnostics.
10316 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10317                                   unsigned NumArgs,
10318                                   bool TakingCandidateAddress) {
10319   FunctionDecl *Fn = Cand->Function;
10320 
10321   // Note deleted candidates, but only if they're viable.
10322   if (Cand->Viable) {
10323     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10324       std::string FnDesc;
10325       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10326           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10327 
10328       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10329           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10330           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10331       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10332       return;
10333     }
10334 
10335     // We don't really have anything else to say about viable candidates.
10336     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10337     return;
10338   }
10339 
10340   switch (Cand->FailureKind) {
10341   case ovl_fail_too_many_arguments:
10342   case ovl_fail_too_few_arguments:
10343     return DiagnoseArityMismatch(S, Cand, NumArgs);
10344 
10345   case ovl_fail_bad_deduction:
10346     return DiagnoseBadDeduction(S, Cand, NumArgs,
10347                                 TakingCandidateAddress);
10348 
10349   case ovl_fail_illegal_constructor: {
10350     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10351       << (Fn->getPrimaryTemplate() ? 1 : 0);
10352     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10353     return;
10354   }
10355 
10356   case ovl_fail_trivial_conversion:
10357   case ovl_fail_bad_final_conversion:
10358   case ovl_fail_final_conversion_not_exact:
10359     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10360 
10361   case ovl_fail_bad_conversion: {
10362     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10363     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10364       if (Cand->Conversions[I].isBad())
10365         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10366 
10367     // FIXME: this currently happens when we're called from SemaInit
10368     // when user-conversion overload fails.  Figure out how to handle
10369     // those conditions and diagnose them well.
10370     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10371   }
10372 
10373   case ovl_fail_bad_target:
10374     return DiagnoseBadTarget(S, Cand);
10375 
10376   case ovl_fail_enable_if:
10377     return DiagnoseFailedEnableIfAttr(S, Cand);
10378 
10379   case ovl_fail_ext_disabled:
10380     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10381 
10382   case ovl_fail_inhctor_slice:
10383     // It's generally not interesting to note copy/move constructors here.
10384     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10385       return;
10386     S.Diag(Fn->getLocation(),
10387            diag::note_ovl_candidate_inherited_constructor_slice)
10388       << (Fn->getPrimaryTemplate() ? 1 : 0)
10389       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10390     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10391     return;
10392 
10393   case ovl_fail_addr_not_available: {
10394     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10395     (void)Available;
10396     assert(!Available);
10397     break;
10398   }
10399   case ovl_non_default_multiversion_function:
10400     // Do nothing, these should simply be ignored.
10401     break;
10402   }
10403 }
10404 
10405 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10406   // Desugar the type of the surrogate down to a function type,
10407   // retaining as many typedefs as possible while still showing
10408   // the function type (and, therefore, its parameter types).
10409   QualType FnType = Cand->Surrogate->getConversionType();
10410   bool isLValueReference = false;
10411   bool isRValueReference = false;
10412   bool isPointer = false;
10413   if (const LValueReferenceType *FnTypeRef =
10414         FnType->getAs<LValueReferenceType>()) {
10415     FnType = FnTypeRef->getPointeeType();
10416     isLValueReference = true;
10417   } else if (const RValueReferenceType *FnTypeRef =
10418                FnType->getAs<RValueReferenceType>()) {
10419     FnType = FnTypeRef->getPointeeType();
10420     isRValueReference = true;
10421   }
10422   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10423     FnType = FnTypePtr->getPointeeType();
10424     isPointer = true;
10425   }
10426   // Desugar down to a function type.
10427   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10428   // Reconstruct the pointer/reference as appropriate.
10429   if (isPointer) FnType = S.Context.getPointerType(FnType);
10430   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10431   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10432 
10433   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10434     << FnType;
10435 }
10436 
10437 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10438                                          SourceLocation OpLoc,
10439                                          OverloadCandidate *Cand) {
10440   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10441   std::string TypeStr("operator");
10442   TypeStr += Opc;
10443   TypeStr += "(";
10444   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10445   if (Cand->Conversions.size() == 1) {
10446     TypeStr += ")";
10447     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10448   } else {
10449     TypeStr += ", ";
10450     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10451     TypeStr += ")";
10452     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10453   }
10454 }
10455 
10456 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10457                                          OverloadCandidate *Cand) {
10458   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10459     if (ICS.isBad()) break; // all meaningless after first invalid
10460     if (!ICS.isAmbiguous()) continue;
10461 
10462     ICS.DiagnoseAmbiguousConversion(
10463         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10464   }
10465 }
10466 
10467 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10468   if (Cand->Function)
10469     return Cand->Function->getLocation();
10470   if (Cand->IsSurrogate)
10471     return Cand->Surrogate->getLocation();
10472   return SourceLocation();
10473 }
10474 
10475 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10476   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10477   case Sema::TDK_Success:
10478   case Sema::TDK_NonDependentConversionFailure:
10479     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10480 
10481   case Sema::TDK_Invalid:
10482   case Sema::TDK_Incomplete:
10483   case Sema::TDK_IncompletePack:
10484     return 1;
10485 
10486   case Sema::TDK_Underqualified:
10487   case Sema::TDK_Inconsistent:
10488     return 2;
10489 
10490   case Sema::TDK_SubstitutionFailure:
10491   case Sema::TDK_DeducedMismatch:
10492   case Sema::TDK_DeducedMismatchNested:
10493   case Sema::TDK_NonDeducedMismatch:
10494   case Sema::TDK_MiscellaneousDeductionFailure:
10495   case Sema::TDK_CUDATargetMismatch:
10496     return 3;
10497 
10498   case Sema::TDK_InstantiationDepth:
10499     return 4;
10500 
10501   case Sema::TDK_InvalidExplicitArguments:
10502     return 5;
10503 
10504   case Sema::TDK_TooManyArguments:
10505   case Sema::TDK_TooFewArguments:
10506     return 6;
10507   }
10508   llvm_unreachable("Unhandled deduction result");
10509 }
10510 
10511 namespace {
10512 struct CompareOverloadCandidatesForDisplay {
10513   Sema &S;
10514   SourceLocation Loc;
10515   size_t NumArgs;
10516   OverloadCandidateSet::CandidateSetKind CSK;
10517 
10518   CompareOverloadCandidatesForDisplay(
10519       Sema &S, SourceLocation Loc, size_t NArgs,
10520       OverloadCandidateSet::CandidateSetKind CSK)
10521       : S(S), NumArgs(NArgs), CSK(CSK) {}
10522 
10523   bool operator()(const OverloadCandidate *L,
10524                   const OverloadCandidate *R) {
10525     // Fast-path this check.
10526     if (L == R) return false;
10527 
10528     // Order first by viability.
10529     if (L->Viable) {
10530       if (!R->Viable) return true;
10531 
10532       // TODO: introduce a tri-valued comparison for overload
10533       // candidates.  Would be more worthwhile if we had a sort
10534       // that could exploit it.
10535       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10536         return true;
10537       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10538         return false;
10539     } else if (R->Viable)
10540       return false;
10541 
10542     assert(L->Viable == R->Viable);
10543 
10544     // Criteria by which we can sort non-viable candidates:
10545     if (!L->Viable) {
10546       // 1. Arity mismatches come after other candidates.
10547       if (L->FailureKind == ovl_fail_too_many_arguments ||
10548           L->FailureKind == ovl_fail_too_few_arguments) {
10549         if (R->FailureKind == ovl_fail_too_many_arguments ||
10550             R->FailureKind == ovl_fail_too_few_arguments) {
10551           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10552           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10553           if (LDist == RDist) {
10554             if (L->FailureKind == R->FailureKind)
10555               // Sort non-surrogates before surrogates.
10556               return !L->IsSurrogate && R->IsSurrogate;
10557             // Sort candidates requiring fewer parameters than there were
10558             // arguments given after candidates requiring more parameters
10559             // than there were arguments given.
10560             return L->FailureKind == ovl_fail_too_many_arguments;
10561           }
10562           return LDist < RDist;
10563         }
10564         return false;
10565       }
10566       if (R->FailureKind == ovl_fail_too_many_arguments ||
10567           R->FailureKind == ovl_fail_too_few_arguments)
10568         return true;
10569 
10570       // 2. Bad conversions come first and are ordered by the number
10571       // of bad conversions and quality of good conversions.
10572       if (L->FailureKind == ovl_fail_bad_conversion) {
10573         if (R->FailureKind != ovl_fail_bad_conversion)
10574           return true;
10575 
10576         // The conversion that can be fixed with a smaller number of changes,
10577         // comes first.
10578         unsigned numLFixes = L->Fix.NumConversionsFixed;
10579         unsigned numRFixes = R->Fix.NumConversionsFixed;
10580         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10581         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10582         if (numLFixes != numRFixes) {
10583           return numLFixes < numRFixes;
10584         }
10585 
10586         // If there's any ordering between the defined conversions...
10587         // FIXME: this might not be transitive.
10588         assert(L->Conversions.size() == R->Conversions.size());
10589 
10590         int leftBetter = 0;
10591         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10592         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10593           switch (CompareImplicitConversionSequences(S, Loc,
10594                                                      L->Conversions[I],
10595                                                      R->Conversions[I])) {
10596           case ImplicitConversionSequence::Better:
10597             leftBetter++;
10598             break;
10599 
10600           case ImplicitConversionSequence::Worse:
10601             leftBetter--;
10602             break;
10603 
10604           case ImplicitConversionSequence::Indistinguishable:
10605             break;
10606           }
10607         }
10608         if (leftBetter > 0) return true;
10609         if (leftBetter < 0) return false;
10610 
10611       } else if (R->FailureKind == ovl_fail_bad_conversion)
10612         return false;
10613 
10614       if (L->FailureKind == ovl_fail_bad_deduction) {
10615         if (R->FailureKind != ovl_fail_bad_deduction)
10616           return true;
10617 
10618         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10619           return RankDeductionFailure(L->DeductionFailure)
10620                < RankDeductionFailure(R->DeductionFailure);
10621       } else if (R->FailureKind == ovl_fail_bad_deduction)
10622         return false;
10623 
10624       // TODO: others?
10625     }
10626 
10627     // Sort everything else by location.
10628     SourceLocation LLoc = GetLocationForCandidate(L);
10629     SourceLocation RLoc = GetLocationForCandidate(R);
10630 
10631     // Put candidates without locations (e.g. builtins) at the end.
10632     if (LLoc.isInvalid()) return false;
10633     if (RLoc.isInvalid()) return true;
10634 
10635     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10636   }
10637 };
10638 }
10639 
10640 /// CompleteNonViableCandidate - Normally, overload resolution only
10641 /// computes up to the first bad conversion. Produces the FixIt set if
10642 /// possible.
10643 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10644                                        ArrayRef<Expr *> Args) {
10645   assert(!Cand->Viable);
10646 
10647   // Don't do anything on failures other than bad conversion.
10648   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10649 
10650   // We only want the FixIts if all the arguments can be corrected.
10651   bool Unfixable = false;
10652   // Use a implicit copy initialization to check conversion fixes.
10653   Cand->Fix.setConversionChecker(TryCopyInitialization);
10654 
10655   // Attempt to fix the bad conversion.
10656   unsigned ConvCount = Cand->Conversions.size();
10657   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10658        ++ConvIdx) {
10659     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10660     if (Cand->Conversions[ConvIdx].isInitialized() &&
10661         Cand->Conversions[ConvIdx].isBad()) {
10662       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10663       break;
10664     }
10665   }
10666 
10667   // FIXME: this should probably be preserved from the overload
10668   // operation somehow.
10669   bool SuppressUserConversions = false;
10670 
10671   unsigned ConvIdx = 0;
10672   ArrayRef<QualType> ParamTypes;
10673 
10674   if (Cand->IsSurrogate) {
10675     QualType ConvType
10676       = Cand->Surrogate->getConversionType().getNonReferenceType();
10677     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10678       ConvType = ConvPtrType->getPointeeType();
10679     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10680     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10681     ConvIdx = 1;
10682   } else if (Cand->Function) {
10683     ParamTypes =
10684         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10685     if (isa<CXXMethodDecl>(Cand->Function) &&
10686         !isa<CXXConstructorDecl>(Cand->Function)) {
10687       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10688       ConvIdx = 1;
10689     }
10690   } else {
10691     // Builtin operator.
10692     assert(ConvCount <= 3);
10693     ParamTypes = Cand->BuiltinParamTypes;
10694   }
10695 
10696   // Fill in the rest of the conversions.
10697   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10698     if (Cand->Conversions[ConvIdx].isInitialized()) {
10699       // We've already checked this conversion.
10700     } else if (ArgIdx < ParamTypes.size()) {
10701       if (ParamTypes[ArgIdx]->isDependentType())
10702         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10703             Args[ArgIdx]->getType());
10704       else {
10705         Cand->Conversions[ConvIdx] =
10706             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10707                                   SuppressUserConversions,
10708                                   /*InOverloadResolution=*/true,
10709                                   /*AllowObjCWritebackConversion=*/
10710                                   S.getLangOpts().ObjCAutoRefCount);
10711         // Store the FixIt in the candidate if it exists.
10712         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10713           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10714       }
10715     } else
10716       Cand->Conversions[ConvIdx].setEllipsis();
10717   }
10718 }
10719 
10720 /// When overload resolution fails, prints diagnostic messages containing the
10721 /// candidates in the candidate set.
10722 void OverloadCandidateSet::NoteCandidates(
10723     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10724     StringRef Opc, SourceLocation OpLoc,
10725     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10726   // Sort the candidates by viability and position.  Sorting directly would
10727   // be prohibitive, so we make a set of pointers and sort those.
10728   SmallVector<OverloadCandidate*, 32> Cands;
10729   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10730   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10731     if (!Filter(*Cand))
10732       continue;
10733     if (Cand->Viable)
10734       Cands.push_back(Cand);
10735     else if (OCD == OCD_AllCandidates) {
10736       CompleteNonViableCandidate(S, Cand, Args);
10737       if (Cand->Function || Cand->IsSurrogate)
10738         Cands.push_back(Cand);
10739       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10740       // want to list every possible builtin candidate.
10741     }
10742   }
10743 
10744   std::stable_sort(Cands.begin(), Cands.end(),
10745             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10746 
10747   bool ReportedAmbiguousConversions = false;
10748 
10749   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10750   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10751   unsigned CandsShown = 0;
10752   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10753     OverloadCandidate *Cand = *I;
10754 
10755     // Set an arbitrary limit on the number of candidate functions we'll spam
10756     // the user with.  FIXME: This limit should depend on details of the
10757     // candidate list.
10758     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10759       break;
10760     }
10761     ++CandsShown;
10762 
10763     if (Cand->Function)
10764       NoteFunctionCandidate(S, Cand, Args.size(),
10765                             /*TakingCandidateAddress=*/false);
10766     else if (Cand->IsSurrogate)
10767       NoteSurrogateCandidate(S, Cand);
10768     else {
10769       assert(Cand->Viable &&
10770              "Non-viable built-in candidates are not added to Cands.");
10771       // Generally we only see ambiguities including viable builtin
10772       // operators if overload resolution got screwed up by an
10773       // ambiguous user-defined conversion.
10774       //
10775       // FIXME: It's quite possible for different conversions to see
10776       // different ambiguities, though.
10777       if (!ReportedAmbiguousConversions) {
10778         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10779         ReportedAmbiguousConversions = true;
10780       }
10781 
10782       // If this is a viable builtin, print it.
10783       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10784     }
10785   }
10786 
10787   if (I != E)
10788     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10789 }
10790 
10791 static SourceLocation
10792 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10793   return Cand->Specialization ? Cand->Specialization->getLocation()
10794                               : SourceLocation();
10795 }
10796 
10797 namespace {
10798 struct CompareTemplateSpecCandidatesForDisplay {
10799   Sema &S;
10800   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10801 
10802   bool operator()(const TemplateSpecCandidate *L,
10803                   const TemplateSpecCandidate *R) {
10804     // Fast-path this check.
10805     if (L == R)
10806       return false;
10807 
10808     // Assuming that both candidates are not matches...
10809 
10810     // Sort by the ranking of deduction failures.
10811     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10812       return RankDeductionFailure(L->DeductionFailure) <
10813              RankDeductionFailure(R->DeductionFailure);
10814 
10815     // Sort everything else by location.
10816     SourceLocation LLoc = GetLocationForCandidate(L);
10817     SourceLocation RLoc = GetLocationForCandidate(R);
10818 
10819     // Put candidates without locations (e.g. builtins) at the end.
10820     if (LLoc.isInvalid())
10821       return false;
10822     if (RLoc.isInvalid())
10823       return true;
10824 
10825     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10826   }
10827 };
10828 }
10829 
10830 /// Diagnose a template argument deduction failure.
10831 /// We are treating these failures as overload failures due to bad
10832 /// deductions.
10833 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10834                                                  bool ForTakingAddress) {
10835   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10836                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10837 }
10838 
10839 void TemplateSpecCandidateSet::destroyCandidates() {
10840   for (iterator i = begin(), e = end(); i != e; ++i) {
10841     i->DeductionFailure.Destroy();
10842   }
10843 }
10844 
10845 void TemplateSpecCandidateSet::clear() {
10846   destroyCandidates();
10847   Candidates.clear();
10848 }
10849 
10850 /// NoteCandidates - When no template specialization match is found, prints
10851 /// diagnostic messages containing the non-matching specializations that form
10852 /// the candidate set.
10853 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10854 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10855 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10856   // Sort the candidates by position (assuming no candidate is a match).
10857   // Sorting directly would be prohibitive, so we make a set of pointers
10858   // and sort those.
10859   SmallVector<TemplateSpecCandidate *, 32> Cands;
10860   Cands.reserve(size());
10861   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10862     if (Cand->Specialization)
10863       Cands.push_back(Cand);
10864     // Otherwise, this is a non-matching builtin candidate.  We do not,
10865     // in general, want to list every possible builtin candidate.
10866   }
10867 
10868   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
10869 
10870   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10871   // for generalization purposes (?).
10872   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10873 
10874   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10875   unsigned CandsShown = 0;
10876   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10877     TemplateSpecCandidate *Cand = *I;
10878 
10879     // Set an arbitrary limit on the number of candidates we'll spam
10880     // the user with.  FIXME: This limit should depend on details of the
10881     // candidate list.
10882     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10883       break;
10884     ++CandsShown;
10885 
10886     assert(Cand->Specialization &&
10887            "Non-matching built-in candidates are not added to Cands.");
10888     Cand->NoteDeductionFailure(S, ForTakingAddress);
10889   }
10890 
10891   if (I != E)
10892     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10893 }
10894 
10895 // [PossiblyAFunctionType]  -->   [Return]
10896 // NonFunctionType --> NonFunctionType
10897 // R (A) --> R(A)
10898 // R (*)(A) --> R (A)
10899 // R (&)(A) --> R (A)
10900 // R (S::*)(A) --> R (A)
10901 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10902   QualType Ret = PossiblyAFunctionType;
10903   if (const PointerType *ToTypePtr =
10904     PossiblyAFunctionType->getAs<PointerType>())
10905     Ret = ToTypePtr->getPointeeType();
10906   else if (const ReferenceType *ToTypeRef =
10907     PossiblyAFunctionType->getAs<ReferenceType>())
10908     Ret = ToTypeRef->getPointeeType();
10909   else if (const MemberPointerType *MemTypePtr =
10910     PossiblyAFunctionType->getAs<MemberPointerType>())
10911     Ret = MemTypePtr->getPointeeType();
10912   Ret =
10913     Context.getCanonicalType(Ret).getUnqualifiedType();
10914   return Ret;
10915 }
10916 
10917 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10918                                  bool Complain = true) {
10919   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10920       S.DeduceReturnType(FD, Loc, Complain))
10921     return true;
10922 
10923   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10924   if (S.getLangOpts().CPlusPlus17 &&
10925       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10926       !S.ResolveExceptionSpec(Loc, FPT))
10927     return true;
10928 
10929   return false;
10930 }
10931 
10932 namespace {
10933 // A helper class to help with address of function resolution
10934 // - allows us to avoid passing around all those ugly parameters
10935 class AddressOfFunctionResolver {
10936   Sema& S;
10937   Expr* SourceExpr;
10938   const QualType& TargetType;
10939   QualType TargetFunctionType; // Extracted function type from target type
10940 
10941   bool Complain;
10942   //DeclAccessPair& ResultFunctionAccessPair;
10943   ASTContext& Context;
10944 
10945   bool TargetTypeIsNonStaticMemberFunction;
10946   bool FoundNonTemplateFunction;
10947   bool StaticMemberFunctionFromBoundPointer;
10948   bool HasComplained;
10949 
10950   OverloadExpr::FindResult OvlExprInfo;
10951   OverloadExpr *OvlExpr;
10952   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10953   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10954   TemplateSpecCandidateSet FailedCandidates;
10955 
10956 public:
10957   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10958                             const QualType &TargetType, bool Complain)
10959       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10960         Complain(Complain), Context(S.getASTContext()),
10961         TargetTypeIsNonStaticMemberFunction(
10962             !!TargetType->getAs<MemberPointerType>()),
10963         FoundNonTemplateFunction(false),
10964         StaticMemberFunctionFromBoundPointer(false),
10965         HasComplained(false),
10966         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10967         OvlExpr(OvlExprInfo.Expression),
10968         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10969     ExtractUnqualifiedFunctionTypeFromTargetType();
10970 
10971     if (TargetFunctionType->isFunctionType()) {
10972       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10973         if (!UME->isImplicitAccess() &&
10974             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10975           StaticMemberFunctionFromBoundPointer = true;
10976     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10977       DeclAccessPair dap;
10978       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10979               OvlExpr, false, &dap)) {
10980         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10981           if (!Method->isStatic()) {
10982             // If the target type is a non-function type and the function found
10983             // is a non-static member function, pretend as if that was the
10984             // target, it's the only possible type to end up with.
10985             TargetTypeIsNonStaticMemberFunction = true;
10986 
10987             // And skip adding the function if its not in the proper form.
10988             // We'll diagnose this due to an empty set of functions.
10989             if (!OvlExprInfo.HasFormOfMemberPointer)
10990               return;
10991           }
10992 
10993         Matches.push_back(std::make_pair(dap, Fn));
10994       }
10995       return;
10996     }
10997 
10998     if (OvlExpr->hasExplicitTemplateArgs())
10999       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11000 
11001     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11002       // C++ [over.over]p4:
11003       //   If more than one function is selected, [...]
11004       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11005         if (FoundNonTemplateFunction)
11006           EliminateAllTemplateMatches();
11007         else
11008           EliminateAllExceptMostSpecializedTemplate();
11009       }
11010     }
11011 
11012     if (S.getLangOpts().CUDA && Matches.size() > 1)
11013       EliminateSuboptimalCudaMatches();
11014   }
11015 
11016   bool hasComplained() const { return HasComplained; }
11017 
11018 private:
11019   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11020     QualType Discard;
11021     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11022            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11023   }
11024 
11025   /// \return true if A is considered a better overload candidate for the
11026   /// desired type than B.
11027   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11028     // If A doesn't have exactly the correct type, we don't want to classify it
11029     // as "better" than anything else. This way, the user is required to
11030     // disambiguate for us if there are multiple candidates and no exact match.
11031     return candidateHasExactlyCorrectType(A) &&
11032            (!candidateHasExactlyCorrectType(B) ||
11033             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11034   }
11035 
11036   /// \return true if we were able to eliminate all but one overload candidate,
11037   /// false otherwise.
11038   bool eliminiateSuboptimalOverloadCandidates() {
11039     // Same algorithm as overload resolution -- one pass to pick the "best",
11040     // another pass to be sure that nothing is better than the best.
11041     auto Best = Matches.begin();
11042     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11043       if (isBetterCandidate(I->second, Best->second))
11044         Best = I;
11045 
11046     const FunctionDecl *BestFn = Best->second;
11047     auto IsBestOrInferiorToBest = [this, BestFn](
11048         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11049       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11050     };
11051 
11052     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11053     // option, so we can potentially give the user a better error
11054     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11055       return false;
11056     Matches[0] = *Best;
11057     Matches.resize(1);
11058     return true;
11059   }
11060 
11061   bool isTargetTypeAFunction() const {
11062     return TargetFunctionType->isFunctionType();
11063   }
11064 
11065   // [ToType]     [Return]
11066 
11067   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11068   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11069   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11070   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11071     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11072   }
11073 
11074   // return true if any matching specializations were found
11075   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11076                                    const DeclAccessPair& CurAccessFunPair) {
11077     if (CXXMethodDecl *Method
11078               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11079       // Skip non-static function templates when converting to pointer, and
11080       // static when converting to member pointer.
11081       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11082         return false;
11083     }
11084     else if (TargetTypeIsNonStaticMemberFunction)
11085       return false;
11086 
11087     // C++ [over.over]p2:
11088     //   If the name is a function template, template argument deduction is
11089     //   done (14.8.2.2), and if the argument deduction succeeds, the
11090     //   resulting template argument list is used to generate a single
11091     //   function template specialization, which is added to the set of
11092     //   overloaded functions considered.
11093     FunctionDecl *Specialization = nullptr;
11094     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11095     if (Sema::TemplateDeductionResult Result
11096           = S.DeduceTemplateArguments(FunctionTemplate,
11097                                       &OvlExplicitTemplateArgs,
11098                                       TargetFunctionType, Specialization,
11099                                       Info, /*IsAddressOfFunction*/true)) {
11100       // Make a note of the failed deduction for diagnostics.
11101       FailedCandidates.addCandidate()
11102           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11103                MakeDeductionFailureInfo(Context, Result, Info));
11104       return false;
11105     }
11106 
11107     // Template argument deduction ensures that we have an exact match or
11108     // compatible pointer-to-function arguments that would be adjusted by ICS.
11109     // This function template specicalization works.
11110     assert(S.isSameOrCompatibleFunctionType(
11111               Context.getCanonicalType(Specialization->getType()),
11112               Context.getCanonicalType(TargetFunctionType)));
11113 
11114     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11115       return false;
11116 
11117     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11118     return true;
11119   }
11120 
11121   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11122                                       const DeclAccessPair& CurAccessFunPair) {
11123     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11124       // Skip non-static functions when converting to pointer, and static
11125       // when converting to member pointer.
11126       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11127         return false;
11128     }
11129     else if (TargetTypeIsNonStaticMemberFunction)
11130       return false;
11131 
11132     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11133       if (S.getLangOpts().CUDA)
11134         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11135           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11136             return false;
11137       if (FunDecl->isMultiVersion()) {
11138         const auto *TA = FunDecl->getAttr<TargetAttr>();
11139         if (TA && !TA->isDefaultVersion())
11140           return false;
11141       }
11142 
11143       // If any candidate has a placeholder return type, trigger its deduction
11144       // now.
11145       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11146                                Complain)) {
11147         HasComplained |= Complain;
11148         return false;
11149       }
11150 
11151       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11152         return false;
11153 
11154       // If we're in C, we need to support types that aren't exactly identical.
11155       if (!S.getLangOpts().CPlusPlus ||
11156           candidateHasExactlyCorrectType(FunDecl)) {
11157         Matches.push_back(std::make_pair(
11158             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11159         FoundNonTemplateFunction = true;
11160         return true;
11161       }
11162     }
11163 
11164     return false;
11165   }
11166 
11167   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11168     bool Ret = false;
11169 
11170     // If the overload expression doesn't have the form of a pointer to
11171     // member, don't try to convert it to a pointer-to-member type.
11172     if (IsInvalidFormOfPointerToMemberFunction())
11173       return false;
11174 
11175     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11176                                E = OvlExpr->decls_end();
11177          I != E; ++I) {
11178       // Look through any using declarations to find the underlying function.
11179       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11180 
11181       // C++ [over.over]p3:
11182       //   Non-member functions and static member functions match
11183       //   targets of type "pointer-to-function" or "reference-to-function."
11184       //   Nonstatic member functions match targets of
11185       //   type "pointer-to-member-function."
11186       // Note that according to DR 247, the containing class does not matter.
11187       if (FunctionTemplateDecl *FunctionTemplate
11188                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11189         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11190           Ret = true;
11191       }
11192       // If we have explicit template arguments supplied, skip non-templates.
11193       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11194                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11195         Ret = true;
11196     }
11197     assert(Ret || Matches.empty());
11198     return Ret;
11199   }
11200 
11201   void EliminateAllExceptMostSpecializedTemplate() {
11202     //   [...] and any given function template specialization F1 is
11203     //   eliminated if the set contains a second function template
11204     //   specialization whose function template is more specialized
11205     //   than the function template of F1 according to the partial
11206     //   ordering rules of 14.5.5.2.
11207 
11208     // The algorithm specified above is quadratic. We instead use a
11209     // two-pass algorithm (similar to the one used to identify the
11210     // best viable function in an overload set) that identifies the
11211     // best function template (if it exists).
11212 
11213     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11214     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11215       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11216 
11217     // TODO: It looks like FailedCandidates does not serve much purpose
11218     // here, since the no_viable diagnostic has index 0.
11219     UnresolvedSetIterator Result = S.getMostSpecialized(
11220         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11221         SourceExpr->getBeginLoc(), S.PDiag(),
11222         S.PDiag(diag::err_addr_ovl_ambiguous)
11223             << Matches[0].second->getDeclName(),
11224         S.PDiag(diag::note_ovl_candidate)
11225             << (unsigned)oc_function << (unsigned)ocs_described_template,
11226         Complain, TargetFunctionType);
11227 
11228     if (Result != MatchesCopy.end()) {
11229       // Make it the first and only element
11230       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11231       Matches[0].second = cast<FunctionDecl>(*Result);
11232       Matches.resize(1);
11233     } else
11234       HasComplained |= Complain;
11235   }
11236 
11237   void EliminateAllTemplateMatches() {
11238     //   [...] any function template specializations in the set are
11239     //   eliminated if the set also contains a non-template function, [...]
11240     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11241       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11242         ++I;
11243       else {
11244         Matches[I] = Matches[--N];
11245         Matches.resize(N);
11246       }
11247     }
11248   }
11249 
11250   void EliminateSuboptimalCudaMatches() {
11251     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11252   }
11253 
11254 public:
11255   void ComplainNoMatchesFound() const {
11256     assert(Matches.empty());
11257     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11258         << OvlExpr->getName() << TargetFunctionType
11259         << OvlExpr->getSourceRange();
11260     if (FailedCandidates.empty())
11261       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11262                                   /*TakingAddress=*/true);
11263     else {
11264       // We have some deduction failure messages. Use them to diagnose
11265       // the function templates, and diagnose the non-template candidates
11266       // normally.
11267       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11268                                  IEnd = OvlExpr->decls_end();
11269            I != IEnd; ++I)
11270         if (FunctionDecl *Fun =
11271                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11272           if (!functionHasPassObjectSizeParams(Fun))
11273             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11274                                     /*TakingAddress=*/true);
11275       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11276     }
11277   }
11278 
11279   bool IsInvalidFormOfPointerToMemberFunction() const {
11280     return TargetTypeIsNonStaticMemberFunction &&
11281       !OvlExprInfo.HasFormOfMemberPointer;
11282   }
11283 
11284   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11285       // TODO: Should we condition this on whether any functions might
11286       // have matched, or is it more appropriate to do that in callers?
11287       // TODO: a fixit wouldn't hurt.
11288       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11289         << TargetType << OvlExpr->getSourceRange();
11290   }
11291 
11292   bool IsStaticMemberFunctionFromBoundPointer() const {
11293     return StaticMemberFunctionFromBoundPointer;
11294   }
11295 
11296   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11297     S.Diag(OvlExpr->getBeginLoc(),
11298            diag::err_invalid_form_pointer_member_function)
11299         << OvlExpr->getSourceRange();
11300   }
11301 
11302   void ComplainOfInvalidConversion() const {
11303     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11304         << OvlExpr->getName() << TargetType;
11305   }
11306 
11307   void ComplainMultipleMatchesFound() const {
11308     assert(Matches.size() > 1);
11309     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11310         << OvlExpr->getName() << OvlExpr->getSourceRange();
11311     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11312                                 /*TakingAddress=*/true);
11313   }
11314 
11315   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11316 
11317   int getNumMatches() const { return Matches.size(); }
11318 
11319   FunctionDecl* getMatchingFunctionDecl() const {
11320     if (Matches.size() != 1) return nullptr;
11321     return Matches[0].second;
11322   }
11323 
11324   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11325     if (Matches.size() != 1) return nullptr;
11326     return &Matches[0].first;
11327   }
11328 };
11329 }
11330 
11331 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11332 /// an overloaded function (C++ [over.over]), where @p From is an
11333 /// expression with overloaded function type and @p ToType is the type
11334 /// we're trying to resolve to. For example:
11335 ///
11336 /// @code
11337 /// int f(double);
11338 /// int f(int);
11339 ///
11340 /// int (*pfd)(double) = f; // selects f(double)
11341 /// @endcode
11342 ///
11343 /// This routine returns the resulting FunctionDecl if it could be
11344 /// resolved, and NULL otherwise. When @p Complain is true, this
11345 /// routine will emit diagnostics if there is an error.
11346 FunctionDecl *
11347 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11348                                          QualType TargetType,
11349                                          bool Complain,
11350                                          DeclAccessPair &FoundResult,
11351                                          bool *pHadMultipleCandidates) {
11352   assert(AddressOfExpr->getType() == Context.OverloadTy);
11353 
11354   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11355                                      Complain);
11356   int NumMatches = Resolver.getNumMatches();
11357   FunctionDecl *Fn = nullptr;
11358   bool ShouldComplain = Complain && !Resolver.hasComplained();
11359   if (NumMatches == 0 && ShouldComplain) {
11360     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11361       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11362     else
11363       Resolver.ComplainNoMatchesFound();
11364   }
11365   else if (NumMatches > 1 && ShouldComplain)
11366     Resolver.ComplainMultipleMatchesFound();
11367   else if (NumMatches == 1) {
11368     Fn = Resolver.getMatchingFunctionDecl();
11369     assert(Fn);
11370     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11371       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11372     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11373     if (Complain) {
11374       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11375         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11376       else
11377         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11378     }
11379   }
11380 
11381   if (pHadMultipleCandidates)
11382     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11383   return Fn;
11384 }
11385 
11386 /// Given an expression that refers to an overloaded function, try to
11387 /// resolve that function to a single function that can have its address taken.
11388 /// This will modify `Pair` iff it returns non-null.
11389 ///
11390 /// This routine can only realistically succeed if all but one candidates in the
11391 /// overload set for SrcExpr cannot have their addresses taken.
11392 FunctionDecl *
11393 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11394                                                   DeclAccessPair &Pair) {
11395   OverloadExpr::FindResult R = OverloadExpr::find(E);
11396   OverloadExpr *Ovl = R.Expression;
11397   FunctionDecl *Result = nullptr;
11398   DeclAccessPair DAP;
11399   // Don't use the AddressOfResolver because we're specifically looking for
11400   // cases where we have one overload candidate that lacks
11401   // enable_if/pass_object_size/...
11402   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11403     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11404     if (!FD)
11405       return nullptr;
11406 
11407     if (!checkAddressOfFunctionIsAvailable(FD))
11408       continue;
11409 
11410     // We have more than one result; quit.
11411     if (Result)
11412       return nullptr;
11413     DAP = I.getPair();
11414     Result = FD;
11415   }
11416 
11417   if (Result)
11418     Pair = DAP;
11419   return Result;
11420 }
11421 
11422 /// Given an overloaded function, tries to turn it into a non-overloaded
11423 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11424 /// will perform access checks, diagnose the use of the resultant decl, and, if
11425 /// requested, potentially perform a function-to-pointer decay.
11426 ///
11427 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11428 /// Otherwise, returns true. This may emit diagnostics and return true.
11429 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11430     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11431   Expr *E = SrcExpr.get();
11432   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11433 
11434   DeclAccessPair DAP;
11435   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11436   if (!Found || Found->isCPUDispatchMultiVersion() ||
11437       Found->isCPUSpecificMultiVersion())
11438     return false;
11439 
11440   // Emitting multiple diagnostics for a function that is both inaccessible and
11441   // unavailable is consistent with our behavior elsewhere. So, always check
11442   // for both.
11443   DiagnoseUseOfDecl(Found, E->getExprLoc());
11444   CheckAddressOfMemberAccess(E, DAP);
11445   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11446   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11447     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11448   else
11449     SrcExpr = Fixed;
11450   return true;
11451 }
11452 
11453 /// Given an expression that refers to an overloaded function, try to
11454 /// resolve that overloaded function expression down to a single function.
11455 ///
11456 /// This routine can only resolve template-ids that refer to a single function
11457 /// template, where that template-id refers to a single template whose template
11458 /// arguments are either provided by the template-id or have defaults,
11459 /// as described in C++0x [temp.arg.explicit]p3.
11460 ///
11461 /// If no template-ids are found, no diagnostics are emitted and NULL is
11462 /// returned.
11463 FunctionDecl *
11464 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11465                                                   bool Complain,
11466                                                   DeclAccessPair *FoundResult) {
11467   // C++ [over.over]p1:
11468   //   [...] [Note: any redundant set of parentheses surrounding the
11469   //   overloaded function name is ignored (5.1). ]
11470   // C++ [over.over]p1:
11471   //   [...] The overloaded function name can be preceded by the &
11472   //   operator.
11473 
11474   // If we didn't actually find any template-ids, we're done.
11475   if (!ovl->hasExplicitTemplateArgs())
11476     return nullptr;
11477 
11478   TemplateArgumentListInfo ExplicitTemplateArgs;
11479   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11480   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11481 
11482   // Look through all of the overloaded functions, searching for one
11483   // whose type matches exactly.
11484   FunctionDecl *Matched = nullptr;
11485   for (UnresolvedSetIterator I = ovl->decls_begin(),
11486          E = ovl->decls_end(); I != E; ++I) {
11487     // C++0x [temp.arg.explicit]p3:
11488     //   [...] In contexts where deduction is done and fails, or in contexts
11489     //   where deduction is not done, if a template argument list is
11490     //   specified and it, along with any default template arguments,
11491     //   identifies a single function template specialization, then the
11492     //   template-id is an lvalue for the function template specialization.
11493     FunctionTemplateDecl *FunctionTemplate
11494       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11495 
11496     // C++ [over.over]p2:
11497     //   If the name is a function template, template argument deduction is
11498     //   done (14.8.2.2), and if the argument deduction succeeds, the
11499     //   resulting template argument list is used to generate a single
11500     //   function template specialization, which is added to the set of
11501     //   overloaded functions considered.
11502     FunctionDecl *Specialization = nullptr;
11503     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11504     if (TemplateDeductionResult Result
11505           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11506                                     Specialization, Info,
11507                                     /*IsAddressOfFunction*/true)) {
11508       // Make a note of the failed deduction for diagnostics.
11509       // TODO: Actually use the failed-deduction info?
11510       FailedCandidates.addCandidate()
11511           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11512                MakeDeductionFailureInfo(Context, Result, Info));
11513       continue;
11514     }
11515 
11516     assert(Specialization && "no specialization and no error?");
11517 
11518     // Multiple matches; we can't resolve to a single declaration.
11519     if (Matched) {
11520       if (Complain) {
11521         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11522           << ovl->getName();
11523         NoteAllOverloadCandidates(ovl);
11524       }
11525       return nullptr;
11526     }
11527 
11528     Matched = Specialization;
11529     if (FoundResult) *FoundResult = I.getPair();
11530   }
11531 
11532   if (Matched &&
11533       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11534     return nullptr;
11535 
11536   return Matched;
11537 }
11538 
11539 // Resolve and fix an overloaded expression that can be resolved
11540 // because it identifies a single function template specialization.
11541 //
11542 // Last three arguments should only be supplied if Complain = true
11543 //
11544 // Return true if it was logically possible to so resolve the
11545 // expression, regardless of whether or not it succeeded.  Always
11546 // returns true if 'complain' is set.
11547 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11548                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11549                       bool complain, SourceRange OpRangeForComplaining,
11550                                            QualType DestTypeForComplaining,
11551                                             unsigned DiagIDForComplaining) {
11552   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11553 
11554   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11555 
11556   DeclAccessPair found;
11557   ExprResult SingleFunctionExpression;
11558   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11559                            ovl.Expression, /*complain*/ false, &found)) {
11560     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11561       SrcExpr = ExprError();
11562       return true;
11563     }
11564 
11565     // It is only correct to resolve to an instance method if we're
11566     // resolving a form that's permitted to be a pointer to member.
11567     // Otherwise we'll end up making a bound member expression, which
11568     // is illegal in all the contexts we resolve like this.
11569     if (!ovl.HasFormOfMemberPointer &&
11570         isa<CXXMethodDecl>(fn) &&
11571         cast<CXXMethodDecl>(fn)->isInstance()) {
11572       if (!complain) return false;
11573 
11574       Diag(ovl.Expression->getExprLoc(),
11575            diag::err_bound_member_function)
11576         << 0 << ovl.Expression->getSourceRange();
11577 
11578       // TODO: I believe we only end up here if there's a mix of
11579       // static and non-static candidates (otherwise the expression
11580       // would have 'bound member' type, not 'overload' type).
11581       // Ideally we would note which candidate was chosen and why
11582       // the static candidates were rejected.
11583       SrcExpr = ExprError();
11584       return true;
11585     }
11586 
11587     // Fix the expression to refer to 'fn'.
11588     SingleFunctionExpression =
11589         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11590 
11591     // If desired, do function-to-pointer decay.
11592     if (doFunctionPointerConverion) {
11593       SingleFunctionExpression =
11594         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11595       if (SingleFunctionExpression.isInvalid()) {
11596         SrcExpr = ExprError();
11597         return true;
11598       }
11599     }
11600   }
11601 
11602   if (!SingleFunctionExpression.isUsable()) {
11603     if (complain) {
11604       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11605         << ovl.Expression->getName()
11606         << DestTypeForComplaining
11607         << OpRangeForComplaining
11608         << ovl.Expression->getQualifierLoc().getSourceRange();
11609       NoteAllOverloadCandidates(SrcExpr.get());
11610 
11611       SrcExpr = ExprError();
11612       return true;
11613     }
11614 
11615     return false;
11616   }
11617 
11618   SrcExpr = SingleFunctionExpression;
11619   return true;
11620 }
11621 
11622 /// Add a single candidate to the overload set.
11623 static void AddOverloadedCallCandidate(Sema &S,
11624                                        DeclAccessPair FoundDecl,
11625                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11626                                        ArrayRef<Expr *> Args,
11627                                        OverloadCandidateSet &CandidateSet,
11628                                        bool PartialOverloading,
11629                                        bool KnownValid) {
11630   NamedDecl *Callee = FoundDecl.getDecl();
11631   if (isa<UsingShadowDecl>(Callee))
11632     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11633 
11634   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11635     if (ExplicitTemplateArgs) {
11636       assert(!KnownValid && "Explicit template arguments?");
11637       return;
11638     }
11639     // Prevent ill-formed function decls to be added as overload candidates.
11640     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11641       return;
11642 
11643     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11644                            /*SuppressUsedConversions=*/false,
11645                            PartialOverloading);
11646     return;
11647   }
11648 
11649   if (FunctionTemplateDecl *FuncTemplate
11650       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11651     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11652                                    ExplicitTemplateArgs, Args, CandidateSet,
11653                                    /*SuppressUsedConversions=*/false,
11654                                    PartialOverloading);
11655     return;
11656   }
11657 
11658   assert(!KnownValid && "unhandled case in overloaded call candidate");
11659 }
11660 
11661 /// Add the overload candidates named by callee and/or found by argument
11662 /// dependent lookup to the given overload set.
11663 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11664                                        ArrayRef<Expr *> Args,
11665                                        OverloadCandidateSet &CandidateSet,
11666                                        bool PartialOverloading) {
11667 
11668 #ifndef NDEBUG
11669   // Verify that ArgumentDependentLookup is consistent with the rules
11670   // in C++0x [basic.lookup.argdep]p3:
11671   //
11672   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11673   //   and let Y be the lookup set produced by argument dependent
11674   //   lookup (defined as follows). If X contains
11675   //
11676   //     -- a declaration of a class member, or
11677   //
11678   //     -- a block-scope function declaration that is not a
11679   //        using-declaration, or
11680   //
11681   //     -- a declaration that is neither a function or a function
11682   //        template
11683   //
11684   //   then Y is empty.
11685 
11686   if (ULE->requiresADL()) {
11687     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11688            E = ULE->decls_end(); I != E; ++I) {
11689       assert(!(*I)->getDeclContext()->isRecord());
11690       assert(isa<UsingShadowDecl>(*I) ||
11691              !(*I)->getDeclContext()->isFunctionOrMethod());
11692       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11693     }
11694   }
11695 #endif
11696 
11697   // It would be nice to avoid this copy.
11698   TemplateArgumentListInfo TABuffer;
11699   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11700   if (ULE->hasExplicitTemplateArgs()) {
11701     ULE->copyTemplateArgumentsInto(TABuffer);
11702     ExplicitTemplateArgs = &TABuffer;
11703   }
11704 
11705   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11706          E = ULE->decls_end(); I != E; ++I)
11707     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11708                                CandidateSet, PartialOverloading,
11709                                /*KnownValid*/ true);
11710 
11711   if (ULE->requiresADL())
11712     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11713                                          Args, ExplicitTemplateArgs,
11714                                          CandidateSet, PartialOverloading);
11715 }
11716 
11717 /// Determine whether a declaration with the specified name could be moved into
11718 /// a different namespace.
11719 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11720   switch (Name.getCXXOverloadedOperator()) {
11721   case OO_New: case OO_Array_New:
11722   case OO_Delete: case OO_Array_Delete:
11723     return false;
11724 
11725   default:
11726     return true;
11727   }
11728 }
11729 
11730 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11731 /// template, where the non-dependent name was declared after the template
11732 /// was defined. This is common in code written for a compilers which do not
11733 /// correctly implement two-stage name lookup.
11734 ///
11735 /// Returns true if a viable candidate was found and a diagnostic was issued.
11736 static bool
11737 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11738                        const CXXScopeSpec &SS, LookupResult &R,
11739                        OverloadCandidateSet::CandidateSetKind CSK,
11740                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11741                        ArrayRef<Expr *> Args,
11742                        bool *DoDiagnoseEmptyLookup = nullptr) {
11743   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11744     return false;
11745 
11746   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11747     if (DC->isTransparentContext())
11748       continue;
11749 
11750     SemaRef.LookupQualifiedName(R, DC);
11751 
11752     if (!R.empty()) {
11753       R.suppressDiagnostics();
11754 
11755       if (isa<CXXRecordDecl>(DC)) {
11756         // Don't diagnose names we find in classes; we get much better
11757         // diagnostics for these from DiagnoseEmptyLookup.
11758         R.clear();
11759         if (DoDiagnoseEmptyLookup)
11760           *DoDiagnoseEmptyLookup = true;
11761         return false;
11762       }
11763 
11764       OverloadCandidateSet Candidates(FnLoc, CSK);
11765       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11766         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11767                                    ExplicitTemplateArgs, Args,
11768                                    Candidates, false, /*KnownValid*/ false);
11769 
11770       OverloadCandidateSet::iterator Best;
11771       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11772         // No viable functions. Don't bother the user with notes for functions
11773         // which don't work and shouldn't be found anyway.
11774         R.clear();
11775         return false;
11776       }
11777 
11778       // Find the namespaces where ADL would have looked, and suggest
11779       // declaring the function there instead.
11780       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11781       Sema::AssociatedClassSet AssociatedClasses;
11782       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11783                                                  AssociatedNamespaces,
11784                                                  AssociatedClasses);
11785       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11786       if (canBeDeclaredInNamespace(R.getLookupName())) {
11787         DeclContext *Std = SemaRef.getStdNamespace();
11788         for (Sema::AssociatedNamespaceSet::iterator
11789                it = AssociatedNamespaces.begin(),
11790                end = AssociatedNamespaces.end(); it != end; ++it) {
11791           // Never suggest declaring a function within namespace 'std'.
11792           if (Std && Std->Encloses(*it))
11793             continue;
11794 
11795           // Never suggest declaring a function within a namespace with a
11796           // reserved name, like __gnu_cxx.
11797           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11798           if (NS &&
11799               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11800             continue;
11801 
11802           SuggestedNamespaces.insert(*it);
11803         }
11804       }
11805 
11806       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11807         << R.getLookupName();
11808       if (SuggestedNamespaces.empty()) {
11809         SemaRef.Diag(Best->Function->getLocation(),
11810                      diag::note_not_found_by_two_phase_lookup)
11811           << R.getLookupName() << 0;
11812       } else if (SuggestedNamespaces.size() == 1) {
11813         SemaRef.Diag(Best->Function->getLocation(),
11814                      diag::note_not_found_by_two_phase_lookup)
11815           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11816       } else {
11817         // FIXME: It would be useful to list the associated namespaces here,
11818         // but the diagnostics infrastructure doesn't provide a way to produce
11819         // a localized representation of a list of items.
11820         SemaRef.Diag(Best->Function->getLocation(),
11821                      diag::note_not_found_by_two_phase_lookup)
11822           << R.getLookupName() << 2;
11823       }
11824 
11825       // Try to recover by calling this function.
11826       return true;
11827     }
11828 
11829     R.clear();
11830   }
11831 
11832   return false;
11833 }
11834 
11835 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11836 /// template, where the non-dependent operator was declared after the template
11837 /// was defined.
11838 ///
11839 /// Returns true if a viable candidate was found and a diagnostic was issued.
11840 static bool
11841 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11842                                SourceLocation OpLoc,
11843                                ArrayRef<Expr *> Args) {
11844   DeclarationName OpName =
11845     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11846   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11847   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11848                                 OverloadCandidateSet::CSK_Operator,
11849                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11850 }
11851 
11852 namespace {
11853 class BuildRecoveryCallExprRAII {
11854   Sema &SemaRef;
11855 public:
11856   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11857     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11858     SemaRef.IsBuildingRecoveryCallExpr = true;
11859   }
11860 
11861   ~BuildRecoveryCallExprRAII() {
11862     SemaRef.IsBuildingRecoveryCallExpr = false;
11863   }
11864 };
11865 
11866 }
11867 
11868 static std::unique_ptr<CorrectionCandidateCallback>
11869 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11870               bool HasTemplateArgs, bool AllowTypoCorrection) {
11871   if (!AllowTypoCorrection)
11872     return llvm::make_unique<NoTypoCorrectionCCC>();
11873   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11874                                                   HasTemplateArgs, ME);
11875 }
11876 
11877 /// Attempts to recover from a call where no functions were found.
11878 ///
11879 /// Returns true if new candidates were found.
11880 static ExprResult
11881 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11882                       UnresolvedLookupExpr *ULE,
11883                       SourceLocation LParenLoc,
11884                       MutableArrayRef<Expr *> Args,
11885                       SourceLocation RParenLoc,
11886                       bool EmptyLookup, bool AllowTypoCorrection) {
11887   // Do not try to recover if it is already building a recovery call.
11888   // This stops infinite loops for template instantiations like
11889   //
11890   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11891   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11892   //
11893   if (SemaRef.IsBuildingRecoveryCallExpr)
11894     return ExprError();
11895   BuildRecoveryCallExprRAII RCE(SemaRef);
11896 
11897   CXXScopeSpec SS;
11898   SS.Adopt(ULE->getQualifierLoc());
11899   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11900 
11901   TemplateArgumentListInfo TABuffer;
11902   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11903   if (ULE->hasExplicitTemplateArgs()) {
11904     ULE->copyTemplateArgumentsInto(TABuffer);
11905     ExplicitTemplateArgs = &TABuffer;
11906   }
11907 
11908   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11909                  Sema::LookupOrdinaryName);
11910   bool DoDiagnoseEmptyLookup = EmptyLookup;
11911   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11912                               OverloadCandidateSet::CSK_Normal,
11913                               ExplicitTemplateArgs, Args,
11914                               &DoDiagnoseEmptyLookup) &&
11915     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11916         S, SS, R,
11917         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11918                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11919         ExplicitTemplateArgs, Args)))
11920     return ExprError();
11921 
11922   assert(!R.empty() && "lookup results empty despite recovery");
11923 
11924   // If recovery created an ambiguity, just bail out.
11925   if (R.isAmbiguous()) {
11926     R.suppressDiagnostics();
11927     return ExprError();
11928   }
11929 
11930   // Build an implicit member call if appropriate.  Just drop the
11931   // casts and such from the call, we don't really care.
11932   ExprResult NewFn = ExprError();
11933   if ((*R.begin())->isCXXClassMember())
11934     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11935                                                     ExplicitTemplateArgs, S);
11936   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11937     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11938                                         ExplicitTemplateArgs);
11939   else
11940     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11941 
11942   if (NewFn.isInvalid())
11943     return ExprError();
11944 
11945   // This shouldn't cause an infinite loop because we're giving it
11946   // an expression with viable lookup results, which should never
11947   // end up here.
11948   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11949                                MultiExprArg(Args.data(), Args.size()),
11950                                RParenLoc);
11951 }
11952 
11953 /// Constructs and populates an OverloadedCandidateSet from
11954 /// the given function.
11955 /// \returns true when an the ExprResult output parameter has been set.
11956 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11957                                   UnresolvedLookupExpr *ULE,
11958                                   MultiExprArg Args,
11959                                   SourceLocation RParenLoc,
11960                                   OverloadCandidateSet *CandidateSet,
11961                                   ExprResult *Result) {
11962 #ifndef NDEBUG
11963   if (ULE->requiresADL()) {
11964     // To do ADL, we must have found an unqualified name.
11965     assert(!ULE->getQualifier() && "qualified name with ADL");
11966 
11967     // We don't perform ADL for implicit declarations of builtins.
11968     // Verify that this was correctly set up.
11969     FunctionDecl *F;
11970     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11971         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11972         F->getBuiltinID() && F->isImplicit())
11973       llvm_unreachable("performing ADL for builtin");
11974 
11975     // We don't perform ADL in C.
11976     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11977   }
11978 #endif
11979 
11980   UnbridgedCastsSet UnbridgedCasts;
11981   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11982     *Result = ExprError();
11983     return true;
11984   }
11985 
11986   // Add the functions denoted by the callee to the set of candidate
11987   // functions, including those from argument-dependent lookup.
11988   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11989 
11990   if (getLangOpts().MSVCCompat &&
11991       CurContext->isDependentContext() && !isSFINAEContext() &&
11992       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11993 
11994     OverloadCandidateSet::iterator Best;
11995     if (CandidateSet->empty() ||
11996         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
11997             OR_No_Viable_Function) {
11998       // In Microsoft mode, if we are inside a template class member function
11999       // then create a type dependent CallExpr. The goal is to postpone name
12000       // lookup to instantiation time to be able to search into type dependent
12001       // base classes.
12002       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12003                                       VK_RValue, RParenLoc);
12004       CE->setTypeDependent(true);
12005       CE->setValueDependent(true);
12006       CE->setInstantiationDependent(true);
12007       *Result = CE;
12008       return true;
12009     }
12010   }
12011 
12012   if (CandidateSet->empty())
12013     return false;
12014 
12015   UnbridgedCasts.restore();
12016   return false;
12017 }
12018 
12019 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12020 /// the completed call expression. If overload resolution fails, emits
12021 /// diagnostics and returns ExprError()
12022 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12023                                            UnresolvedLookupExpr *ULE,
12024                                            SourceLocation LParenLoc,
12025                                            MultiExprArg Args,
12026                                            SourceLocation RParenLoc,
12027                                            Expr *ExecConfig,
12028                                            OverloadCandidateSet *CandidateSet,
12029                                            OverloadCandidateSet::iterator *Best,
12030                                            OverloadingResult OverloadResult,
12031                                            bool AllowTypoCorrection) {
12032   if (CandidateSet->empty())
12033     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12034                                  RParenLoc, /*EmptyLookup=*/true,
12035                                  AllowTypoCorrection);
12036 
12037   switch (OverloadResult) {
12038   case OR_Success: {
12039     FunctionDecl *FDecl = (*Best)->Function;
12040     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12041     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12042       return ExprError();
12043     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12044     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12045                                          ExecConfig, /*IsExecConfig=*/false,
12046                                          (*Best)->IsADLCandidate);
12047   }
12048 
12049   case OR_No_Viable_Function: {
12050     // Try to recover by looking for viable functions which the user might
12051     // have meant to call.
12052     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12053                                                 Args, RParenLoc,
12054                                                 /*EmptyLookup=*/false,
12055                                                 AllowTypoCorrection);
12056     if (!Recovery.isInvalid())
12057       return Recovery;
12058 
12059     // If the user passes in a function that we can't take the address of, we
12060     // generally end up emitting really bad error messages. Here, we attempt to
12061     // emit better ones.
12062     for (const Expr *Arg : Args) {
12063       if (!Arg->getType()->isFunctionType())
12064         continue;
12065       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12066         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12067         if (FD &&
12068             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12069                                                        Arg->getExprLoc()))
12070           return ExprError();
12071       }
12072     }
12073 
12074     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call)
12075         << ULE->getName() << Fn->getSourceRange();
12076     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12077     break;
12078   }
12079 
12080   case OR_Ambiguous:
12081     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call)
12082         << ULE->getName() << Fn->getSourceRange();
12083     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12084     break;
12085 
12086   case OR_Deleted: {
12087     SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call)
12088         << (*Best)->Function->isDeleted() << ULE->getName()
12089         << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12090         << Fn->getSourceRange();
12091     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12092 
12093     // We emitted an error for the unavailable/deleted function call but keep
12094     // the call in the AST.
12095     FunctionDecl *FDecl = (*Best)->Function;
12096     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12097     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12098                                          ExecConfig, /*IsExecConfig=*/false,
12099                                          (*Best)->IsADLCandidate);
12100   }
12101   }
12102 
12103   // Overload resolution failed.
12104   return ExprError();
12105 }
12106 
12107 static void markUnaddressableCandidatesUnviable(Sema &S,
12108                                                 OverloadCandidateSet &CS) {
12109   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12110     if (I->Viable &&
12111         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12112       I->Viable = false;
12113       I->FailureKind = ovl_fail_addr_not_available;
12114     }
12115   }
12116 }
12117 
12118 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12119 /// (which eventually refers to the declaration Func) and the call
12120 /// arguments Args/NumArgs, attempt to resolve the function call down
12121 /// to a specific function. If overload resolution succeeds, returns
12122 /// the call expression produced by overload resolution.
12123 /// Otherwise, emits diagnostics and returns ExprError.
12124 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12125                                          UnresolvedLookupExpr *ULE,
12126                                          SourceLocation LParenLoc,
12127                                          MultiExprArg Args,
12128                                          SourceLocation RParenLoc,
12129                                          Expr *ExecConfig,
12130                                          bool AllowTypoCorrection,
12131                                          bool CalleesAddressIsTaken) {
12132   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12133                                     OverloadCandidateSet::CSK_Normal);
12134   ExprResult result;
12135 
12136   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12137                              &result))
12138     return result;
12139 
12140   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12141   // functions that aren't addressible are considered unviable.
12142   if (CalleesAddressIsTaken)
12143     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12144 
12145   OverloadCandidateSet::iterator Best;
12146   OverloadingResult OverloadResult =
12147       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12148 
12149   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12150                                   RParenLoc, ExecConfig, &CandidateSet,
12151                                   &Best, OverloadResult,
12152                                   AllowTypoCorrection);
12153 }
12154 
12155 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12156   return Functions.size() > 1 ||
12157     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12158 }
12159 
12160 /// Create a unary operation that may resolve to an overloaded
12161 /// operator.
12162 ///
12163 /// \param OpLoc The location of the operator itself (e.g., '*').
12164 ///
12165 /// \param Opc The UnaryOperatorKind that describes this operator.
12166 ///
12167 /// \param Fns The set of non-member functions that will be
12168 /// considered by overload resolution. The caller needs to build this
12169 /// set based on the context using, e.g.,
12170 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12171 /// set should not contain any member functions; those will be added
12172 /// by CreateOverloadedUnaryOp().
12173 ///
12174 /// \param Input The input argument.
12175 ExprResult
12176 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12177                               const UnresolvedSetImpl &Fns,
12178                               Expr *Input, bool PerformADL) {
12179   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12180   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12181   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12182   // TODO: provide better source location info.
12183   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12184 
12185   if (checkPlaceholderForOverload(*this, Input))
12186     return ExprError();
12187 
12188   Expr *Args[2] = { Input, nullptr };
12189   unsigned NumArgs = 1;
12190 
12191   // For post-increment and post-decrement, add the implicit '0' as
12192   // the second argument, so that we know this is a post-increment or
12193   // post-decrement.
12194   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12195     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12196     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12197                                      SourceLocation());
12198     NumArgs = 2;
12199   }
12200 
12201   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12202 
12203   if (Input->isTypeDependent()) {
12204     if (Fns.empty())
12205       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12206                                          VK_RValue, OK_Ordinary, OpLoc, false);
12207 
12208     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12209     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12210         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12211         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12212     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12213                                        Context.DependentTy, VK_RValue, OpLoc,
12214                                        FPOptions());
12215   }
12216 
12217   // Build an empty overload set.
12218   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12219 
12220   // Add the candidates from the given function set.
12221   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12222 
12223   // Add operator candidates that are member functions.
12224   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12225 
12226   // Add candidates from ADL.
12227   if (PerformADL) {
12228     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12229                                          /*ExplicitTemplateArgs*/nullptr,
12230                                          CandidateSet);
12231   }
12232 
12233   // Add builtin operator candidates.
12234   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12235 
12236   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12237 
12238   // Perform overload resolution.
12239   OverloadCandidateSet::iterator Best;
12240   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12241   case OR_Success: {
12242     // We found a built-in operator or an overloaded operator.
12243     FunctionDecl *FnDecl = Best->Function;
12244 
12245     if (FnDecl) {
12246       Expr *Base = nullptr;
12247       // We matched an overloaded operator. Build a call to that
12248       // operator.
12249 
12250       // Convert the arguments.
12251       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12252         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12253 
12254         ExprResult InputRes =
12255           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12256                                               Best->FoundDecl, Method);
12257         if (InputRes.isInvalid())
12258           return ExprError();
12259         Base = Input = InputRes.get();
12260       } else {
12261         // Convert the arguments.
12262         ExprResult InputInit
12263           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12264                                                       Context,
12265                                                       FnDecl->getParamDecl(0)),
12266                                       SourceLocation(),
12267                                       Input);
12268         if (InputInit.isInvalid())
12269           return ExprError();
12270         Input = InputInit.get();
12271       }
12272 
12273       // Build the actual expression node.
12274       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12275                                                 Base, HadMultipleCandidates,
12276                                                 OpLoc);
12277       if (FnExpr.isInvalid())
12278         return ExprError();
12279 
12280       // Determine the result type.
12281       QualType ResultTy = FnDecl->getReturnType();
12282       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12283       ResultTy = ResultTy.getNonLValueExprType(Context);
12284 
12285       Args[0] = Input;
12286       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12287           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12288           FPOptions(), Best->IsADLCandidate);
12289 
12290       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12291         return ExprError();
12292 
12293       if (CheckFunctionCall(FnDecl, TheCall,
12294                             FnDecl->getType()->castAs<FunctionProtoType>()))
12295         return ExprError();
12296 
12297       return MaybeBindToTemporary(TheCall);
12298     } else {
12299       // We matched a built-in operator. Convert the arguments, then
12300       // break out so that we will build the appropriate built-in
12301       // operator node.
12302       ExprResult InputRes = PerformImplicitConversion(
12303           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12304           CCK_ForBuiltinOverloadedOp);
12305       if (InputRes.isInvalid())
12306         return ExprError();
12307       Input = InputRes.get();
12308       break;
12309     }
12310   }
12311 
12312   case OR_No_Viable_Function:
12313     // This is an erroneous use of an operator which can be overloaded by
12314     // a non-member function. Check for non-member operators which were
12315     // defined too late to be candidates.
12316     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12317       // FIXME: Recover by calling the found function.
12318       return ExprError();
12319 
12320     // No viable function; fall through to handling this as a
12321     // built-in operator, which will produce an error message for us.
12322     break;
12323 
12324   case OR_Ambiguous:
12325     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12326         << UnaryOperator::getOpcodeStr(Opc)
12327         << Input->getType()
12328         << Input->getSourceRange();
12329     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12330                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12331     return ExprError();
12332 
12333   case OR_Deleted:
12334     Diag(OpLoc, diag::err_ovl_deleted_oper)
12335       << Best->Function->isDeleted()
12336       << UnaryOperator::getOpcodeStr(Opc)
12337       << getDeletedOrUnavailableSuffix(Best->Function)
12338       << Input->getSourceRange();
12339     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12340                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12341     return ExprError();
12342   }
12343 
12344   // Either we found no viable overloaded operator or we matched a
12345   // built-in operator. In either case, fall through to trying to
12346   // build a built-in operation.
12347   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12348 }
12349 
12350 /// Create a binary operation that may resolve to an overloaded
12351 /// operator.
12352 ///
12353 /// \param OpLoc The location of the operator itself (e.g., '+').
12354 ///
12355 /// \param Opc The BinaryOperatorKind that describes this operator.
12356 ///
12357 /// \param Fns The set of non-member functions that will be
12358 /// considered by overload resolution. The caller needs to build this
12359 /// set based on the context using, e.g.,
12360 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12361 /// set should not contain any member functions; those will be added
12362 /// by CreateOverloadedBinOp().
12363 ///
12364 /// \param LHS Left-hand argument.
12365 /// \param RHS Right-hand argument.
12366 ExprResult
12367 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12368                             BinaryOperatorKind Opc,
12369                             const UnresolvedSetImpl &Fns,
12370                             Expr *LHS, Expr *RHS, bool PerformADL) {
12371   Expr *Args[2] = { LHS, RHS };
12372   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12373 
12374   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12375   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12376 
12377   // If either side is type-dependent, create an appropriate dependent
12378   // expression.
12379   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12380     if (Fns.empty()) {
12381       // If there are no functions to store, just build a dependent
12382       // BinaryOperator or CompoundAssignment.
12383       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12384         return new (Context) BinaryOperator(
12385             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12386             OpLoc, FPFeatures);
12387 
12388       return new (Context) CompoundAssignOperator(
12389           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12390           Context.DependentTy, Context.DependentTy, OpLoc,
12391           FPFeatures);
12392     }
12393 
12394     // FIXME: save results of ADL from here?
12395     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12396     // TODO: provide better source location info in DNLoc component.
12397     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12398     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12399         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12400         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12401     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12402                                        Context.DependentTy, VK_RValue, OpLoc,
12403                                        FPFeatures);
12404   }
12405 
12406   // Always do placeholder-like conversions on the RHS.
12407   if (checkPlaceholderForOverload(*this, Args[1]))
12408     return ExprError();
12409 
12410   // Do placeholder-like conversion on the LHS; note that we should
12411   // not get here with a PseudoObject LHS.
12412   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12413   if (checkPlaceholderForOverload(*this, Args[0]))
12414     return ExprError();
12415 
12416   // If this is the assignment operator, we only perform overload resolution
12417   // if the left-hand side is a class or enumeration type. This is actually
12418   // a hack. The standard requires that we do overload resolution between the
12419   // various built-in candidates, but as DR507 points out, this can lead to
12420   // problems. So we do it this way, which pretty much follows what GCC does.
12421   // Note that we go the traditional code path for compound assignment forms.
12422   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12423     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12424 
12425   // If this is the .* operator, which is not overloadable, just
12426   // create a built-in binary operator.
12427   if (Opc == BO_PtrMemD)
12428     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12429 
12430   // Build an empty overload set.
12431   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12432 
12433   // Add the candidates from the given function set.
12434   AddFunctionCandidates(Fns, Args, CandidateSet);
12435 
12436   // Add operator candidates that are member functions.
12437   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12438 
12439   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12440   // performed for an assignment operator (nor for operator[] nor operator->,
12441   // which don't get here).
12442   if (Opc != BO_Assign && PerformADL)
12443     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12444                                          /*ExplicitTemplateArgs*/ nullptr,
12445                                          CandidateSet);
12446 
12447   // Add builtin operator candidates.
12448   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12449 
12450   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12451 
12452   // Perform overload resolution.
12453   OverloadCandidateSet::iterator Best;
12454   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12455     case OR_Success: {
12456       // We found a built-in operator or an overloaded operator.
12457       FunctionDecl *FnDecl = Best->Function;
12458 
12459       if (FnDecl) {
12460         Expr *Base = nullptr;
12461         // We matched an overloaded operator. Build a call to that
12462         // operator.
12463 
12464         // Convert the arguments.
12465         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12466           // Best->Access is only meaningful for class members.
12467           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12468 
12469           ExprResult Arg1 =
12470             PerformCopyInitialization(
12471               InitializedEntity::InitializeParameter(Context,
12472                                                      FnDecl->getParamDecl(0)),
12473               SourceLocation(), Args[1]);
12474           if (Arg1.isInvalid())
12475             return ExprError();
12476 
12477           ExprResult Arg0 =
12478             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12479                                                 Best->FoundDecl, Method);
12480           if (Arg0.isInvalid())
12481             return ExprError();
12482           Base = Args[0] = Arg0.getAs<Expr>();
12483           Args[1] = RHS = Arg1.getAs<Expr>();
12484         } else {
12485           // Convert the arguments.
12486           ExprResult Arg0 = PerformCopyInitialization(
12487             InitializedEntity::InitializeParameter(Context,
12488                                                    FnDecl->getParamDecl(0)),
12489             SourceLocation(), Args[0]);
12490           if (Arg0.isInvalid())
12491             return ExprError();
12492 
12493           ExprResult Arg1 =
12494             PerformCopyInitialization(
12495               InitializedEntity::InitializeParameter(Context,
12496                                                      FnDecl->getParamDecl(1)),
12497               SourceLocation(), Args[1]);
12498           if (Arg1.isInvalid())
12499             return ExprError();
12500           Args[0] = LHS = Arg0.getAs<Expr>();
12501           Args[1] = RHS = Arg1.getAs<Expr>();
12502         }
12503 
12504         // Build the actual expression node.
12505         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12506                                                   Best->FoundDecl, Base,
12507                                                   HadMultipleCandidates, OpLoc);
12508         if (FnExpr.isInvalid())
12509           return ExprError();
12510 
12511         // Determine the result type.
12512         QualType ResultTy = FnDecl->getReturnType();
12513         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12514         ResultTy = ResultTy.getNonLValueExprType(Context);
12515 
12516         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
12517             Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
12518             Best->IsADLCandidate);
12519 
12520         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12521                                 FnDecl))
12522           return ExprError();
12523 
12524         ArrayRef<const Expr *> ArgsArray(Args, 2);
12525         const Expr *ImplicitThis = nullptr;
12526         // Cut off the implicit 'this'.
12527         if (isa<CXXMethodDecl>(FnDecl)) {
12528           ImplicitThis = ArgsArray[0];
12529           ArgsArray = ArgsArray.slice(1);
12530         }
12531 
12532         // Check for a self move.
12533         if (Op == OO_Equal)
12534           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12535 
12536         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12537                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12538                   VariadicDoesNotApply);
12539 
12540         return MaybeBindToTemporary(TheCall);
12541       } else {
12542         // We matched a built-in operator. Convert the arguments, then
12543         // break out so that we will build the appropriate built-in
12544         // operator node.
12545         ExprResult ArgsRes0 = PerformImplicitConversion(
12546             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12547             AA_Passing, CCK_ForBuiltinOverloadedOp);
12548         if (ArgsRes0.isInvalid())
12549           return ExprError();
12550         Args[0] = ArgsRes0.get();
12551 
12552         ExprResult ArgsRes1 = PerformImplicitConversion(
12553             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12554             AA_Passing, CCK_ForBuiltinOverloadedOp);
12555         if (ArgsRes1.isInvalid())
12556           return ExprError();
12557         Args[1] = ArgsRes1.get();
12558         break;
12559       }
12560     }
12561 
12562     case OR_No_Viable_Function: {
12563       // C++ [over.match.oper]p9:
12564       //   If the operator is the operator , [...] and there are no
12565       //   viable functions, then the operator is assumed to be the
12566       //   built-in operator and interpreted according to clause 5.
12567       if (Opc == BO_Comma)
12568         break;
12569 
12570       // For class as left operand for assignment or compound assignment
12571       // operator do not fall through to handling in built-in, but report that
12572       // no overloaded assignment operator found
12573       ExprResult Result = ExprError();
12574       if (Args[0]->getType()->isRecordType() &&
12575           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12576         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12577              << BinaryOperator::getOpcodeStr(Opc)
12578              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12579         if (Args[0]->getType()->isIncompleteType()) {
12580           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12581             << Args[0]->getType()
12582             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12583         }
12584       } else {
12585         // This is an erroneous use of an operator which can be overloaded by
12586         // a non-member function. Check for non-member operators which were
12587         // defined too late to be candidates.
12588         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12589           // FIXME: Recover by calling the found function.
12590           return ExprError();
12591 
12592         // No viable function; try to create a built-in operation, which will
12593         // produce an error. Then, show the non-viable candidates.
12594         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12595       }
12596       assert(Result.isInvalid() &&
12597              "C++ binary operator overloading is missing candidates!");
12598       if (Result.isInvalid())
12599         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12600                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12601       return Result;
12602     }
12603 
12604     case OR_Ambiguous:
12605       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12606           << BinaryOperator::getOpcodeStr(Opc)
12607           << Args[0]->getType() << Args[1]->getType()
12608           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12609       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12610                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12611       return ExprError();
12612 
12613     case OR_Deleted:
12614       if (isImplicitlyDeleted(Best->Function)) {
12615         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12616         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12617           << Context.getRecordType(Method->getParent())
12618           << getSpecialMember(Method);
12619 
12620         // The user probably meant to call this special member. Just
12621         // explain why it's deleted.
12622         NoteDeletedFunction(Method);
12623         return ExprError();
12624       } else {
12625         Diag(OpLoc, diag::err_ovl_deleted_oper)
12626           << Best->Function->isDeleted()
12627           << BinaryOperator::getOpcodeStr(Opc)
12628           << getDeletedOrUnavailableSuffix(Best->Function)
12629           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12630       }
12631       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12632                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12633       return ExprError();
12634   }
12635 
12636   // We matched a built-in operator; build it.
12637   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12638 }
12639 
12640 ExprResult
12641 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12642                                          SourceLocation RLoc,
12643                                          Expr *Base, Expr *Idx) {
12644   Expr *Args[2] = { Base, Idx };
12645   DeclarationName OpName =
12646       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12647 
12648   // If either side is type-dependent, create an appropriate dependent
12649   // expression.
12650   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12651 
12652     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12653     // CHECKME: no 'operator' keyword?
12654     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12655     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12656     UnresolvedLookupExpr *Fn
12657       = UnresolvedLookupExpr::Create(Context, NamingClass,
12658                                      NestedNameSpecifierLoc(), OpNameInfo,
12659                                      /*ADL*/ true, /*Overloaded*/ false,
12660                                      UnresolvedSetIterator(),
12661                                      UnresolvedSetIterator());
12662     // Can't add any actual overloads yet
12663 
12664     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
12665                                        Context.DependentTy, VK_RValue, RLoc,
12666                                        FPOptions());
12667   }
12668 
12669   // Handle placeholders on both operands.
12670   if (checkPlaceholderForOverload(*this, Args[0]))
12671     return ExprError();
12672   if (checkPlaceholderForOverload(*this, Args[1]))
12673     return ExprError();
12674 
12675   // Build an empty overload set.
12676   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12677 
12678   // Subscript can only be overloaded as a member function.
12679 
12680   // Add operator candidates that are member functions.
12681   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12682 
12683   // Add builtin operator candidates.
12684   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12685 
12686   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12687 
12688   // Perform overload resolution.
12689   OverloadCandidateSet::iterator Best;
12690   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12691     case OR_Success: {
12692       // We found a built-in operator or an overloaded operator.
12693       FunctionDecl *FnDecl = Best->Function;
12694 
12695       if (FnDecl) {
12696         // We matched an overloaded operator. Build a call to that
12697         // operator.
12698 
12699         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12700 
12701         // Convert the arguments.
12702         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12703         ExprResult Arg0 =
12704           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12705                                               Best->FoundDecl, Method);
12706         if (Arg0.isInvalid())
12707           return ExprError();
12708         Args[0] = Arg0.get();
12709 
12710         // Convert the arguments.
12711         ExprResult InputInit
12712           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12713                                                       Context,
12714                                                       FnDecl->getParamDecl(0)),
12715                                       SourceLocation(),
12716                                       Args[1]);
12717         if (InputInit.isInvalid())
12718           return ExprError();
12719 
12720         Args[1] = InputInit.getAs<Expr>();
12721 
12722         // Build the actual expression node.
12723         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12724         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12725         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12726                                                   Best->FoundDecl,
12727                                                   Base,
12728                                                   HadMultipleCandidates,
12729                                                   OpLocInfo.getLoc(),
12730                                                   OpLocInfo.getInfo());
12731         if (FnExpr.isInvalid())
12732           return ExprError();
12733 
12734         // Determine the result type
12735         QualType ResultTy = FnDecl->getReturnType();
12736         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12737         ResultTy = ResultTy.getNonLValueExprType(Context);
12738 
12739         CXXOperatorCallExpr *TheCall =
12740             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
12741                                         Args, ResultTy, VK, RLoc, FPOptions());
12742 
12743         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12744           return ExprError();
12745 
12746         if (CheckFunctionCall(Method, TheCall,
12747                               Method->getType()->castAs<FunctionProtoType>()))
12748           return ExprError();
12749 
12750         return MaybeBindToTemporary(TheCall);
12751       } else {
12752         // We matched a built-in operator. Convert the arguments, then
12753         // break out so that we will build the appropriate built-in
12754         // operator node.
12755         ExprResult ArgsRes0 = PerformImplicitConversion(
12756             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12757             AA_Passing, CCK_ForBuiltinOverloadedOp);
12758         if (ArgsRes0.isInvalid())
12759           return ExprError();
12760         Args[0] = ArgsRes0.get();
12761 
12762         ExprResult ArgsRes1 = PerformImplicitConversion(
12763             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12764             AA_Passing, CCK_ForBuiltinOverloadedOp);
12765         if (ArgsRes1.isInvalid())
12766           return ExprError();
12767         Args[1] = ArgsRes1.get();
12768 
12769         break;
12770       }
12771     }
12772 
12773     case OR_No_Viable_Function: {
12774       if (CandidateSet.empty())
12775         Diag(LLoc, diag::err_ovl_no_oper)
12776           << Args[0]->getType() << /*subscript*/ 0
12777           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12778       else
12779         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12780           << Args[0]->getType()
12781           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12782       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12783                                   "[]", LLoc);
12784       return ExprError();
12785     }
12786 
12787     case OR_Ambiguous:
12788       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12789           << "[]"
12790           << Args[0]->getType() << Args[1]->getType()
12791           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12792       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12793                                   "[]", LLoc);
12794       return ExprError();
12795 
12796     case OR_Deleted:
12797       Diag(LLoc, diag::err_ovl_deleted_oper)
12798         << Best->Function->isDeleted() << "[]"
12799         << getDeletedOrUnavailableSuffix(Best->Function)
12800         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12801       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12802                                   "[]", LLoc);
12803       return ExprError();
12804     }
12805 
12806   // We matched a built-in operator; build it.
12807   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12808 }
12809 
12810 /// BuildCallToMemberFunction - Build a call to a member
12811 /// function. MemExpr is the expression that refers to the member
12812 /// function (and includes the object parameter), Args/NumArgs are the
12813 /// arguments to the function call (not including the object
12814 /// parameter). The caller needs to validate that the member
12815 /// expression refers to a non-static member function or an overloaded
12816 /// member function.
12817 ExprResult
12818 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12819                                 SourceLocation LParenLoc,
12820                                 MultiExprArg Args,
12821                                 SourceLocation RParenLoc) {
12822   assert(MemExprE->getType() == Context.BoundMemberTy ||
12823          MemExprE->getType() == Context.OverloadTy);
12824 
12825   // Dig out the member expression. This holds both the object
12826   // argument and the member function we're referring to.
12827   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12828 
12829   // Determine whether this is a call to a pointer-to-member function.
12830   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12831     assert(op->getType() == Context.BoundMemberTy);
12832     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12833 
12834     QualType fnType =
12835       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12836 
12837     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12838     QualType resultType = proto->getCallResultType(Context);
12839     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12840 
12841     // Check that the object type isn't more qualified than the
12842     // member function we're calling.
12843     Qualifiers funcQuals = proto->getTypeQuals();
12844 
12845     QualType objectType = op->getLHS()->getType();
12846     if (op->getOpcode() == BO_PtrMemI)
12847       objectType = objectType->castAs<PointerType>()->getPointeeType();
12848     Qualifiers objectQuals = objectType.getQualifiers();
12849 
12850     Qualifiers difference = objectQuals - funcQuals;
12851     difference.removeObjCGCAttr();
12852     difference.removeAddressSpace();
12853     if (difference) {
12854       std::string qualsString = difference.getAsString();
12855       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12856         << fnType.getUnqualifiedType()
12857         << qualsString
12858         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12859     }
12860 
12861     CXXMemberCallExpr *call =
12862         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
12863                                   valueKind, RParenLoc, proto->getNumParams());
12864 
12865     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
12866                             call, nullptr))
12867       return ExprError();
12868 
12869     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12870       return ExprError();
12871 
12872     if (CheckOtherCall(call, proto))
12873       return ExprError();
12874 
12875     return MaybeBindToTemporary(call);
12876   }
12877 
12878   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12879     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
12880                             RParenLoc);
12881 
12882   UnbridgedCastsSet UnbridgedCasts;
12883   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12884     return ExprError();
12885 
12886   MemberExpr *MemExpr;
12887   CXXMethodDecl *Method = nullptr;
12888   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12889   NestedNameSpecifier *Qualifier = nullptr;
12890   if (isa<MemberExpr>(NakedMemExpr)) {
12891     MemExpr = cast<MemberExpr>(NakedMemExpr);
12892     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12893     FoundDecl = MemExpr->getFoundDecl();
12894     Qualifier = MemExpr->getQualifier();
12895     UnbridgedCasts.restore();
12896   } else {
12897     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12898     Qualifier = UnresExpr->getQualifier();
12899 
12900     QualType ObjectType = UnresExpr->getBaseType();
12901     Expr::Classification ObjectClassification
12902       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12903                             : UnresExpr->getBase()->Classify(Context);
12904 
12905     // Add overload candidates
12906     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12907                                       OverloadCandidateSet::CSK_Normal);
12908 
12909     // FIXME: avoid copy.
12910     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12911     if (UnresExpr->hasExplicitTemplateArgs()) {
12912       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12913       TemplateArgs = &TemplateArgsBuffer;
12914     }
12915 
12916     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12917            E = UnresExpr->decls_end(); I != E; ++I) {
12918 
12919       NamedDecl *Func = *I;
12920       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12921       if (isa<UsingShadowDecl>(Func))
12922         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12923 
12924 
12925       // Microsoft supports direct constructor calls.
12926       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12927         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12928                              Args, CandidateSet);
12929       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12930         // If explicit template arguments were provided, we can't call a
12931         // non-template member function.
12932         if (TemplateArgs)
12933           continue;
12934 
12935         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12936                            ObjectClassification, Args, CandidateSet,
12937                            /*SuppressUserConversions=*/false);
12938       } else {
12939         AddMethodTemplateCandidate(
12940             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12941             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12942             /*SuppressUsedConversions=*/false);
12943       }
12944     }
12945 
12946     DeclarationName DeclName = UnresExpr->getMemberName();
12947 
12948     UnbridgedCasts.restore();
12949 
12950     OverloadCandidateSet::iterator Best;
12951     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
12952                                             Best)) {
12953     case OR_Success:
12954       Method = cast<CXXMethodDecl>(Best->Function);
12955       FoundDecl = Best->FoundDecl;
12956       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12957       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12958         return ExprError();
12959       // If FoundDecl is different from Method (such as if one is a template
12960       // and the other a specialization), make sure DiagnoseUseOfDecl is
12961       // called on both.
12962       // FIXME: This would be more comprehensively addressed by modifying
12963       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12964       // being used.
12965       if (Method != FoundDecl.getDecl() &&
12966                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12967         return ExprError();
12968       break;
12969 
12970     case OR_No_Viable_Function:
12971       Diag(UnresExpr->getMemberLoc(),
12972            diag::err_ovl_no_viable_member_function_in_call)
12973         << DeclName << MemExprE->getSourceRange();
12974       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12975       // FIXME: Leaking incoming expressions!
12976       return ExprError();
12977 
12978     case OR_Ambiguous:
12979       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12980         << DeclName << MemExprE->getSourceRange();
12981       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12982       // FIXME: Leaking incoming expressions!
12983       return ExprError();
12984 
12985     case OR_Deleted:
12986       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12987         << Best->Function->isDeleted()
12988         << DeclName
12989         << getDeletedOrUnavailableSuffix(Best->Function)
12990         << MemExprE->getSourceRange();
12991       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12992       // FIXME: Leaking incoming expressions!
12993       return ExprError();
12994     }
12995 
12996     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12997 
12998     // If overload resolution picked a static member, build a
12999     // non-member call based on that function.
13000     if (Method->isStatic()) {
13001       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13002                                    RParenLoc);
13003     }
13004 
13005     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13006   }
13007 
13008   QualType ResultType = Method->getReturnType();
13009   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13010   ResultType = ResultType.getNonLValueExprType(Context);
13011 
13012   assert(Method && "Member call to something that isn't a method?");
13013   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13014   CXXMemberCallExpr *TheCall =
13015       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13016                                 RParenLoc, Proto->getNumParams());
13017 
13018   // Check for a valid return type.
13019   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13020                           TheCall, Method))
13021     return ExprError();
13022 
13023   // Convert the object argument (for a non-static member function call).
13024   // We only need to do this if there was actually an overload; otherwise
13025   // it was done at lookup.
13026   if (!Method->isStatic()) {
13027     ExprResult ObjectArg =
13028       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13029                                           FoundDecl, Method);
13030     if (ObjectArg.isInvalid())
13031       return ExprError();
13032     MemExpr->setBase(ObjectArg.get());
13033   }
13034 
13035   // Convert the rest of the arguments
13036   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13037                               RParenLoc))
13038     return ExprError();
13039 
13040   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13041 
13042   if (CheckFunctionCall(Method, TheCall, Proto))
13043     return ExprError();
13044 
13045   // In the case the method to call was not selected by the overloading
13046   // resolution process, we still need to handle the enable_if attribute. Do
13047   // that here, so it will not hide previous -- and more relevant -- errors.
13048   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13049     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13050       Diag(MemE->getMemberLoc(),
13051            diag::err_ovl_no_viable_member_function_in_call)
13052           << Method << Method->getSourceRange();
13053       Diag(Method->getLocation(),
13054            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13055           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13056       return ExprError();
13057     }
13058   }
13059 
13060   if ((isa<CXXConstructorDecl>(CurContext) ||
13061        isa<CXXDestructorDecl>(CurContext)) &&
13062       TheCall->getMethodDecl()->isPure()) {
13063     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13064 
13065     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13066         MemExpr->performsVirtualDispatch(getLangOpts())) {
13067       Diag(MemExpr->getBeginLoc(),
13068            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13069           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13070           << MD->getParent()->getDeclName();
13071 
13072       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13073       if (getLangOpts().AppleKext)
13074         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13075             << MD->getParent()->getDeclName() << MD->getDeclName();
13076     }
13077   }
13078 
13079   if (CXXDestructorDecl *DD =
13080           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13081     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13082     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13083     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13084                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13085                          MemExpr->getMemberLoc());
13086   }
13087 
13088   return MaybeBindToTemporary(TheCall);
13089 }
13090 
13091 /// BuildCallToObjectOfClassType - Build a call to an object of class
13092 /// type (C++ [over.call.object]), which can end up invoking an
13093 /// overloaded function call operator (@c operator()) or performing a
13094 /// user-defined conversion on the object argument.
13095 ExprResult
13096 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13097                                    SourceLocation LParenLoc,
13098                                    MultiExprArg Args,
13099                                    SourceLocation RParenLoc) {
13100   if (checkPlaceholderForOverload(*this, Obj))
13101     return ExprError();
13102   ExprResult Object = Obj;
13103 
13104   UnbridgedCastsSet UnbridgedCasts;
13105   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13106     return ExprError();
13107 
13108   assert(Object.get()->getType()->isRecordType() &&
13109          "Requires object type argument");
13110   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13111 
13112   // C++ [over.call.object]p1:
13113   //  If the primary-expression E in the function call syntax
13114   //  evaluates to a class object of type "cv T", then the set of
13115   //  candidate functions includes at least the function call
13116   //  operators of T. The function call operators of T are obtained by
13117   //  ordinary lookup of the name operator() in the context of
13118   //  (E).operator().
13119   OverloadCandidateSet CandidateSet(LParenLoc,
13120                                     OverloadCandidateSet::CSK_Operator);
13121   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13122 
13123   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13124                           diag::err_incomplete_object_call, Object.get()))
13125     return true;
13126 
13127   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13128   LookupQualifiedName(R, Record->getDecl());
13129   R.suppressDiagnostics();
13130 
13131   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13132        Oper != OperEnd; ++Oper) {
13133     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13134                        Object.get()->Classify(Context), Args, CandidateSet,
13135                        /*SuppressUserConversions=*/false);
13136   }
13137 
13138   // C++ [over.call.object]p2:
13139   //   In addition, for each (non-explicit in C++0x) conversion function
13140   //   declared in T of the form
13141   //
13142   //        operator conversion-type-id () cv-qualifier;
13143   //
13144   //   where cv-qualifier is the same cv-qualification as, or a
13145   //   greater cv-qualification than, cv, and where conversion-type-id
13146   //   denotes the type "pointer to function of (P1,...,Pn) returning
13147   //   R", or the type "reference to pointer to function of
13148   //   (P1,...,Pn) returning R", or the type "reference to function
13149   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13150   //   is also considered as a candidate function. Similarly,
13151   //   surrogate call functions are added to the set of candidate
13152   //   functions for each conversion function declared in an
13153   //   accessible base class provided the function is not hidden
13154   //   within T by another intervening declaration.
13155   const auto &Conversions =
13156       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13157   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13158     NamedDecl *D = *I;
13159     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13160     if (isa<UsingShadowDecl>(D))
13161       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13162 
13163     // Skip over templated conversion functions; they aren't
13164     // surrogates.
13165     if (isa<FunctionTemplateDecl>(D))
13166       continue;
13167 
13168     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13169     if (!Conv->isExplicit()) {
13170       // Strip the reference type (if any) and then the pointer type (if
13171       // any) to get down to what might be a function type.
13172       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13173       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13174         ConvType = ConvPtrType->getPointeeType();
13175 
13176       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13177       {
13178         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13179                               Object.get(), Args, CandidateSet);
13180       }
13181     }
13182   }
13183 
13184   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13185 
13186   // Perform overload resolution.
13187   OverloadCandidateSet::iterator Best;
13188   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13189                                           Best)) {
13190   case OR_Success:
13191     // Overload resolution succeeded; we'll build the appropriate call
13192     // below.
13193     break;
13194 
13195   case OR_No_Viable_Function:
13196     if (CandidateSet.empty())
13197       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper)
13198           << Object.get()->getType() << /*call*/ 1
13199           << Object.get()->getSourceRange();
13200     else
13201       Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call)
13202           << Object.get()->getType() << Object.get()->getSourceRange();
13203     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13204     break;
13205 
13206   case OR_Ambiguous:
13207     Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call)
13208         << Object.get()->getType() << Object.get()->getSourceRange();
13209     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13210     break;
13211 
13212   case OR_Deleted:
13213     Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call)
13214         << Best->Function->isDeleted() << Object.get()->getType()
13215         << getDeletedOrUnavailableSuffix(Best->Function)
13216         << Object.get()->getSourceRange();
13217     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13218     break;
13219   }
13220 
13221   if (Best == CandidateSet.end())
13222     return true;
13223 
13224   UnbridgedCasts.restore();
13225 
13226   if (Best->Function == nullptr) {
13227     // Since there is no function declaration, this is one of the
13228     // surrogate candidates. Dig out the conversion function.
13229     CXXConversionDecl *Conv
13230       = cast<CXXConversionDecl>(
13231                          Best->Conversions[0].UserDefined.ConversionFunction);
13232 
13233     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13234                               Best->FoundDecl);
13235     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13236       return ExprError();
13237     assert(Conv == Best->FoundDecl.getDecl() &&
13238              "Found Decl & conversion-to-functionptr should be same, right?!");
13239     // We selected one of the surrogate functions that converts the
13240     // object parameter to a function pointer. Perform the conversion
13241     // on the object argument, then let ActOnCallExpr finish the job.
13242 
13243     // Create an implicit member expr to refer to the conversion operator.
13244     // and then call it.
13245     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13246                                              Conv, HadMultipleCandidates);
13247     if (Call.isInvalid())
13248       return ExprError();
13249     // Record usage of conversion in an implicit cast.
13250     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13251                                     CK_UserDefinedConversion, Call.get(),
13252                                     nullptr, VK_RValue);
13253 
13254     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13255   }
13256 
13257   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13258 
13259   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13260   // that calls this method, using Object for the implicit object
13261   // parameter and passing along the remaining arguments.
13262   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13263 
13264   // An error diagnostic has already been printed when parsing the declaration.
13265   if (Method->isInvalidDecl())
13266     return ExprError();
13267 
13268   const FunctionProtoType *Proto =
13269     Method->getType()->getAs<FunctionProtoType>();
13270 
13271   unsigned NumParams = Proto->getNumParams();
13272 
13273   DeclarationNameInfo OpLocInfo(
13274                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13275   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13276   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13277                                            Obj, HadMultipleCandidates,
13278                                            OpLocInfo.getLoc(),
13279                                            OpLocInfo.getInfo());
13280   if (NewFn.isInvalid())
13281     return true;
13282 
13283   // The number of argument slots to allocate in the call. If we have default
13284   // arguments we need to allocate space for them as well. We additionally
13285   // need one more slot for the object parameter.
13286   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13287 
13288   // Build the full argument list for the method call (the implicit object
13289   // parameter is placed at the beginning of the list).
13290   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13291 
13292   bool IsError = false;
13293 
13294   // Initialize the implicit object parameter.
13295   ExprResult ObjRes =
13296     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13297                                         Best->FoundDecl, Method);
13298   if (ObjRes.isInvalid())
13299     IsError = true;
13300   else
13301     Object = ObjRes;
13302   MethodArgs[0] = Object.get();
13303 
13304   // Check the argument types.
13305   for (unsigned i = 0; i != NumParams; i++) {
13306     Expr *Arg;
13307     if (i < Args.size()) {
13308       Arg = Args[i];
13309 
13310       // Pass the argument.
13311 
13312       ExprResult InputInit
13313         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13314                                                     Context,
13315                                                     Method->getParamDecl(i)),
13316                                     SourceLocation(), Arg);
13317 
13318       IsError |= InputInit.isInvalid();
13319       Arg = InputInit.getAs<Expr>();
13320     } else {
13321       ExprResult DefArg
13322         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13323       if (DefArg.isInvalid()) {
13324         IsError = true;
13325         break;
13326       }
13327 
13328       Arg = DefArg.getAs<Expr>();
13329     }
13330 
13331     MethodArgs[i + 1] = Arg;
13332   }
13333 
13334   // If this is a variadic call, handle args passed through "...".
13335   if (Proto->isVariadic()) {
13336     // Promote the arguments (C99 6.5.2.2p7).
13337     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13338       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13339                                                         nullptr);
13340       IsError |= Arg.isInvalid();
13341       MethodArgs[i + 1] = Arg.get();
13342     }
13343   }
13344 
13345   if (IsError)
13346     return true;
13347 
13348   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13349 
13350   // Once we've built TheCall, all of the expressions are properly owned.
13351   QualType ResultTy = Method->getReturnType();
13352   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13353   ResultTy = ResultTy.getNonLValueExprType(Context);
13354 
13355   CXXOperatorCallExpr *TheCall =
13356       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
13357                                   ResultTy, VK, RParenLoc, FPOptions());
13358 
13359   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13360     return true;
13361 
13362   if (CheckFunctionCall(Method, TheCall, Proto))
13363     return true;
13364 
13365   return MaybeBindToTemporary(TheCall);
13366 }
13367 
13368 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13369 ///  (if one exists), where @c Base is an expression of class type and
13370 /// @c Member is the name of the member we're trying to find.
13371 ExprResult
13372 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13373                                bool *NoArrowOperatorFound) {
13374   assert(Base->getType()->isRecordType() &&
13375          "left-hand side must have class type");
13376 
13377   if (checkPlaceholderForOverload(*this, Base))
13378     return ExprError();
13379 
13380   SourceLocation Loc = Base->getExprLoc();
13381 
13382   // C++ [over.ref]p1:
13383   //
13384   //   [...] An expression x->m is interpreted as (x.operator->())->m
13385   //   for a class object x of type T if T::operator->() exists and if
13386   //   the operator is selected as the best match function by the
13387   //   overload resolution mechanism (13.3).
13388   DeclarationName OpName =
13389     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13390   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13391   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13392 
13393   if (RequireCompleteType(Loc, Base->getType(),
13394                           diag::err_typecheck_incomplete_tag, Base))
13395     return ExprError();
13396 
13397   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13398   LookupQualifiedName(R, BaseRecord->getDecl());
13399   R.suppressDiagnostics();
13400 
13401   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13402        Oper != OperEnd; ++Oper) {
13403     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13404                        None, CandidateSet, /*SuppressUserConversions=*/false);
13405   }
13406 
13407   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13408 
13409   // Perform overload resolution.
13410   OverloadCandidateSet::iterator Best;
13411   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13412   case OR_Success:
13413     // Overload resolution succeeded; we'll build the call below.
13414     break;
13415 
13416   case OR_No_Viable_Function:
13417     if (CandidateSet.empty()) {
13418       QualType BaseType = Base->getType();
13419       if (NoArrowOperatorFound) {
13420         // Report this specific error to the caller instead of emitting a
13421         // diagnostic, as requested.
13422         *NoArrowOperatorFound = true;
13423         return ExprError();
13424       }
13425       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13426         << BaseType << Base->getSourceRange();
13427       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13428         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13429           << FixItHint::CreateReplacement(OpLoc, ".");
13430       }
13431     } else
13432       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13433         << "operator->" << Base->getSourceRange();
13434     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13435     return ExprError();
13436 
13437   case OR_Ambiguous:
13438     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13439       << "->" << Base->getType() << Base->getSourceRange();
13440     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13441     return ExprError();
13442 
13443   case OR_Deleted:
13444     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13445       << Best->Function->isDeleted()
13446       << "->"
13447       << getDeletedOrUnavailableSuffix(Best->Function)
13448       << Base->getSourceRange();
13449     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13450     return ExprError();
13451   }
13452 
13453   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13454 
13455   // Convert the object parameter.
13456   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13457   ExprResult BaseResult =
13458     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13459                                         Best->FoundDecl, Method);
13460   if (BaseResult.isInvalid())
13461     return ExprError();
13462   Base = BaseResult.get();
13463 
13464   // Build the operator call.
13465   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13466                                             Base, HadMultipleCandidates, OpLoc);
13467   if (FnExpr.isInvalid())
13468     return ExprError();
13469 
13470   QualType ResultTy = Method->getReturnType();
13471   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13472   ResultTy = ResultTy.getNonLValueExprType(Context);
13473   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13474       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
13475 
13476   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13477     return ExprError();
13478 
13479   if (CheckFunctionCall(Method, TheCall,
13480                         Method->getType()->castAs<FunctionProtoType>()))
13481     return ExprError();
13482 
13483   return MaybeBindToTemporary(TheCall);
13484 }
13485 
13486 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13487 /// a literal operator described by the provided lookup results.
13488 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13489                                           DeclarationNameInfo &SuffixInfo,
13490                                           ArrayRef<Expr*> Args,
13491                                           SourceLocation LitEndLoc,
13492                                        TemplateArgumentListInfo *TemplateArgs) {
13493   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13494 
13495   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13496                                     OverloadCandidateSet::CSK_Normal);
13497   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13498                         /*SuppressUserConversions=*/true);
13499 
13500   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13501 
13502   // Perform overload resolution. This will usually be trivial, but might need
13503   // to perform substitutions for a literal operator template.
13504   OverloadCandidateSet::iterator Best;
13505   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13506   case OR_Success:
13507   case OR_Deleted:
13508     break;
13509 
13510   case OR_No_Viable_Function:
13511     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13512       << R.getLookupName();
13513     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13514     return ExprError();
13515 
13516   case OR_Ambiguous:
13517     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13518     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13519     return ExprError();
13520   }
13521 
13522   FunctionDecl *FD = Best->Function;
13523   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13524                                         nullptr, HadMultipleCandidates,
13525                                         SuffixInfo.getLoc(),
13526                                         SuffixInfo.getInfo());
13527   if (Fn.isInvalid())
13528     return true;
13529 
13530   // Check the argument types. This should almost always be a no-op, except
13531   // that array-to-pointer decay is applied to string literals.
13532   Expr *ConvArgs[2];
13533   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13534     ExprResult InputInit = PerformCopyInitialization(
13535       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13536       SourceLocation(), Args[ArgIdx]);
13537     if (InputInit.isInvalid())
13538       return true;
13539     ConvArgs[ArgIdx] = InputInit.get();
13540   }
13541 
13542   QualType ResultTy = FD->getReturnType();
13543   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13544   ResultTy = ResultTy.getNonLValueExprType(Context);
13545 
13546   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
13547       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
13548       VK, LitEndLoc, UDSuffixLoc);
13549 
13550   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13551     return ExprError();
13552 
13553   if (CheckFunctionCall(FD, UDL, nullptr))
13554     return ExprError();
13555 
13556   return MaybeBindToTemporary(UDL);
13557 }
13558 
13559 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13560 /// given LookupResult is non-empty, it is assumed to describe a member which
13561 /// will be invoked. Otherwise, the function will be found via argument
13562 /// dependent lookup.
13563 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13564 /// otherwise CallExpr is set to ExprError() and some non-success value
13565 /// is returned.
13566 Sema::ForRangeStatus
13567 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13568                                 SourceLocation RangeLoc,
13569                                 const DeclarationNameInfo &NameInfo,
13570                                 LookupResult &MemberLookup,
13571                                 OverloadCandidateSet *CandidateSet,
13572                                 Expr *Range, ExprResult *CallExpr) {
13573   Scope *S = nullptr;
13574 
13575   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13576   if (!MemberLookup.empty()) {
13577     ExprResult MemberRef =
13578         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13579                                  /*IsPtr=*/false, CXXScopeSpec(),
13580                                  /*TemplateKWLoc=*/SourceLocation(),
13581                                  /*FirstQualifierInScope=*/nullptr,
13582                                  MemberLookup,
13583                                  /*TemplateArgs=*/nullptr, S);
13584     if (MemberRef.isInvalid()) {
13585       *CallExpr = ExprError();
13586       return FRS_DiagnosticIssued;
13587     }
13588     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13589     if (CallExpr->isInvalid()) {
13590       *CallExpr = ExprError();
13591       return FRS_DiagnosticIssued;
13592     }
13593   } else {
13594     UnresolvedSet<0> FoundNames;
13595     UnresolvedLookupExpr *Fn =
13596       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13597                                    NestedNameSpecifierLoc(), NameInfo,
13598                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13599                                    FoundNames.begin(), FoundNames.end());
13600 
13601     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13602                                                     CandidateSet, CallExpr);
13603     if (CandidateSet->empty() || CandidateSetError) {
13604       *CallExpr = ExprError();
13605       return FRS_NoViableFunction;
13606     }
13607     OverloadCandidateSet::iterator Best;
13608     OverloadingResult OverloadResult =
13609         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13610 
13611     if (OverloadResult == OR_No_Viable_Function) {
13612       *CallExpr = ExprError();
13613       return FRS_NoViableFunction;
13614     }
13615     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13616                                          Loc, nullptr, CandidateSet, &Best,
13617                                          OverloadResult,
13618                                          /*AllowTypoCorrection=*/false);
13619     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13620       *CallExpr = ExprError();
13621       return FRS_DiagnosticIssued;
13622     }
13623   }
13624   return FRS_Success;
13625 }
13626 
13627 
13628 /// FixOverloadedFunctionReference - E is an expression that refers to
13629 /// a C++ overloaded function (possibly with some parentheses and
13630 /// perhaps a '&' around it). We have resolved the overloaded function
13631 /// to the function declaration Fn, so patch up the expression E to
13632 /// refer (possibly indirectly) to Fn. Returns the new expr.
13633 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13634                                            FunctionDecl *Fn) {
13635   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13636     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13637                                                    Found, Fn);
13638     if (SubExpr == PE->getSubExpr())
13639       return PE;
13640 
13641     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13642   }
13643 
13644   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13645     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13646                                                    Found, Fn);
13647     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13648                                SubExpr->getType()) &&
13649            "Implicit cast type cannot be determined from overload");
13650     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13651     if (SubExpr == ICE->getSubExpr())
13652       return ICE;
13653 
13654     return ImplicitCastExpr::Create(Context, ICE->getType(),
13655                                     ICE->getCastKind(),
13656                                     SubExpr, nullptr,
13657                                     ICE->getValueKind());
13658   }
13659 
13660   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13661     if (!GSE->isResultDependent()) {
13662       Expr *SubExpr =
13663           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13664       if (SubExpr == GSE->getResultExpr())
13665         return GSE;
13666 
13667       // Replace the resulting type information before rebuilding the generic
13668       // selection expression.
13669       ArrayRef<Expr *> A = GSE->getAssocExprs();
13670       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13671       unsigned ResultIdx = GSE->getResultIndex();
13672       AssocExprs[ResultIdx] = SubExpr;
13673 
13674       return new (Context) GenericSelectionExpr(
13675           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13676           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13677           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13678           ResultIdx);
13679     }
13680     // Rather than fall through to the unreachable, return the original generic
13681     // selection expression.
13682     return GSE;
13683   }
13684 
13685   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13686     assert(UnOp->getOpcode() == UO_AddrOf &&
13687            "Can only take the address of an overloaded function");
13688     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13689       if (Method->isStatic()) {
13690         // Do nothing: static member functions aren't any different
13691         // from non-member functions.
13692       } else {
13693         // Fix the subexpression, which really has to be an
13694         // UnresolvedLookupExpr holding an overloaded member function
13695         // or template.
13696         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13697                                                        Found, Fn);
13698         if (SubExpr == UnOp->getSubExpr())
13699           return UnOp;
13700 
13701         assert(isa<DeclRefExpr>(SubExpr)
13702                && "fixed to something other than a decl ref");
13703         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13704                && "fixed to a member ref with no nested name qualifier");
13705 
13706         // We have taken the address of a pointer to member
13707         // function. Perform the computation here so that we get the
13708         // appropriate pointer to member type.
13709         QualType ClassType
13710           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13711         QualType MemPtrType
13712           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13713         // Under the MS ABI, lock down the inheritance model now.
13714         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13715           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13716 
13717         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13718                                            VK_RValue, OK_Ordinary,
13719                                            UnOp->getOperatorLoc(), false);
13720       }
13721     }
13722     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13723                                                    Found, Fn);
13724     if (SubExpr == UnOp->getSubExpr())
13725       return UnOp;
13726 
13727     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13728                                      Context.getPointerType(SubExpr->getType()),
13729                                        VK_RValue, OK_Ordinary,
13730                                        UnOp->getOperatorLoc(), false);
13731   }
13732 
13733   // C++ [except.spec]p17:
13734   //   An exception-specification is considered to be needed when:
13735   //   - in an expression the function is the unique lookup result or the
13736   //     selected member of a set of overloaded functions
13737   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13738     ResolveExceptionSpec(E->getExprLoc(), FPT);
13739 
13740   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13741     // FIXME: avoid copy.
13742     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13743     if (ULE->hasExplicitTemplateArgs()) {
13744       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13745       TemplateArgs = &TemplateArgsBuffer;
13746     }
13747 
13748     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13749                                            ULE->getQualifierLoc(),
13750                                            ULE->getTemplateKeywordLoc(),
13751                                            Fn,
13752                                            /*enclosing*/ false, // FIXME?
13753                                            ULE->getNameLoc(),
13754                                            Fn->getType(),
13755                                            VK_LValue,
13756                                            Found.getDecl(),
13757                                            TemplateArgs);
13758     MarkDeclRefReferenced(DRE);
13759     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13760     return DRE;
13761   }
13762 
13763   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13764     // FIXME: avoid copy.
13765     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13766     if (MemExpr->hasExplicitTemplateArgs()) {
13767       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13768       TemplateArgs = &TemplateArgsBuffer;
13769     }
13770 
13771     Expr *Base;
13772 
13773     // If we're filling in a static method where we used to have an
13774     // implicit member access, rewrite to a simple decl ref.
13775     if (MemExpr->isImplicitAccess()) {
13776       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13777         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13778                                                MemExpr->getQualifierLoc(),
13779                                                MemExpr->getTemplateKeywordLoc(),
13780                                                Fn,
13781                                                /*enclosing*/ false,
13782                                                MemExpr->getMemberLoc(),
13783                                                Fn->getType(),
13784                                                VK_LValue,
13785                                                Found.getDecl(),
13786                                                TemplateArgs);
13787         MarkDeclRefReferenced(DRE);
13788         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13789         return DRE;
13790       } else {
13791         SourceLocation Loc = MemExpr->getMemberLoc();
13792         if (MemExpr->getQualifier())
13793           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13794         CheckCXXThisCapture(Loc);
13795         Base = new (Context) CXXThisExpr(Loc,
13796                                          MemExpr->getBaseType(),
13797                                          /*isImplicit=*/true);
13798       }
13799     } else
13800       Base = MemExpr->getBase();
13801 
13802     ExprValueKind valueKind;
13803     QualType type;
13804     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13805       valueKind = VK_LValue;
13806       type = Fn->getType();
13807     } else {
13808       valueKind = VK_RValue;
13809       type = Context.BoundMemberTy;
13810     }
13811 
13812     MemberExpr *ME = MemberExpr::Create(
13813         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13814         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13815         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13816         OK_Ordinary);
13817     ME->setHadMultipleCandidates(true);
13818     MarkMemberReferenced(ME);
13819     return ME;
13820   }
13821 
13822   llvm_unreachable("Invalid reference to overloaded function");
13823 }
13824 
13825 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13826                                                 DeclAccessPair Found,
13827                                                 FunctionDecl *Fn) {
13828   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13829 }
13830