1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43     return P->hasAttr<PassObjectSizeAttr>();
44   });
45 }
46 
47 /// A convenience routine for creating a decayed reference to a function.
48 static ExprResult
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50                       const Expr *Base, bool HadMultipleCandidates,
51                       SourceLocation Loc = SourceLocation(),
52                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54     return ExprError();
55   // If FoundDecl is different from Fn (such as if one is a template
56   // and the other a specialization), make sure DiagnoseUseOfDecl is
57   // called on both.
58   // FIXME: This would be more comprehensively addressed by modifying
59   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60   // being used.
61   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62     return ExprError();
63   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64     S.ResolveExceptionSpec(Loc, FPT);
65   DeclRefExpr *DRE = new (S.Context)
66       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE, Base);
71   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72                              CK_FunctionToPointerDecay);
73 }
74 
75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76                                  bool InOverloadResolution,
77                                  StandardConversionSequence &SCS,
78                                  bool CStyle,
79                                  bool AllowObjCWritebackConversion);
80 
81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82                                                  QualType &ToType,
83                                                  bool InOverloadResolution,
84                                                  StandardConversionSequence &SCS,
85                                                  bool CStyle);
86 static OverloadingResult
87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88                         UserDefinedConversionSequence& User,
89                         OverloadCandidateSet& Conversions,
90                         bool AllowExplicit,
91                         bool AllowObjCConversionOnExplicit);
92 
93 
94 static ImplicitConversionSequence::CompareKind
95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96                                    const StandardConversionSequence& SCS1,
97                                    const StandardConversionSequence& SCS2);
98 
99 static ImplicitConversionSequence::CompareKind
100 CompareQualificationConversions(Sema &S,
101                                 const StandardConversionSequence& SCS1,
102                                 const StandardConversionSequence& SCS2);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106                                 const StandardConversionSequence& SCS1,
107                                 const StandardConversionSequence& SCS2);
108 
109 /// GetConversionRank - Retrieve the implicit conversion rank
110 /// corresponding to the given implicit conversion kind.
111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112   static const ImplicitConversionRank
113     Rank[(int)ICK_Num_Conversion_Kinds] = {
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Promotion,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Conversion,
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_OCL_Scalar_Widening,
134     ICR_Complex_Real_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Writeback_Conversion,
138     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139                      // it was omitted by the patch that added
140                      // ICK_Zero_Event_Conversion
141     ICR_C_Conversion,
142     ICR_C_Conversion_Extension
143   };
144   return Rank[(int)Kind];
145 }
146 
147 /// GetImplicitConversionName - Return the name of this kind of
148 /// implicit conversion.
149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
151     "No conversion",
152     "Lvalue-to-rvalue",
153     "Array-to-pointer",
154     "Function-to-pointer",
155     "Function pointer conversion",
156     "Qualification",
157     "Integral promotion",
158     "Floating point promotion",
159     "Complex promotion",
160     "Integral conversion",
161     "Floating conversion",
162     "Complex conversion",
163     "Floating-integral conversion",
164     "Pointer conversion",
165     "Pointer-to-member conversion",
166     "Boolean conversion",
167     "Compatible-types conversion",
168     "Derived-to-base conversion",
169     "Vector conversion",
170     "Vector splat",
171     "Complex-real conversion",
172     "Block Pointer conversion",
173     "Transparent Union Conversion",
174     "Writeback conversion",
175     "OpenCL Zero Event Conversion",
176     "C specific type conversion",
177     "Incompatible pointer conversion"
178   };
179   return Name[Kind];
180 }
181 
182 /// StandardConversionSequence - Set the standard conversion
183 /// sequence to the identity conversion.
184 void StandardConversionSequence::setAsIdentityConversion() {
185   First = ICK_Identity;
186   Second = ICK_Identity;
187   Third = ICK_Identity;
188   DeprecatedStringLiteralToCharPtr = false;
189   QualificationIncludesObjCLifetime = false;
190   ReferenceBinding = false;
191   DirectBinding = false;
192   IsLvalueReference = true;
193   BindsToFunctionLvalue = false;
194   BindsToRvalue = false;
195   BindsImplicitObjectArgumentWithoutRefQualifier = false;
196   ObjCLifetimeConversionBinding = false;
197   CopyConstructor = nullptr;
198 }
199 
200 /// getRank - Retrieve the rank of this standard conversion sequence
201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202 /// implicit conversions.
203 ImplicitConversionRank StandardConversionSequence::getRank() const {
204   ImplicitConversionRank Rank = ICR_Exact_Match;
205   if  (GetConversionRank(First) > Rank)
206     Rank = GetConversionRank(First);
207   if  (GetConversionRank(Second) > Rank)
208     Rank = GetConversionRank(Second);
209   if  (GetConversionRank(Third) > Rank)
210     Rank = GetConversionRank(Third);
211   return Rank;
212 }
213 
214 /// isPointerConversionToBool - Determines whether this conversion is
215 /// a conversion of a pointer or pointer-to-member to bool. This is
216 /// used as part of the ranking of standard conversion sequences
217 /// (C++ 13.3.3.2p4).
218 bool StandardConversionSequence::isPointerConversionToBool() const {
219   // Note that FromType has not necessarily been transformed by the
220   // array-to-pointer or function-to-pointer implicit conversions, so
221   // check for their presence as well as checking whether FromType is
222   // a pointer.
223   if (getToType(1)->isBooleanType() &&
224       (getFromType()->isPointerType() ||
225        getFromType()->isMemberPointerType() ||
226        getFromType()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231 
232   return false;
233 }
234 
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244 
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250 
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254 
255   return false;
256 }
257 
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262     switch (ICE->getCastKind()) {
263     case CK_NoOp:
264     case CK_IntegralCast:
265     case CK_IntegralToBoolean:
266     case CK_IntegralToFloating:
267     case CK_BooleanToSignedIntegral:
268     case CK_FloatingToIntegral:
269     case CK_FloatingToBoolean:
270     case CK_FloatingCast:
271       Converted = ICE->getSubExpr();
272       continue;
273 
274     default:
275       return Converted;
276     }
277   }
278 
279   return Converted;
280 }
281 
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
284 ///
285 /// \param Ctx  The AST context.
286 /// \param Converted  The result of applying this standard conversion sequence.
287 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288 ///        value of the expression prior to the narrowing conversion.
289 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290 ///        type of the expression prior to the narrowing conversion.
291 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
292 ///        from floating point types to integral types should be ignored.
293 NarrowingKind StandardConversionSequence::getNarrowingKind(
294     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
295     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
296   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297 
298   // C++11 [dcl.init.list]p7:
299   //   A narrowing conversion is an implicit conversion ...
300   QualType FromType = getToType(0);
301   QualType ToType = getToType(1);
302 
303   // A conversion to an enumeration type is narrowing if the conversion to
304   // the underlying type is narrowing. This only arises for expressions of
305   // the form 'Enum{init}'.
306   if (auto *ET = ToType->getAs<EnumType>())
307     ToType = ET->getDecl()->getIntegerType();
308 
309   switch (Second) {
310   // 'bool' is an integral type; dispatch to the right place to handle it.
311   case ICK_Boolean_Conversion:
312     if (FromType->isRealFloatingType())
313       goto FloatingIntegralConversion;
314     if (FromType->isIntegralOrUnscopedEnumerationType())
315       goto IntegralConversion;
316     // Boolean conversions can be from pointers and pointers to members
317     // [conv.bool], and those aren't considered narrowing conversions.
318     return NK_Not_Narrowing;
319 
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327   FloatingIntegralConversion:
328     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329       return NK_Type_Narrowing;
330     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
331                ToType->isRealFloatingType()) {
332       if (IgnoreFloatToIntegralConversion)
333         return NK_Not_Narrowing;
334       llvm::APSInt IntConstantValue;
335       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
336       assert(Initializer && "Unknown conversion expression");
337 
338       // If it's value-dependent, we can't tell whether it's narrowing.
339       if (Initializer->isValueDependent())
340         return NK_Dependent_Narrowing;
341 
342       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
343         // Convert the integer to the floating type.
344         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
345         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
346                                 llvm::APFloat::rmNearestTiesToEven);
347         // And back.
348         llvm::APSInt ConvertedValue = IntConstantValue;
349         bool ignored;
350         Result.convertToInteger(ConvertedValue,
351                                 llvm::APFloat::rmTowardZero, &ignored);
352         // If the resulting value is different, this was a narrowing conversion.
353         if (IntConstantValue != ConvertedValue) {
354           ConstantValue = APValue(IntConstantValue);
355           ConstantType = Initializer->getType();
356           return NK_Constant_Narrowing;
357         }
358       } else {
359         // Variables are always narrowings.
360         return NK_Variable_Narrowing;
361       }
362     }
363     return NK_Not_Narrowing;
364 
365   // -- from long double to double or float, or from double to float, except
366   //    where the source is a constant expression and the actual value after
367   //    conversion is within the range of values that can be represented (even
368   //    if it cannot be represented exactly), or
369   case ICK_Floating_Conversion:
370     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
371         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
372       // FromType is larger than ToType.
373       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
374 
375       // If it's value-dependent, we can't tell whether it's narrowing.
376       if (Initializer->isValueDependent())
377         return NK_Dependent_Narrowing;
378 
379       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
380         // Constant!
381         assert(ConstantValue.isFloat());
382         llvm::APFloat FloatVal = ConstantValue.getFloat();
383         // Convert the source value into the target type.
384         bool ignored;
385         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
386           Ctx.getFloatTypeSemantics(ToType),
387           llvm::APFloat::rmNearestTiesToEven, &ignored);
388         // If there was no overflow, the source value is within the range of
389         // values that can be represented.
390         if (ConvertStatus & llvm::APFloat::opOverflow) {
391           ConstantType = Initializer->getType();
392           return NK_Constant_Narrowing;
393         }
394       } else {
395         return NK_Variable_Narrowing;
396       }
397     }
398     return NK_Not_Narrowing;
399 
400   // -- from an integer type or unscoped enumeration type to an integer type
401   //    that cannot represent all the values of the original type, except where
402   //    the source is a constant expression and the actual value after
403   //    conversion will fit into the target type and will produce the original
404   //    value when converted back to the original type.
405   case ICK_Integral_Conversion:
406   IntegralConversion: {
407     assert(FromType->isIntegralOrUnscopedEnumerationType());
408     assert(ToType->isIntegralOrUnscopedEnumerationType());
409     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
410     const unsigned FromWidth = Ctx.getIntWidth(FromType);
411     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
412     const unsigned ToWidth = Ctx.getIntWidth(ToType);
413 
414     if (FromWidth > ToWidth ||
415         (FromWidth == ToWidth && FromSigned != ToSigned) ||
416         (FromSigned && !ToSigned)) {
417       // Not all values of FromType can be represented in ToType.
418       llvm::APSInt InitializerValue;
419       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
420 
421       // If it's value-dependent, we can't tell whether it's narrowing.
422       if (Initializer->isValueDependent())
423         return NK_Dependent_Narrowing;
424 
425       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
426         // Such conversions on variables are always narrowing.
427         return NK_Variable_Narrowing;
428       }
429       bool Narrowing = false;
430       if (FromWidth < ToWidth) {
431         // Negative -> unsigned is narrowing. Otherwise, more bits is never
432         // narrowing.
433         if (InitializerValue.isSigned() && InitializerValue.isNegative())
434           Narrowing = true;
435       } else {
436         // Add a bit to the InitializerValue so we don't have to worry about
437         // signed vs. unsigned comparisons.
438         InitializerValue = InitializerValue.extend(
439           InitializerValue.getBitWidth() + 1);
440         // Convert the initializer to and from the target width and signed-ness.
441         llvm::APSInt ConvertedValue = InitializerValue;
442         ConvertedValue = ConvertedValue.trunc(ToWidth);
443         ConvertedValue.setIsSigned(ToSigned);
444         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
445         ConvertedValue.setIsSigned(InitializerValue.isSigned());
446         // If the result is different, this was a narrowing conversion.
447         if (ConvertedValue != InitializerValue)
448           Narrowing = true;
449       }
450       if (Narrowing) {
451         ConstantType = Initializer->getType();
452         ConstantValue = APValue(InitializerValue);
453         return NK_Constant_Narrowing;
454       }
455     }
456     return NK_Not_Narrowing;
457   }
458 
459   default:
460     // Other kinds of conversions are not narrowings.
461     return NK_Not_Narrowing;
462   }
463 }
464 
465 /// dump - Print this standard conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
468   raw_ostream &OS = llvm::errs();
469   bool PrintedSomething = false;
470   if (First != ICK_Identity) {
471     OS << GetImplicitConversionName(First);
472     PrintedSomething = true;
473   }
474 
475   if (Second != ICK_Identity) {
476     if (PrintedSomething) {
477       OS << " -> ";
478     }
479     OS << GetImplicitConversionName(Second);
480 
481     if (CopyConstructor) {
482       OS << " (by copy constructor)";
483     } else if (DirectBinding) {
484       OS << " (direct reference binding)";
485     } else if (ReferenceBinding) {
486       OS << " (reference binding)";
487     }
488     PrintedSomething = true;
489   }
490 
491   if (Third != ICK_Identity) {
492     if (PrintedSomething) {
493       OS << " -> ";
494     }
495     OS << GetImplicitConversionName(Third);
496     PrintedSomething = true;
497   }
498 
499   if (!PrintedSomething) {
500     OS << "No conversions required";
501   }
502 }
503 
504 /// dump - Print this user-defined conversion sequence to standard
505 /// error. Useful for debugging overloading issues.
506 void UserDefinedConversionSequence::dump() const {
507   raw_ostream &OS = llvm::errs();
508   if (Before.First || Before.Second || Before.Third) {
509     Before.dump();
510     OS << " -> ";
511   }
512   if (ConversionFunction)
513     OS << '\'' << *ConversionFunction << '\'';
514   else
515     OS << "aggregate initialization";
516   if (After.First || After.Second || After.Third) {
517     OS << " -> ";
518     After.dump();
519   }
520 }
521 
522 /// dump - Print this implicit conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void ImplicitConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (isStdInitializerListElement())
527     OS << "Worst std::initializer_list element conversion: ";
528   switch (ConversionKind) {
529   case StandardConversion:
530     OS << "Standard conversion: ";
531     Standard.dump();
532     break;
533   case UserDefinedConversion:
534     OS << "User-defined conversion: ";
535     UserDefined.dump();
536     break;
537   case EllipsisConversion:
538     OS << "Ellipsis conversion";
539     break;
540   case AmbiguousConversion:
541     OS << "Ambiguous conversion";
542     break;
543   case BadConversion:
544     OS << "Bad conversion";
545     break;
546   }
547 
548   OS << "\n";
549 }
550 
551 void AmbiguousConversionSequence::construct() {
552   new (&conversions()) ConversionSet();
553 }
554 
555 void AmbiguousConversionSequence::destruct() {
556   conversions().~ConversionSet();
557 }
558 
559 void
560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
561   FromTypePtr = O.FromTypePtr;
562   ToTypePtr = O.ToTypePtr;
563   new (&conversions()) ConversionSet(O.conversions());
564 }
565 
566 namespace {
567   // Structure used by DeductionFailureInfo to store
568   // template argument information.
569   struct DFIArguments {
570     TemplateArgument FirstArg;
571     TemplateArgument SecondArg;
572   };
573   // Structure used by DeductionFailureInfo to store
574   // template parameter and template argument information.
575   struct DFIParamWithArguments : DFIArguments {
576     TemplateParameter Param;
577   };
578   // Structure used by DeductionFailureInfo to store template argument
579   // information and the index of the problematic call argument.
580   struct DFIDeducedMismatchArgs : DFIArguments {
581     TemplateArgumentList *TemplateArgs;
582     unsigned CallArgIndex;
583   };
584 }
585 
586 /// Convert from Sema's representation of template deduction information
587 /// to the form used in overload-candidate information.
588 DeductionFailureInfo
589 clang::MakeDeductionFailureInfo(ASTContext &Context,
590                                 Sema::TemplateDeductionResult TDK,
591                                 TemplateDeductionInfo &Info) {
592   DeductionFailureInfo Result;
593   Result.Result = static_cast<unsigned>(TDK);
594   Result.HasDiagnostic = false;
595   switch (TDK) {
596   case Sema::TDK_Invalid:
597   case Sema::TDK_InstantiationDepth:
598   case Sema::TDK_TooManyArguments:
599   case Sema::TDK_TooFewArguments:
600   case Sema::TDK_MiscellaneousDeductionFailure:
601   case Sema::TDK_CUDATargetMismatch:
602     Result.Data = nullptr;
603     break;
604 
605   case Sema::TDK_Incomplete:
606   case Sema::TDK_InvalidExplicitArguments:
607     Result.Data = Info.Param.getOpaqueValue();
608     break;
609 
610   case Sema::TDK_DeducedMismatch:
611   case Sema::TDK_DeducedMismatchNested: {
612     // FIXME: Should allocate from normal heap so that we can free this later.
613     auto *Saved = new (Context) DFIDeducedMismatchArgs;
614     Saved->FirstArg = Info.FirstArg;
615     Saved->SecondArg = Info.SecondArg;
616     Saved->TemplateArgs = Info.take();
617     Saved->CallArgIndex = Info.CallArgIndex;
618     Result.Data = Saved;
619     break;
620   }
621 
622   case Sema::TDK_NonDeducedMismatch: {
623     // FIXME: Should allocate from normal heap so that we can free this later.
624     DFIArguments *Saved = new (Context) DFIArguments;
625     Saved->FirstArg = Info.FirstArg;
626     Saved->SecondArg = Info.SecondArg;
627     Result.Data = Saved;
628     break;
629   }
630 
631   case Sema::TDK_IncompletePack:
632     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
633   case Sema::TDK_Inconsistent:
634   case Sema::TDK_Underqualified: {
635     // FIXME: Should allocate from normal heap so that we can free this later.
636     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
637     Saved->Param = Info.Param;
638     Saved->FirstArg = Info.FirstArg;
639     Saved->SecondArg = Info.SecondArg;
640     Result.Data = Saved;
641     break;
642   }
643 
644   case Sema::TDK_SubstitutionFailure:
645     Result.Data = Info.take();
646     if (Info.hasSFINAEDiagnostic()) {
647       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
648           SourceLocation(), PartialDiagnostic::NullDiagnostic());
649       Info.takeSFINAEDiagnostic(*Diag);
650       Result.HasDiagnostic = true;
651     }
652     break;
653 
654   case Sema::TDK_Success:
655   case Sema::TDK_NonDependentConversionFailure:
656     llvm_unreachable("not a deduction failure");
657   }
658 
659   return Result;
660 }
661 
662 void DeductionFailureInfo::Destroy() {
663   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
664   case Sema::TDK_Success:
665   case Sema::TDK_Invalid:
666   case Sema::TDK_InstantiationDepth:
667   case Sema::TDK_Incomplete:
668   case Sema::TDK_TooManyArguments:
669   case Sema::TDK_TooFewArguments:
670   case Sema::TDK_InvalidExplicitArguments:
671   case Sema::TDK_CUDATargetMismatch:
672   case Sema::TDK_NonDependentConversionFailure:
673     break;
674 
675   case Sema::TDK_IncompletePack:
676   case Sema::TDK_Inconsistent:
677   case Sema::TDK_Underqualified:
678   case Sema::TDK_DeducedMismatch:
679   case Sema::TDK_DeducedMismatchNested:
680   case Sema::TDK_NonDeducedMismatch:
681     // FIXME: Destroy the data?
682     Data = nullptr;
683     break;
684 
685   case Sema::TDK_SubstitutionFailure:
686     // FIXME: Destroy the template argument list?
687     Data = nullptr;
688     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
689       Diag->~PartialDiagnosticAt();
690       HasDiagnostic = false;
691     }
692     break;
693 
694   // Unhandled
695   case Sema::TDK_MiscellaneousDeductionFailure:
696     break;
697   }
698 }
699 
700 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
701   if (HasDiagnostic)
702     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
703   return nullptr;
704 }
705 
706 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
707   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
708   case Sema::TDK_Success:
709   case Sema::TDK_Invalid:
710   case Sema::TDK_InstantiationDepth:
711   case Sema::TDK_TooManyArguments:
712   case Sema::TDK_TooFewArguments:
713   case Sema::TDK_SubstitutionFailure:
714   case Sema::TDK_DeducedMismatch:
715   case Sema::TDK_DeducedMismatchNested:
716   case Sema::TDK_NonDeducedMismatch:
717   case Sema::TDK_CUDATargetMismatch:
718   case Sema::TDK_NonDependentConversionFailure:
719     return TemplateParameter();
720 
721   case Sema::TDK_Incomplete:
722   case Sema::TDK_InvalidExplicitArguments:
723     return TemplateParameter::getFromOpaqueValue(Data);
724 
725   case Sema::TDK_IncompletePack:
726   case Sema::TDK_Inconsistent:
727   case Sema::TDK_Underqualified:
728     return static_cast<DFIParamWithArguments*>(Data)->Param;
729 
730   // Unhandled
731   case Sema::TDK_MiscellaneousDeductionFailure:
732     break;
733   }
734 
735   return TemplateParameter();
736 }
737 
738 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
739   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
740   case Sema::TDK_Success:
741   case Sema::TDK_Invalid:
742   case Sema::TDK_InstantiationDepth:
743   case Sema::TDK_TooManyArguments:
744   case Sema::TDK_TooFewArguments:
745   case Sema::TDK_Incomplete:
746   case Sema::TDK_IncompletePack:
747   case Sema::TDK_InvalidExplicitArguments:
748   case Sema::TDK_Inconsistent:
749   case Sema::TDK_Underqualified:
750   case Sema::TDK_NonDeducedMismatch:
751   case Sema::TDK_CUDATargetMismatch:
752   case Sema::TDK_NonDependentConversionFailure:
753     return nullptr;
754 
755   case Sema::TDK_DeducedMismatch:
756   case Sema::TDK_DeducedMismatchNested:
757     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
758 
759   case Sema::TDK_SubstitutionFailure:
760     return static_cast<TemplateArgumentList*>(Data);
761 
762   // Unhandled
763   case Sema::TDK_MiscellaneousDeductionFailure:
764     break;
765   }
766 
767   return nullptr;
768 }
769 
770 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
771   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
772   case Sema::TDK_Success:
773   case Sema::TDK_Invalid:
774   case Sema::TDK_InstantiationDepth:
775   case Sema::TDK_Incomplete:
776   case Sema::TDK_TooManyArguments:
777   case Sema::TDK_TooFewArguments:
778   case Sema::TDK_InvalidExplicitArguments:
779   case Sema::TDK_SubstitutionFailure:
780   case Sema::TDK_CUDATargetMismatch:
781   case Sema::TDK_NonDependentConversionFailure:
782     return nullptr;
783 
784   case Sema::TDK_IncompletePack:
785   case Sema::TDK_Inconsistent:
786   case Sema::TDK_Underqualified:
787   case Sema::TDK_DeducedMismatch:
788   case Sema::TDK_DeducedMismatchNested:
789   case Sema::TDK_NonDeducedMismatch:
790     return &static_cast<DFIArguments*>(Data)->FirstArg;
791 
792   // Unhandled
793   case Sema::TDK_MiscellaneousDeductionFailure:
794     break;
795   }
796 
797   return nullptr;
798 }
799 
800 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
801   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
802   case Sema::TDK_Success:
803   case Sema::TDK_Invalid:
804   case Sema::TDK_InstantiationDepth:
805   case Sema::TDK_Incomplete:
806   case Sema::TDK_IncompletePack:
807   case Sema::TDK_TooManyArguments:
808   case Sema::TDK_TooFewArguments:
809   case Sema::TDK_InvalidExplicitArguments:
810   case Sema::TDK_SubstitutionFailure:
811   case Sema::TDK_CUDATargetMismatch:
812   case Sema::TDK_NonDependentConversionFailure:
813     return nullptr;
814 
815   case Sema::TDK_Inconsistent:
816   case Sema::TDK_Underqualified:
817   case Sema::TDK_DeducedMismatch:
818   case Sema::TDK_DeducedMismatchNested:
819   case Sema::TDK_NonDeducedMismatch:
820     return &static_cast<DFIArguments*>(Data)->SecondArg;
821 
822   // Unhandled
823   case Sema::TDK_MiscellaneousDeductionFailure:
824     break;
825   }
826 
827   return nullptr;
828 }
829 
830 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
831   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
832   case Sema::TDK_DeducedMismatch:
833   case Sema::TDK_DeducedMismatchNested:
834     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
835 
836   default:
837     return llvm::None;
838   }
839 }
840 
841 void OverloadCandidateSet::destroyCandidates() {
842   for (iterator i = begin(), e = end(); i != e; ++i) {
843     for (auto &C : i->Conversions)
844       C.~ImplicitConversionSequence();
845     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
846       i->DeductionFailure.Destroy();
847   }
848 }
849 
850 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
851   destroyCandidates();
852   SlabAllocator.Reset();
853   NumInlineBytesUsed = 0;
854   Candidates.clear();
855   Functions.clear();
856   Kind = CSK;
857 }
858 
859 namespace {
860   class UnbridgedCastsSet {
861     struct Entry {
862       Expr **Addr;
863       Expr *Saved;
864     };
865     SmallVector<Entry, 2> Entries;
866 
867   public:
868     void save(Sema &S, Expr *&E) {
869       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
870       Entry entry = { &E, E };
871       Entries.push_back(entry);
872       E = S.stripARCUnbridgedCast(E);
873     }
874 
875     void restore() {
876       for (SmallVectorImpl<Entry>::iterator
877              i = Entries.begin(), e = Entries.end(); i != e; ++i)
878         *i->Addr = i->Saved;
879     }
880   };
881 }
882 
883 /// checkPlaceholderForOverload - Do any interesting placeholder-like
884 /// preprocessing on the given expression.
885 ///
886 /// \param unbridgedCasts a collection to which to add unbridged casts;
887 ///   without this, they will be immediately diagnosed as errors
888 ///
889 /// Return true on unrecoverable error.
890 static bool
891 checkPlaceholderForOverload(Sema &S, Expr *&E,
892                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
893   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
894     // We can't handle overloaded expressions here because overload
895     // resolution might reasonably tweak them.
896     if (placeholder->getKind() == BuiltinType::Overload) return false;
897 
898     // If the context potentially accepts unbridged ARC casts, strip
899     // the unbridged cast and add it to the collection for later restoration.
900     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
901         unbridgedCasts) {
902       unbridgedCasts->save(S, E);
903       return false;
904     }
905 
906     // Go ahead and check everything else.
907     ExprResult result = S.CheckPlaceholderExpr(E);
908     if (result.isInvalid())
909       return true;
910 
911     E = result.get();
912     return false;
913   }
914 
915   // Nothing to do.
916   return false;
917 }
918 
919 /// checkArgPlaceholdersForOverload - Check a set of call operands for
920 /// placeholders.
921 static bool checkArgPlaceholdersForOverload(Sema &S,
922                                             MultiExprArg Args,
923                                             UnbridgedCastsSet &unbridged) {
924   for (unsigned i = 0, e = Args.size(); i != e; ++i)
925     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
926       return true;
927 
928   return false;
929 }
930 
931 /// Determine whether the given New declaration is an overload of the
932 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
933 /// New and Old cannot be overloaded, e.g., if New has the same signature as
934 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
935 /// functions (or function templates) at all. When it does return Ovl_Match or
936 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
937 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
938 /// declaration.
939 ///
940 /// Example: Given the following input:
941 ///
942 ///   void f(int, float); // #1
943 ///   void f(int, int); // #2
944 ///   int f(int, int); // #3
945 ///
946 /// When we process #1, there is no previous declaration of "f", so IsOverload
947 /// will not be used.
948 ///
949 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
950 /// the parameter types, we see that #1 and #2 are overloaded (since they have
951 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
952 /// unchanged.
953 ///
954 /// When we process #3, Old is an overload set containing #1 and #2. We compare
955 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
956 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
957 /// functions are not part of the signature), IsOverload returns Ovl_Match and
958 /// MatchedDecl will be set to point to the FunctionDecl for #2.
959 ///
960 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
961 /// by a using declaration. The rules for whether to hide shadow declarations
962 /// ignore some properties which otherwise figure into a function template's
963 /// signature.
964 Sema::OverloadKind
965 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
966                     NamedDecl *&Match, bool NewIsUsingDecl) {
967   for (LookupResult::iterator I = Old.begin(), E = Old.end();
968          I != E; ++I) {
969     NamedDecl *OldD = *I;
970 
971     bool OldIsUsingDecl = false;
972     if (isa<UsingShadowDecl>(OldD)) {
973       OldIsUsingDecl = true;
974 
975       // We can always introduce two using declarations into the same
976       // context, even if they have identical signatures.
977       if (NewIsUsingDecl) continue;
978 
979       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
980     }
981 
982     // A using-declaration does not conflict with another declaration
983     // if one of them is hidden.
984     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
985       continue;
986 
987     // If either declaration was introduced by a using declaration,
988     // we'll need to use slightly different rules for matching.
989     // Essentially, these rules are the normal rules, except that
990     // function templates hide function templates with different
991     // return types or template parameter lists.
992     bool UseMemberUsingDeclRules =
993       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
994       !New->getFriendObjectKind();
995 
996     if (FunctionDecl *OldF = OldD->getAsFunction()) {
997       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
998         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
999           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1000           continue;
1001         }
1002 
1003         if (!isa<FunctionTemplateDecl>(OldD) &&
1004             !shouldLinkPossiblyHiddenDecl(*I, New))
1005           continue;
1006 
1007         Match = *I;
1008         return Ovl_Match;
1009       }
1010 
1011       // Builtins that have custom typechecking or have a reference should
1012       // not be overloadable or redeclarable.
1013       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1014         Match = *I;
1015         return Ovl_NonFunction;
1016       }
1017     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1018       // We can overload with these, which can show up when doing
1019       // redeclaration checks for UsingDecls.
1020       assert(Old.getLookupKind() == LookupUsingDeclName);
1021     } else if (isa<TagDecl>(OldD)) {
1022       // We can always overload with tags by hiding them.
1023     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1024       // Optimistically assume that an unresolved using decl will
1025       // overload; if it doesn't, we'll have to diagnose during
1026       // template instantiation.
1027       //
1028       // Exception: if the scope is dependent and this is not a class
1029       // member, the using declaration can only introduce an enumerator.
1030       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1031         Match = *I;
1032         return Ovl_NonFunction;
1033       }
1034     } else {
1035       // (C++ 13p1):
1036       //   Only function declarations can be overloaded; object and type
1037       //   declarations cannot be overloaded.
1038       Match = *I;
1039       return Ovl_NonFunction;
1040     }
1041   }
1042 
1043   // C++ [temp.friend]p1:
1044   //   For a friend function declaration that is not a template declaration:
1045   //    -- if the name of the friend is a qualified or unqualified template-id,
1046   //       [...], otherwise
1047   //    -- if the name of the friend is a qualified-id and a matching
1048   //       non-template function is found in the specified class or namespace,
1049   //       the friend declaration refers to that function, otherwise,
1050   //    -- if the name of the friend is a qualified-id and a matching function
1051   //       template is found in the specified class or namespace, the friend
1052   //       declaration refers to the deduced specialization of that function
1053   //       template, otherwise
1054   //    -- the name shall be an unqualified-id [...]
1055   // If we get here for a qualified friend declaration, we've just reached the
1056   // third bullet. If the type of the friend is dependent, skip this lookup
1057   // until instantiation.
1058   if (New->getFriendObjectKind() && New->getQualifier() &&
1059       !New->getDescribedFunctionTemplate() &&
1060       !New->getDependentSpecializationInfo() &&
1061       !New->getType()->isDependentType()) {
1062     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1063     TemplateSpecResult.addAllDecls(Old);
1064     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1065                                             /*QualifiedFriend*/true)) {
1066       New->setInvalidDecl();
1067       return Ovl_Overload;
1068     }
1069 
1070     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1071     return Ovl_Match;
1072   }
1073 
1074   return Ovl_Overload;
1075 }
1076 
1077 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1078                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1079   // C++ [basic.start.main]p2: This function shall not be overloaded.
1080   if (New->isMain())
1081     return false;
1082 
1083   // MSVCRT user defined entry points cannot be overloaded.
1084   if (New->isMSVCRTEntryPoint())
1085     return false;
1086 
1087   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1088   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1089 
1090   // C++ [temp.fct]p2:
1091   //   A function template can be overloaded with other function templates
1092   //   and with normal (non-template) functions.
1093   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1094     return true;
1095 
1096   // Is the function New an overload of the function Old?
1097   QualType OldQType = Context.getCanonicalType(Old->getType());
1098   QualType NewQType = Context.getCanonicalType(New->getType());
1099 
1100   // Compare the signatures (C++ 1.3.10) of the two functions to
1101   // determine whether they are overloads. If we find any mismatch
1102   // in the signature, they are overloads.
1103 
1104   // If either of these functions is a K&R-style function (no
1105   // prototype), then we consider them to have matching signatures.
1106   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1107       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1108     return false;
1109 
1110   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1111   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1112 
1113   // The signature of a function includes the types of its
1114   // parameters (C++ 1.3.10), which includes the presence or absence
1115   // of the ellipsis; see C++ DR 357).
1116   if (OldQType != NewQType &&
1117       (OldType->getNumParams() != NewType->getNumParams() ||
1118        OldType->isVariadic() != NewType->isVariadic() ||
1119        !FunctionParamTypesAreEqual(OldType, NewType)))
1120     return true;
1121 
1122   // C++ [temp.over.link]p4:
1123   //   The signature of a function template consists of its function
1124   //   signature, its return type and its template parameter list. The names
1125   //   of the template parameters are significant only for establishing the
1126   //   relationship between the template parameters and the rest of the
1127   //   signature.
1128   //
1129   // We check the return type and template parameter lists for function
1130   // templates first; the remaining checks follow.
1131   //
1132   // However, we don't consider either of these when deciding whether
1133   // a member introduced by a shadow declaration is hidden.
1134   if (!UseMemberUsingDeclRules && NewTemplate &&
1135       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1136                                        OldTemplate->getTemplateParameters(),
1137                                        false, TPL_TemplateMatch) ||
1138        !Context.hasSameType(Old->getDeclaredReturnType(),
1139                             New->getDeclaredReturnType())))
1140     return true;
1141 
1142   // If the function is a class member, its signature includes the
1143   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1144   //
1145   // As part of this, also check whether one of the member functions
1146   // is static, in which case they are not overloads (C++
1147   // 13.1p2). While not part of the definition of the signature,
1148   // this check is important to determine whether these functions
1149   // can be overloaded.
1150   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1151   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1152   if (OldMethod && NewMethod &&
1153       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1154     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1155       if (!UseMemberUsingDeclRules &&
1156           (OldMethod->getRefQualifier() == RQ_None ||
1157            NewMethod->getRefQualifier() == RQ_None)) {
1158         // C++0x [over.load]p2:
1159         //   - Member function declarations with the same name and the same
1160         //     parameter-type-list as well as member function template
1161         //     declarations with the same name, the same parameter-type-list, and
1162         //     the same template parameter lists cannot be overloaded if any of
1163         //     them, but not all, have a ref-qualifier (8.3.5).
1164         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1165           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1166         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1167       }
1168       return true;
1169     }
1170 
1171     // We may not have applied the implicit const for a constexpr member
1172     // function yet (because we haven't yet resolved whether this is a static
1173     // or non-static member function). Add it now, on the assumption that this
1174     // is a redeclaration of OldMethod.
1175     auto OldQuals = OldMethod->getMethodQualifiers();
1176     auto NewQuals = NewMethod->getMethodQualifiers();
1177     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1178         !isa<CXXConstructorDecl>(NewMethod))
1179       NewQuals.addConst();
1180     // We do not allow overloading based off of '__restrict'.
1181     OldQuals.removeRestrict();
1182     NewQuals.removeRestrict();
1183     if (OldQuals != NewQuals)
1184       return true;
1185   }
1186 
1187   // Though pass_object_size is placed on parameters and takes an argument, we
1188   // consider it to be a function-level modifier for the sake of function
1189   // identity. Either the function has one or more parameters with
1190   // pass_object_size or it doesn't.
1191   if (functionHasPassObjectSizeParams(New) !=
1192       functionHasPassObjectSizeParams(Old))
1193     return true;
1194 
1195   // enable_if attributes are an order-sensitive part of the signature.
1196   for (specific_attr_iterator<EnableIfAttr>
1197          NewI = New->specific_attr_begin<EnableIfAttr>(),
1198          NewE = New->specific_attr_end<EnableIfAttr>(),
1199          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1200          OldE = Old->specific_attr_end<EnableIfAttr>();
1201        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1202     if (NewI == NewE || OldI == OldE)
1203       return true;
1204     llvm::FoldingSetNodeID NewID, OldID;
1205     NewI->getCond()->Profile(NewID, Context, true);
1206     OldI->getCond()->Profile(OldID, Context, true);
1207     if (NewID != OldID)
1208       return true;
1209   }
1210 
1211   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1212     // Don't allow overloading of destructors.  (In theory we could, but it
1213     // would be a giant change to clang.)
1214     if (isa<CXXDestructorDecl>(New))
1215       return false;
1216 
1217     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1218                        OldTarget = IdentifyCUDATarget(Old);
1219     if (NewTarget == CFT_InvalidTarget)
1220       return false;
1221 
1222     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1223 
1224     // Allow overloading of functions with same signature and different CUDA
1225     // target attributes.
1226     return NewTarget != OldTarget;
1227   }
1228 
1229   // The signatures match; this is not an overload.
1230   return false;
1231 }
1232 
1233 /// Tries a user-defined conversion from From to ToType.
1234 ///
1235 /// Produces an implicit conversion sequence for when a standard conversion
1236 /// is not an option. See TryImplicitConversion for more information.
1237 static ImplicitConversionSequence
1238 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1239                          bool SuppressUserConversions,
1240                          bool AllowExplicit,
1241                          bool InOverloadResolution,
1242                          bool CStyle,
1243                          bool AllowObjCWritebackConversion,
1244                          bool AllowObjCConversionOnExplicit) {
1245   ImplicitConversionSequence ICS;
1246 
1247   if (SuppressUserConversions) {
1248     // We're not in the case above, so there is no conversion that
1249     // we can perform.
1250     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1251     return ICS;
1252   }
1253 
1254   // Attempt user-defined conversion.
1255   OverloadCandidateSet Conversions(From->getExprLoc(),
1256                                    OverloadCandidateSet::CSK_Normal);
1257   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1258                                   Conversions, AllowExplicit,
1259                                   AllowObjCConversionOnExplicit)) {
1260   case OR_Success:
1261   case OR_Deleted:
1262     ICS.setUserDefined();
1263     // C++ [over.ics.user]p4:
1264     //   A conversion of an expression of class type to the same class
1265     //   type is given Exact Match rank, and a conversion of an
1266     //   expression of class type to a base class of that type is
1267     //   given Conversion rank, in spite of the fact that a copy
1268     //   constructor (i.e., a user-defined conversion function) is
1269     //   called for those cases.
1270     if (CXXConstructorDecl *Constructor
1271           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1272       QualType FromCanon
1273         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1274       QualType ToCanon
1275         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1276       if (Constructor->isCopyConstructor() &&
1277           (FromCanon == ToCanon ||
1278            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1279         // Turn this into a "standard" conversion sequence, so that it
1280         // gets ranked with standard conversion sequences.
1281         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1282         ICS.setStandard();
1283         ICS.Standard.setAsIdentityConversion();
1284         ICS.Standard.setFromType(From->getType());
1285         ICS.Standard.setAllToTypes(ToType);
1286         ICS.Standard.CopyConstructor = Constructor;
1287         ICS.Standard.FoundCopyConstructor = Found;
1288         if (ToCanon != FromCanon)
1289           ICS.Standard.Second = ICK_Derived_To_Base;
1290       }
1291     }
1292     break;
1293 
1294   case OR_Ambiguous:
1295     ICS.setAmbiguous();
1296     ICS.Ambiguous.setFromType(From->getType());
1297     ICS.Ambiguous.setToType(ToType);
1298     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1299          Cand != Conversions.end(); ++Cand)
1300       if (Cand->Viable)
1301         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1302     break;
1303 
1304     // Fall through.
1305   case OR_No_Viable_Function:
1306     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1307     break;
1308   }
1309 
1310   return ICS;
1311 }
1312 
1313 /// TryImplicitConversion - Attempt to perform an implicit conversion
1314 /// from the given expression (Expr) to the given type (ToType). This
1315 /// function returns an implicit conversion sequence that can be used
1316 /// to perform the initialization. Given
1317 ///
1318 ///   void f(float f);
1319 ///   void g(int i) { f(i); }
1320 ///
1321 /// this routine would produce an implicit conversion sequence to
1322 /// describe the initialization of f from i, which will be a standard
1323 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1324 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1325 //
1326 /// Note that this routine only determines how the conversion can be
1327 /// performed; it does not actually perform the conversion. As such,
1328 /// it will not produce any diagnostics if no conversion is available,
1329 /// but will instead return an implicit conversion sequence of kind
1330 /// "BadConversion".
1331 ///
1332 /// If @p SuppressUserConversions, then user-defined conversions are
1333 /// not permitted.
1334 /// If @p AllowExplicit, then explicit user-defined conversions are
1335 /// permitted.
1336 ///
1337 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1338 /// writeback conversion, which allows __autoreleasing id* parameters to
1339 /// be initialized with __strong id* or __weak id* arguments.
1340 static ImplicitConversionSequence
1341 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1342                       bool SuppressUserConversions,
1343                       bool AllowExplicit,
1344                       bool InOverloadResolution,
1345                       bool CStyle,
1346                       bool AllowObjCWritebackConversion,
1347                       bool AllowObjCConversionOnExplicit) {
1348   ImplicitConversionSequence ICS;
1349   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1350                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1351     ICS.setStandard();
1352     return ICS;
1353   }
1354 
1355   if (!S.getLangOpts().CPlusPlus) {
1356     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1357     return ICS;
1358   }
1359 
1360   // C++ [over.ics.user]p4:
1361   //   A conversion of an expression of class type to the same class
1362   //   type is given Exact Match rank, and a conversion of an
1363   //   expression of class type to a base class of that type is
1364   //   given Conversion rank, in spite of the fact that a copy/move
1365   //   constructor (i.e., a user-defined conversion function) is
1366   //   called for those cases.
1367   QualType FromType = From->getType();
1368   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1369       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1370        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1371     ICS.setStandard();
1372     ICS.Standard.setAsIdentityConversion();
1373     ICS.Standard.setFromType(FromType);
1374     ICS.Standard.setAllToTypes(ToType);
1375 
1376     // We don't actually check at this point whether there is a valid
1377     // copy/move constructor, since overloading just assumes that it
1378     // exists. When we actually perform initialization, we'll find the
1379     // appropriate constructor to copy the returned object, if needed.
1380     ICS.Standard.CopyConstructor = nullptr;
1381 
1382     // Determine whether this is considered a derived-to-base conversion.
1383     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1384       ICS.Standard.Second = ICK_Derived_To_Base;
1385 
1386     return ICS;
1387   }
1388 
1389   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1390                                   AllowExplicit, InOverloadResolution, CStyle,
1391                                   AllowObjCWritebackConversion,
1392                                   AllowObjCConversionOnExplicit);
1393 }
1394 
1395 ImplicitConversionSequence
1396 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1397                             bool SuppressUserConversions,
1398                             bool AllowExplicit,
1399                             bool InOverloadResolution,
1400                             bool CStyle,
1401                             bool AllowObjCWritebackConversion) {
1402   return ::TryImplicitConversion(*this, From, ToType,
1403                                  SuppressUserConversions, AllowExplicit,
1404                                  InOverloadResolution, CStyle,
1405                                  AllowObjCWritebackConversion,
1406                                  /*AllowObjCConversionOnExplicit=*/false);
1407 }
1408 
1409 /// PerformImplicitConversion - Perform an implicit conversion of the
1410 /// expression From to the type ToType. Returns the
1411 /// converted expression. Flavor is the kind of conversion we're
1412 /// performing, used in the error message. If @p AllowExplicit,
1413 /// explicit user-defined conversions are permitted.
1414 ExprResult
1415 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1416                                 AssignmentAction Action, bool AllowExplicit) {
1417   ImplicitConversionSequence ICS;
1418   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1419 }
1420 
1421 ExprResult
1422 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1423                                 AssignmentAction Action, bool AllowExplicit,
1424                                 ImplicitConversionSequence& ICS) {
1425   if (checkPlaceholderForOverload(*this, From))
1426     return ExprError();
1427 
1428   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1429   bool AllowObjCWritebackConversion
1430     = getLangOpts().ObjCAutoRefCount &&
1431       (Action == AA_Passing || Action == AA_Sending);
1432   if (getLangOpts().ObjC)
1433     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1434                                       From->getType(), From);
1435   ICS = ::TryImplicitConversion(*this, From, ToType,
1436                                 /*SuppressUserConversions=*/false,
1437                                 AllowExplicit,
1438                                 /*InOverloadResolution=*/false,
1439                                 /*CStyle=*/false,
1440                                 AllowObjCWritebackConversion,
1441                                 /*AllowObjCConversionOnExplicit=*/false);
1442   return PerformImplicitConversion(From, ToType, ICS, Action);
1443 }
1444 
1445 /// Determine whether the conversion from FromType to ToType is a valid
1446 /// conversion that strips "noexcept" or "noreturn" off the nested function
1447 /// type.
1448 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1449                                 QualType &ResultTy) {
1450   if (Context.hasSameUnqualifiedType(FromType, ToType))
1451     return false;
1452 
1453   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1454   //                    or F(t noexcept) -> F(t)
1455   // where F adds one of the following at most once:
1456   //   - a pointer
1457   //   - a member pointer
1458   //   - a block pointer
1459   // Changes here need matching changes in FindCompositePointerType.
1460   CanQualType CanTo = Context.getCanonicalType(ToType);
1461   CanQualType CanFrom = Context.getCanonicalType(FromType);
1462   Type::TypeClass TyClass = CanTo->getTypeClass();
1463   if (TyClass != CanFrom->getTypeClass()) return false;
1464   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1465     if (TyClass == Type::Pointer) {
1466       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1467       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1468     } else if (TyClass == Type::BlockPointer) {
1469       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1470       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1471     } else if (TyClass == Type::MemberPointer) {
1472       auto ToMPT = CanTo.getAs<MemberPointerType>();
1473       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1474       // A function pointer conversion cannot change the class of the function.
1475       if (ToMPT->getClass() != FromMPT->getClass())
1476         return false;
1477       CanTo = ToMPT->getPointeeType();
1478       CanFrom = FromMPT->getPointeeType();
1479     } else {
1480       return false;
1481     }
1482 
1483     TyClass = CanTo->getTypeClass();
1484     if (TyClass != CanFrom->getTypeClass()) return false;
1485     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1486       return false;
1487   }
1488 
1489   const auto *FromFn = cast<FunctionType>(CanFrom);
1490   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1491 
1492   const auto *ToFn = cast<FunctionType>(CanTo);
1493   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1494 
1495   bool Changed = false;
1496 
1497   // Drop 'noreturn' if not present in target type.
1498   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1499     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1500     Changed = true;
1501   }
1502 
1503   // Drop 'noexcept' if not present in target type.
1504   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1505     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1506     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1507       FromFn = cast<FunctionType>(
1508           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1509                                                    EST_None)
1510                  .getTypePtr());
1511       Changed = true;
1512     }
1513 
1514     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1515     // only if the ExtParameterInfo lists of the two function prototypes can be
1516     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1517     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1518     bool CanUseToFPT, CanUseFromFPT;
1519     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1520                                       CanUseFromFPT, NewParamInfos) &&
1521         CanUseToFPT && !CanUseFromFPT) {
1522       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1523       ExtInfo.ExtParameterInfos =
1524           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1525       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1526                                             FromFPT->getParamTypes(), ExtInfo);
1527       FromFn = QT->getAs<FunctionType>();
1528       Changed = true;
1529     }
1530   }
1531 
1532   if (!Changed)
1533     return false;
1534 
1535   assert(QualType(FromFn, 0).isCanonical());
1536   if (QualType(FromFn, 0) != CanTo) return false;
1537 
1538   ResultTy = ToType;
1539   return true;
1540 }
1541 
1542 /// Determine whether the conversion from FromType to ToType is a valid
1543 /// vector conversion.
1544 ///
1545 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1546 /// conversion.
1547 static bool IsVectorConversion(Sema &S, QualType FromType,
1548                                QualType ToType, ImplicitConversionKind &ICK) {
1549   // We need at least one of these types to be a vector type to have a vector
1550   // conversion.
1551   if (!ToType->isVectorType() && !FromType->isVectorType())
1552     return false;
1553 
1554   // Identical types require no conversions.
1555   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1556     return false;
1557 
1558   // There are no conversions between extended vector types, only identity.
1559   if (ToType->isExtVectorType()) {
1560     // There are no conversions between extended vector types other than the
1561     // identity conversion.
1562     if (FromType->isExtVectorType())
1563       return false;
1564 
1565     // Vector splat from any arithmetic type to a vector.
1566     if (FromType->isArithmeticType()) {
1567       ICK = ICK_Vector_Splat;
1568       return true;
1569     }
1570   }
1571 
1572   // We can perform the conversion between vector types in the following cases:
1573   // 1)vector types are equivalent AltiVec and GCC vector types
1574   // 2)lax vector conversions are permitted and the vector types are of the
1575   //   same size
1576   if (ToType->isVectorType() && FromType->isVectorType()) {
1577     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1578         S.isLaxVectorConversion(FromType, ToType)) {
1579       ICK = ICK_Vector_Conversion;
1580       return true;
1581     }
1582   }
1583 
1584   return false;
1585 }
1586 
1587 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1588                                 bool InOverloadResolution,
1589                                 StandardConversionSequence &SCS,
1590                                 bool CStyle);
1591 
1592 /// IsStandardConversion - Determines whether there is a standard
1593 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1594 /// expression From to the type ToType. Standard conversion sequences
1595 /// only consider non-class types; for conversions that involve class
1596 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1597 /// contain the standard conversion sequence required to perform this
1598 /// conversion and this routine will return true. Otherwise, this
1599 /// routine will return false and the value of SCS is unspecified.
1600 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1601                                  bool InOverloadResolution,
1602                                  StandardConversionSequence &SCS,
1603                                  bool CStyle,
1604                                  bool AllowObjCWritebackConversion) {
1605   QualType FromType = From->getType();
1606 
1607   // Standard conversions (C++ [conv])
1608   SCS.setAsIdentityConversion();
1609   SCS.IncompatibleObjC = false;
1610   SCS.setFromType(FromType);
1611   SCS.CopyConstructor = nullptr;
1612 
1613   // There are no standard conversions for class types in C++, so
1614   // abort early. When overloading in C, however, we do permit them.
1615   if (S.getLangOpts().CPlusPlus &&
1616       (FromType->isRecordType() || ToType->isRecordType()))
1617     return false;
1618 
1619   // The first conversion can be an lvalue-to-rvalue conversion,
1620   // array-to-pointer conversion, or function-to-pointer conversion
1621   // (C++ 4p1).
1622 
1623   if (FromType == S.Context.OverloadTy) {
1624     DeclAccessPair AccessPair;
1625     if (FunctionDecl *Fn
1626           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1627                                                  AccessPair)) {
1628       // We were able to resolve the address of the overloaded function,
1629       // so we can convert to the type of that function.
1630       FromType = Fn->getType();
1631       SCS.setFromType(FromType);
1632 
1633       // we can sometimes resolve &foo<int> regardless of ToType, so check
1634       // if the type matches (identity) or we are converting to bool
1635       if (!S.Context.hasSameUnqualifiedType(
1636                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1637         QualType resultTy;
1638         // if the function type matches except for [[noreturn]], it's ok
1639         if (!S.IsFunctionConversion(FromType,
1640               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1641           // otherwise, only a boolean conversion is standard
1642           if (!ToType->isBooleanType())
1643             return false;
1644       }
1645 
1646       // Check if the "from" expression is taking the address of an overloaded
1647       // function and recompute the FromType accordingly. Take advantage of the
1648       // fact that non-static member functions *must* have such an address-of
1649       // expression.
1650       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1651       if (Method && !Method->isStatic()) {
1652         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1653                "Non-unary operator on non-static member address");
1654         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1655                == UO_AddrOf &&
1656                "Non-address-of operator on non-static member address");
1657         const Type *ClassType
1658           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1659         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1660       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1661         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1662                UO_AddrOf &&
1663                "Non-address-of operator for overloaded function expression");
1664         FromType = S.Context.getPointerType(FromType);
1665       }
1666 
1667       // Check that we've computed the proper type after overload resolution.
1668       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1669       // be calling it from within an NDEBUG block.
1670       assert(S.Context.hasSameType(
1671         FromType,
1672         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1673     } else {
1674       return false;
1675     }
1676   }
1677   // Lvalue-to-rvalue conversion (C++11 4.1):
1678   //   A glvalue (3.10) of a non-function, non-array type T can
1679   //   be converted to a prvalue.
1680   bool argIsLValue = From->isGLValue();
1681   if (argIsLValue &&
1682       !FromType->isFunctionType() && !FromType->isArrayType() &&
1683       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1684     SCS.First = ICK_Lvalue_To_Rvalue;
1685 
1686     // C11 6.3.2.1p2:
1687     //   ... if the lvalue has atomic type, the value has the non-atomic version
1688     //   of the type of the lvalue ...
1689     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1690       FromType = Atomic->getValueType();
1691 
1692     // If T is a non-class type, the type of the rvalue is the
1693     // cv-unqualified version of T. Otherwise, the type of the rvalue
1694     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1695     // just strip the qualifiers because they don't matter.
1696     FromType = FromType.getUnqualifiedType();
1697   } else if (FromType->isArrayType()) {
1698     // Array-to-pointer conversion (C++ 4.2)
1699     SCS.First = ICK_Array_To_Pointer;
1700 
1701     // An lvalue or rvalue of type "array of N T" or "array of unknown
1702     // bound of T" can be converted to an rvalue of type "pointer to
1703     // T" (C++ 4.2p1).
1704     FromType = S.Context.getArrayDecayedType(FromType);
1705 
1706     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1707       // This conversion is deprecated in C++03 (D.4)
1708       SCS.DeprecatedStringLiteralToCharPtr = true;
1709 
1710       // For the purpose of ranking in overload resolution
1711       // (13.3.3.1.1), this conversion is considered an
1712       // array-to-pointer conversion followed by a qualification
1713       // conversion (4.4). (C++ 4.2p2)
1714       SCS.Second = ICK_Identity;
1715       SCS.Third = ICK_Qualification;
1716       SCS.QualificationIncludesObjCLifetime = false;
1717       SCS.setAllToTypes(FromType);
1718       return true;
1719     }
1720   } else if (FromType->isFunctionType() && argIsLValue) {
1721     // Function-to-pointer conversion (C++ 4.3).
1722     SCS.First = ICK_Function_To_Pointer;
1723 
1724     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1725       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1726         if (!S.checkAddressOfFunctionIsAvailable(FD))
1727           return false;
1728 
1729     // An lvalue of function type T can be converted to an rvalue of
1730     // type "pointer to T." The result is a pointer to the
1731     // function. (C++ 4.3p1).
1732     FromType = S.Context.getPointerType(FromType);
1733   } else {
1734     // We don't require any conversions for the first step.
1735     SCS.First = ICK_Identity;
1736   }
1737   SCS.setToType(0, FromType);
1738 
1739   // The second conversion can be an integral promotion, floating
1740   // point promotion, integral conversion, floating point conversion,
1741   // floating-integral conversion, pointer conversion,
1742   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1743   // For overloading in C, this can also be a "compatible-type"
1744   // conversion.
1745   bool IncompatibleObjC = false;
1746   ImplicitConversionKind SecondICK = ICK_Identity;
1747   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1748     // The unqualified versions of the types are the same: there's no
1749     // conversion to do.
1750     SCS.Second = ICK_Identity;
1751   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1752     // Integral promotion (C++ 4.5).
1753     SCS.Second = ICK_Integral_Promotion;
1754     FromType = ToType.getUnqualifiedType();
1755   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1756     // Floating point promotion (C++ 4.6).
1757     SCS.Second = ICK_Floating_Promotion;
1758     FromType = ToType.getUnqualifiedType();
1759   } else if (S.IsComplexPromotion(FromType, ToType)) {
1760     // Complex promotion (Clang extension)
1761     SCS.Second = ICK_Complex_Promotion;
1762     FromType = ToType.getUnqualifiedType();
1763   } else if (ToType->isBooleanType() &&
1764              (FromType->isArithmeticType() ||
1765               FromType->isAnyPointerType() ||
1766               FromType->isBlockPointerType() ||
1767               FromType->isMemberPointerType() ||
1768               FromType->isNullPtrType())) {
1769     // Boolean conversions (C++ 4.12).
1770     SCS.Second = ICK_Boolean_Conversion;
1771     FromType = S.Context.BoolTy;
1772   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1773              ToType->isIntegralType(S.Context)) {
1774     // Integral conversions (C++ 4.7).
1775     SCS.Second = ICK_Integral_Conversion;
1776     FromType = ToType.getUnqualifiedType();
1777   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1778     // Complex conversions (C99 6.3.1.6)
1779     SCS.Second = ICK_Complex_Conversion;
1780     FromType = ToType.getUnqualifiedType();
1781   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1782              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1783     // Complex-real conversions (C99 6.3.1.7)
1784     SCS.Second = ICK_Complex_Real;
1785     FromType = ToType.getUnqualifiedType();
1786   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1787     // FIXME: disable conversions between long double and __float128 if
1788     // their representation is different until there is back end support
1789     // We of course allow this conversion if long double is really double.
1790     if (&S.Context.getFloatTypeSemantics(FromType) !=
1791         &S.Context.getFloatTypeSemantics(ToType)) {
1792       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1793                                     ToType == S.Context.LongDoubleTy) ||
1794                                    (FromType == S.Context.LongDoubleTy &&
1795                                     ToType == S.Context.Float128Ty));
1796       if (Float128AndLongDouble &&
1797           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1798            &llvm::APFloat::PPCDoubleDouble()))
1799         return false;
1800     }
1801     // Floating point conversions (C++ 4.8).
1802     SCS.Second = ICK_Floating_Conversion;
1803     FromType = ToType.getUnqualifiedType();
1804   } else if ((FromType->isRealFloatingType() &&
1805               ToType->isIntegralType(S.Context)) ||
1806              (FromType->isIntegralOrUnscopedEnumerationType() &&
1807               ToType->isRealFloatingType())) {
1808     // Floating-integral conversions (C++ 4.9).
1809     SCS.Second = ICK_Floating_Integral;
1810     FromType = ToType.getUnqualifiedType();
1811   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1812     SCS.Second = ICK_Block_Pointer_Conversion;
1813   } else if (AllowObjCWritebackConversion &&
1814              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1815     SCS.Second = ICK_Writeback_Conversion;
1816   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1817                                    FromType, IncompatibleObjC)) {
1818     // Pointer conversions (C++ 4.10).
1819     SCS.Second = ICK_Pointer_Conversion;
1820     SCS.IncompatibleObjC = IncompatibleObjC;
1821     FromType = FromType.getUnqualifiedType();
1822   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1823                                          InOverloadResolution, FromType)) {
1824     // Pointer to member conversions (4.11).
1825     SCS.Second = ICK_Pointer_Member;
1826   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1827     SCS.Second = SecondICK;
1828     FromType = ToType.getUnqualifiedType();
1829   } else if (!S.getLangOpts().CPlusPlus &&
1830              S.Context.typesAreCompatible(ToType, FromType)) {
1831     // Compatible conversions (Clang extension for C function overloading)
1832     SCS.Second = ICK_Compatible_Conversion;
1833     FromType = ToType.getUnqualifiedType();
1834   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1835                                              InOverloadResolution,
1836                                              SCS, CStyle)) {
1837     SCS.Second = ICK_TransparentUnionConversion;
1838     FromType = ToType;
1839   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1840                                  CStyle)) {
1841     // tryAtomicConversion has updated the standard conversion sequence
1842     // appropriately.
1843     return true;
1844   } else if (ToType->isEventT() &&
1845              From->isIntegerConstantExpr(S.getASTContext()) &&
1846              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1847     SCS.Second = ICK_Zero_Event_Conversion;
1848     FromType = ToType;
1849   } else if (ToType->isQueueT() &&
1850              From->isIntegerConstantExpr(S.getASTContext()) &&
1851              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1852     SCS.Second = ICK_Zero_Queue_Conversion;
1853     FromType = ToType;
1854   } else if (ToType->isSamplerT() &&
1855              From->isIntegerConstantExpr(S.getASTContext())) {
1856     SCS.Second = ICK_Compatible_Conversion;
1857     FromType = ToType;
1858   } else {
1859     // No second conversion required.
1860     SCS.Second = ICK_Identity;
1861   }
1862   SCS.setToType(1, FromType);
1863 
1864   // The third conversion can be a function pointer conversion or a
1865   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1866   bool ObjCLifetimeConversion;
1867   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1868     // Function pointer conversions (removing 'noexcept') including removal of
1869     // 'noreturn' (Clang extension).
1870     SCS.Third = ICK_Function_Conversion;
1871   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1872                                          ObjCLifetimeConversion)) {
1873     SCS.Third = ICK_Qualification;
1874     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1875     FromType = ToType;
1876   } else {
1877     // No conversion required
1878     SCS.Third = ICK_Identity;
1879   }
1880 
1881   // C++ [over.best.ics]p6:
1882   //   [...] Any difference in top-level cv-qualification is
1883   //   subsumed by the initialization itself and does not constitute
1884   //   a conversion. [...]
1885   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1886   QualType CanonTo = S.Context.getCanonicalType(ToType);
1887   if (CanonFrom.getLocalUnqualifiedType()
1888                                      == CanonTo.getLocalUnqualifiedType() &&
1889       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1890     FromType = ToType;
1891     CanonFrom = CanonTo;
1892   }
1893 
1894   SCS.setToType(2, FromType);
1895 
1896   if (CanonFrom == CanonTo)
1897     return true;
1898 
1899   // If we have not converted the argument type to the parameter type,
1900   // this is a bad conversion sequence, unless we're resolving an overload in C.
1901   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1902     return false;
1903 
1904   ExprResult ER = ExprResult{From};
1905   Sema::AssignConvertType Conv =
1906       S.CheckSingleAssignmentConstraints(ToType, ER,
1907                                          /*Diagnose=*/false,
1908                                          /*DiagnoseCFAudited=*/false,
1909                                          /*ConvertRHS=*/false);
1910   ImplicitConversionKind SecondConv;
1911   switch (Conv) {
1912   case Sema::Compatible:
1913     SecondConv = ICK_C_Only_Conversion;
1914     break;
1915   // For our purposes, discarding qualifiers is just as bad as using an
1916   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1917   // qualifiers, as well.
1918   case Sema::CompatiblePointerDiscardsQualifiers:
1919   case Sema::IncompatiblePointer:
1920   case Sema::IncompatiblePointerSign:
1921     SecondConv = ICK_Incompatible_Pointer_Conversion;
1922     break;
1923   default:
1924     return false;
1925   }
1926 
1927   // First can only be an lvalue conversion, so we pretend that this was the
1928   // second conversion. First should already be valid from earlier in the
1929   // function.
1930   SCS.Second = SecondConv;
1931   SCS.setToType(1, ToType);
1932 
1933   // Third is Identity, because Second should rank us worse than any other
1934   // conversion. This could also be ICK_Qualification, but it's simpler to just
1935   // lump everything in with the second conversion, and we don't gain anything
1936   // from making this ICK_Qualification.
1937   SCS.Third = ICK_Identity;
1938   SCS.setToType(2, ToType);
1939   return true;
1940 }
1941 
1942 static bool
1943 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1944                                      QualType &ToType,
1945                                      bool InOverloadResolution,
1946                                      StandardConversionSequence &SCS,
1947                                      bool CStyle) {
1948 
1949   const RecordType *UT = ToType->getAsUnionType();
1950   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1951     return false;
1952   // The field to initialize within the transparent union.
1953   RecordDecl *UD = UT->getDecl();
1954   // It's compatible if the expression matches any of the fields.
1955   for (const auto *it : UD->fields()) {
1956     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1957                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
1958       ToType = it->getType();
1959       return true;
1960     }
1961   }
1962   return false;
1963 }
1964 
1965 /// IsIntegralPromotion - Determines whether the conversion from the
1966 /// expression From (whose potentially-adjusted type is FromType) to
1967 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1968 /// sets PromotedType to the promoted type.
1969 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1970   const BuiltinType *To = ToType->getAs<BuiltinType>();
1971   // All integers are built-in.
1972   if (!To) {
1973     return false;
1974   }
1975 
1976   // An rvalue of type char, signed char, unsigned char, short int, or
1977   // unsigned short int can be converted to an rvalue of type int if
1978   // int can represent all the values of the source type; otherwise,
1979   // the source rvalue can be converted to an rvalue of type unsigned
1980   // int (C++ 4.5p1).
1981   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1982       !FromType->isEnumeralType()) {
1983     if (// We can promote any signed, promotable integer type to an int
1984         (FromType->isSignedIntegerType() ||
1985          // We can promote any unsigned integer type whose size is
1986          // less than int to an int.
1987          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1988       return To->getKind() == BuiltinType::Int;
1989     }
1990 
1991     return To->getKind() == BuiltinType::UInt;
1992   }
1993 
1994   // C++11 [conv.prom]p3:
1995   //   A prvalue of an unscoped enumeration type whose underlying type is not
1996   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1997   //   following types that can represent all the values of the enumeration
1998   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1999   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2000   //   long long int. If none of the types in that list can represent all the
2001   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2002   //   type can be converted to an rvalue a prvalue of the extended integer type
2003   //   with lowest integer conversion rank (4.13) greater than the rank of long
2004   //   long in which all the values of the enumeration can be represented. If
2005   //   there are two such extended types, the signed one is chosen.
2006   // C++11 [conv.prom]p4:
2007   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2008   //   can be converted to a prvalue of its underlying type. Moreover, if
2009   //   integral promotion can be applied to its underlying type, a prvalue of an
2010   //   unscoped enumeration type whose underlying type is fixed can also be
2011   //   converted to a prvalue of the promoted underlying type.
2012   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2013     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2014     // provided for a scoped enumeration.
2015     if (FromEnumType->getDecl()->isScoped())
2016       return false;
2017 
2018     // We can perform an integral promotion to the underlying type of the enum,
2019     // even if that's not the promoted type. Note that the check for promoting
2020     // the underlying type is based on the type alone, and does not consider
2021     // the bitfield-ness of the actual source expression.
2022     if (FromEnumType->getDecl()->isFixed()) {
2023       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2024       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2025              IsIntegralPromotion(nullptr, Underlying, ToType);
2026     }
2027 
2028     // We have already pre-calculated the promotion type, so this is trivial.
2029     if (ToType->isIntegerType() &&
2030         isCompleteType(From->getBeginLoc(), FromType))
2031       return Context.hasSameUnqualifiedType(
2032           ToType, FromEnumType->getDecl()->getPromotionType());
2033 
2034     // C++ [conv.prom]p5:
2035     //   If the bit-field has an enumerated type, it is treated as any other
2036     //   value of that type for promotion purposes.
2037     //
2038     // ... so do not fall through into the bit-field checks below in C++.
2039     if (getLangOpts().CPlusPlus)
2040       return false;
2041   }
2042 
2043   // C++0x [conv.prom]p2:
2044   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2045   //   to an rvalue a prvalue of the first of the following types that can
2046   //   represent all the values of its underlying type: int, unsigned int,
2047   //   long int, unsigned long int, long long int, or unsigned long long int.
2048   //   If none of the types in that list can represent all the values of its
2049   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2050   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2051   //   type.
2052   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2053       ToType->isIntegerType()) {
2054     // Determine whether the type we're converting from is signed or
2055     // unsigned.
2056     bool FromIsSigned = FromType->isSignedIntegerType();
2057     uint64_t FromSize = Context.getTypeSize(FromType);
2058 
2059     // The types we'll try to promote to, in the appropriate
2060     // order. Try each of these types.
2061     QualType PromoteTypes[6] = {
2062       Context.IntTy, Context.UnsignedIntTy,
2063       Context.LongTy, Context.UnsignedLongTy ,
2064       Context.LongLongTy, Context.UnsignedLongLongTy
2065     };
2066     for (int Idx = 0; Idx < 6; ++Idx) {
2067       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2068       if (FromSize < ToSize ||
2069           (FromSize == ToSize &&
2070            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2071         // We found the type that we can promote to. If this is the
2072         // type we wanted, we have a promotion. Otherwise, no
2073         // promotion.
2074         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2075       }
2076     }
2077   }
2078 
2079   // An rvalue for an integral bit-field (9.6) can be converted to an
2080   // rvalue of type int if int can represent all the values of the
2081   // bit-field; otherwise, it can be converted to unsigned int if
2082   // unsigned int can represent all the values of the bit-field. If
2083   // the bit-field is larger yet, no integral promotion applies to
2084   // it. If the bit-field has an enumerated type, it is treated as any
2085   // other value of that type for promotion purposes (C++ 4.5p3).
2086   // FIXME: We should delay checking of bit-fields until we actually perform the
2087   // conversion.
2088   //
2089   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2090   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2091   // bit-fields and those whose underlying type is larger than int) for GCC
2092   // compatibility.
2093   if (From) {
2094     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2095       llvm::APSInt BitWidth;
2096       if (FromType->isIntegralType(Context) &&
2097           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2098         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2099         ToSize = Context.getTypeSize(ToType);
2100 
2101         // Are we promoting to an int from a bitfield that fits in an int?
2102         if (BitWidth < ToSize ||
2103             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2104           return To->getKind() == BuiltinType::Int;
2105         }
2106 
2107         // Are we promoting to an unsigned int from an unsigned bitfield
2108         // that fits into an unsigned int?
2109         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2110           return To->getKind() == BuiltinType::UInt;
2111         }
2112 
2113         return false;
2114       }
2115     }
2116   }
2117 
2118   // An rvalue of type bool can be converted to an rvalue of type int,
2119   // with false becoming zero and true becoming one (C++ 4.5p4).
2120   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2121     return true;
2122   }
2123 
2124   return false;
2125 }
2126 
2127 /// IsFloatingPointPromotion - Determines whether the conversion from
2128 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2129 /// returns true and sets PromotedType to the promoted type.
2130 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2131   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2132     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2133       /// An rvalue of type float can be converted to an rvalue of type
2134       /// double. (C++ 4.6p1).
2135       if (FromBuiltin->getKind() == BuiltinType::Float &&
2136           ToBuiltin->getKind() == BuiltinType::Double)
2137         return true;
2138 
2139       // C99 6.3.1.5p1:
2140       //   When a float is promoted to double or long double, or a
2141       //   double is promoted to long double [...].
2142       if (!getLangOpts().CPlusPlus &&
2143           (FromBuiltin->getKind() == BuiltinType::Float ||
2144            FromBuiltin->getKind() == BuiltinType::Double) &&
2145           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2146            ToBuiltin->getKind() == BuiltinType::Float128))
2147         return true;
2148 
2149       // Half can be promoted to float.
2150       if (!getLangOpts().NativeHalfType &&
2151            FromBuiltin->getKind() == BuiltinType::Half &&
2152           ToBuiltin->getKind() == BuiltinType::Float)
2153         return true;
2154     }
2155 
2156   return false;
2157 }
2158 
2159 /// Determine if a conversion is a complex promotion.
2160 ///
2161 /// A complex promotion is defined as a complex -> complex conversion
2162 /// where the conversion between the underlying real types is a
2163 /// floating-point or integral promotion.
2164 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2165   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2166   if (!FromComplex)
2167     return false;
2168 
2169   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2170   if (!ToComplex)
2171     return false;
2172 
2173   return IsFloatingPointPromotion(FromComplex->getElementType(),
2174                                   ToComplex->getElementType()) ||
2175     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2176                         ToComplex->getElementType());
2177 }
2178 
2179 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2180 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2181 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2182 /// if non-empty, will be a pointer to ToType that may or may not have
2183 /// the right set of qualifiers on its pointee.
2184 ///
2185 static QualType
2186 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2187                                    QualType ToPointee, QualType ToType,
2188                                    ASTContext &Context,
2189                                    bool StripObjCLifetime = false) {
2190   assert((FromPtr->getTypeClass() == Type::Pointer ||
2191           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2192          "Invalid similarly-qualified pointer type");
2193 
2194   /// Conversions to 'id' subsume cv-qualifier conversions.
2195   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2196     return ToType.getUnqualifiedType();
2197 
2198   QualType CanonFromPointee
2199     = Context.getCanonicalType(FromPtr->getPointeeType());
2200   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2201   Qualifiers Quals = CanonFromPointee.getQualifiers();
2202 
2203   if (StripObjCLifetime)
2204     Quals.removeObjCLifetime();
2205 
2206   // Exact qualifier match -> return the pointer type we're converting to.
2207   if (CanonToPointee.getLocalQualifiers() == Quals) {
2208     // ToType is exactly what we need. Return it.
2209     if (!ToType.isNull())
2210       return ToType.getUnqualifiedType();
2211 
2212     // Build a pointer to ToPointee. It has the right qualifiers
2213     // already.
2214     if (isa<ObjCObjectPointerType>(ToType))
2215       return Context.getObjCObjectPointerType(ToPointee);
2216     return Context.getPointerType(ToPointee);
2217   }
2218 
2219   // Just build a canonical type that has the right qualifiers.
2220   QualType QualifiedCanonToPointee
2221     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2222 
2223   if (isa<ObjCObjectPointerType>(ToType))
2224     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2225   return Context.getPointerType(QualifiedCanonToPointee);
2226 }
2227 
2228 static bool isNullPointerConstantForConversion(Expr *Expr,
2229                                                bool InOverloadResolution,
2230                                                ASTContext &Context) {
2231   // Handle value-dependent integral null pointer constants correctly.
2232   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2233   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2234       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2235     return !InOverloadResolution;
2236 
2237   return Expr->isNullPointerConstant(Context,
2238                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2239                                         : Expr::NPC_ValueDependentIsNull);
2240 }
2241 
2242 /// IsPointerConversion - Determines whether the conversion of the
2243 /// expression From, which has the (possibly adjusted) type FromType,
2244 /// can be converted to the type ToType via a pointer conversion (C++
2245 /// 4.10). If so, returns true and places the converted type (that
2246 /// might differ from ToType in its cv-qualifiers at some level) into
2247 /// ConvertedType.
2248 ///
2249 /// This routine also supports conversions to and from block pointers
2250 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2251 /// pointers to interfaces. FIXME: Once we've determined the
2252 /// appropriate overloading rules for Objective-C, we may want to
2253 /// split the Objective-C checks into a different routine; however,
2254 /// GCC seems to consider all of these conversions to be pointer
2255 /// conversions, so for now they live here. IncompatibleObjC will be
2256 /// set if the conversion is an allowed Objective-C conversion that
2257 /// should result in a warning.
2258 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2259                                bool InOverloadResolution,
2260                                QualType& ConvertedType,
2261                                bool &IncompatibleObjC) {
2262   IncompatibleObjC = false;
2263   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2264                               IncompatibleObjC))
2265     return true;
2266 
2267   // Conversion from a null pointer constant to any Objective-C pointer type.
2268   if (ToType->isObjCObjectPointerType() &&
2269       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2270     ConvertedType = ToType;
2271     return true;
2272   }
2273 
2274   // Blocks: Block pointers can be converted to void*.
2275   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2276       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2277     ConvertedType = ToType;
2278     return true;
2279   }
2280   // Blocks: A null pointer constant can be converted to a block
2281   // pointer type.
2282   if (ToType->isBlockPointerType() &&
2283       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2284     ConvertedType = ToType;
2285     return true;
2286   }
2287 
2288   // If the left-hand-side is nullptr_t, the right side can be a null
2289   // pointer constant.
2290   if (ToType->isNullPtrType() &&
2291       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2292     ConvertedType = ToType;
2293     return true;
2294   }
2295 
2296   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2297   if (!ToTypePtr)
2298     return false;
2299 
2300   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2301   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2302     ConvertedType = ToType;
2303     return true;
2304   }
2305 
2306   // Beyond this point, both types need to be pointers
2307   // , including objective-c pointers.
2308   QualType ToPointeeType = ToTypePtr->getPointeeType();
2309   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2310       !getLangOpts().ObjCAutoRefCount) {
2311     ConvertedType = BuildSimilarlyQualifiedPointerType(
2312                                       FromType->getAs<ObjCObjectPointerType>(),
2313                                                        ToPointeeType,
2314                                                        ToType, Context);
2315     return true;
2316   }
2317   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2318   if (!FromTypePtr)
2319     return false;
2320 
2321   QualType FromPointeeType = FromTypePtr->getPointeeType();
2322 
2323   // If the unqualified pointee types are the same, this can't be a
2324   // pointer conversion, so don't do all of the work below.
2325   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2326     return false;
2327 
2328   // An rvalue of type "pointer to cv T," where T is an object type,
2329   // can be converted to an rvalue of type "pointer to cv void" (C++
2330   // 4.10p2).
2331   if (FromPointeeType->isIncompleteOrObjectType() &&
2332       ToPointeeType->isVoidType()) {
2333     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2334                                                        ToPointeeType,
2335                                                        ToType, Context,
2336                                                    /*StripObjCLifetime=*/true);
2337     return true;
2338   }
2339 
2340   // MSVC allows implicit function to void* type conversion.
2341   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2342       ToPointeeType->isVoidType()) {
2343     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2344                                                        ToPointeeType,
2345                                                        ToType, Context);
2346     return true;
2347   }
2348 
2349   // When we're overloading in C, we allow a special kind of pointer
2350   // conversion for compatible-but-not-identical pointee types.
2351   if (!getLangOpts().CPlusPlus &&
2352       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2353     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2354                                                        ToPointeeType,
2355                                                        ToType, Context);
2356     return true;
2357   }
2358 
2359   // C++ [conv.ptr]p3:
2360   //
2361   //   An rvalue of type "pointer to cv D," where D is a class type,
2362   //   can be converted to an rvalue of type "pointer to cv B," where
2363   //   B is a base class (clause 10) of D. If B is an inaccessible
2364   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2365   //   necessitates this conversion is ill-formed. The result of the
2366   //   conversion is a pointer to the base class sub-object of the
2367   //   derived class object. The null pointer value is converted to
2368   //   the null pointer value of the destination type.
2369   //
2370   // Note that we do not check for ambiguity or inaccessibility
2371   // here. That is handled by CheckPointerConversion.
2372   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2373       ToPointeeType->isRecordType() &&
2374       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2375       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2376     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2377                                                        ToPointeeType,
2378                                                        ToType, Context);
2379     return true;
2380   }
2381 
2382   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2383       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2384     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2385                                                        ToPointeeType,
2386                                                        ToType, Context);
2387     return true;
2388   }
2389 
2390   return false;
2391 }
2392 
2393 /// Adopt the given qualifiers for the given type.
2394 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2395   Qualifiers TQs = T.getQualifiers();
2396 
2397   // Check whether qualifiers already match.
2398   if (TQs == Qs)
2399     return T;
2400 
2401   if (Qs.compatiblyIncludes(TQs))
2402     return Context.getQualifiedType(T, Qs);
2403 
2404   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2405 }
2406 
2407 /// isObjCPointerConversion - Determines whether this is an
2408 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2409 /// with the same arguments and return values.
2410 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2411                                    QualType& ConvertedType,
2412                                    bool &IncompatibleObjC) {
2413   if (!getLangOpts().ObjC)
2414     return false;
2415 
2416   // The set of qualifiers on the type we're converting from.
2417   Qualifiers FromQualifiers = FromType.getQualifiers();
2418 
2419   // First, we handle all conversions on ObjC object pointer types.
2420   const ObjCObjectPointerType* ToObjCPtr =
2421     ToType->getAs<ObjCObjectPointerType>();
2422   const ObjCObjectPointerType *FromObjCPtr =
2423     FromType->getAs<ObjCObjectPointerType>();
2424 
2425   if (ToObjCPtr && FromObjCPtr) {
2426     // If the pointee types are the same (ignoring qualifications),
2427     // then this is not a pointer conversion.
2428     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2429                                        FromObjCPtr->getPointeeType()))
2430       return false;
2431 
2432     // Conversion between Objective-C pointers.
2433     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2434       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2435       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2436       if (getLangOpts().CPlusPlus && LHS && RHS &&
2437           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2438                                                 FromObjCPtr->getPointeeType()))
2439         return false;
2440       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2441                                                    ToObjCPtr->getPointeeType(),
2442                                                          ToType, Context);
2443       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2444       return true;
2445     }
2446 
2447     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2448       // Okay: this is some kind of implicit downcast of Objective-C
2449       // interfaces, which is permitted. However, we're going to
2450       // complain about it.
2451       IncompatibleObjC = true;
2452       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2453                                                    ToObjCPtr->getPointeeType(),
2454                                                          ToType, Context);
2455       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2456       return true;
2457     }
2458   }
2459   // Beyond this point, both types need to be C pointers or block pointers.
2460   QualType ToPointeeType;
2461   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2462     ToPointeeType = ToCPtr->getPointeeType();
2463   else if (const BlockPointerType *ToBlockPtr =
2464             ToType->getAs<BlockPointerType>()) {
2465     // Objective C++: We're able to convert from a pointer to any object
2466     // to a block pointer type.
2467     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2468       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2469       return true;
2470     }
2471     ToPointeeType = ToBlockPtr->getPointeeType();
2472   }
2473   else if (FromType->getAs<BlockPointerType>() &&
2474            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2475     // Objective C++: We're able to convert from a block pointer type to a
2476     // pointer to any object.
2477     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2478     return true;
2479   }
2480   else
2481     return false;
2482 
2483   QualType FromPointeeType;
2484   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2485     FromPointeeType = FromCPtr->getPointeeType();
2486   else if (const BlockPointerType *FromBlockPtr =
2487            FromType->getAs<BlockPointerType>())
2488     FromPointeeType = FromBlockPtr->getPointeeType();
2489   else
2490     return false;
2491 
2492   // If we have pointers to pointers, recursively check whether this
2493   // is an Objective-C conversion.
2494   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2495       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2496                               IncompatibleObjC)) {
2497     // We always complain about this conversion.
2498     IncompatibleObjC = true;
2499     ConvertedType = Context.getPointerType(ConvertedType);
2500     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2501     return true;
2502   }
2503   // Allow conversion of pointee being objective-c pointer to another one;
2504   // as in I* to id.
2505   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2506       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2507       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2508                               IncompatibleObjC)) {
2509 
2510     ConvertedType = Context.getPointerType(ConvertedType);
2511     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2512     return true;
2513   }
2514 
2515   // If we have pointers to functions or blocks, check whether the only
2516   // differences in the argument and result types are in Objective-C
2517   // pointer conversions. If so, we permit the conversion (but
2518   // complain about it).
2519   const FunctionProtoType *FromFunctionType
2520     = FromPointeeType->getAs<FunctionProtoType>();
2521   const FunctionProtoType *ToFunctionType
2522     = ToPointeeType->getAs<FunctionProtoType>();
2523   if (FromFunctionType && ToFunctionType) {
2524     // If the function types are exactly the same, this isn't an
2525     // Objective-C pointer conversion.
2526     if (Context.getCanonicalType(FromPointeeType)
2527           == Context.getCanonicalType(ToPointeeType))
2528       return false;
2529 
2530     // Perform the quick checks that will tell us whether these
2531     // function types are obviously different.
2532     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2533         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2534         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2535       return false;
2536 
2537     bool HasObjCConversion = false;
2538     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2539         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2540       // Okay, the types match exactly. Nothing to do.
2541     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2542                                        ToFunctionType->getReturnType(),
2543                                        ConvertedType, IncompatibleObjC)) {
2544       // Okay, we have an Objective-C pointer conversion.
2545       HasObjCConversion = true;
2546     } else {
2547       // Function types are too different. Abort.
2548       return false;
2549     }
2550 
2551     // Check argument types.
2552     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2553          ArgIdx != NumArgs; ++ArgIdx) {
2554       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2555       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2556       if (Context.getCanonicalType(FromArgType)
2557             == Context.getCanonicalType(ToArgType)) {
2558         // Okay, the types match exactly. Nothing to do.
2559       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2560                                          ConvertedType, IncompatibleObjC)) {
2561         // Okay, we have an Objective-C pointer conversion.
2562         HasObjCConversion = true;
2563       } else {
2564         // Argument types are too different. Abort.
2565         return false;
2566       }
2567     }
2568 
2569     if (HasObjCConversion) {
2570       // We had an Objective-C conversion. Allow this pointer
2571       // conversion, but complain about it.
2572       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2573       IncompatibleObjC = true;
2574       return true;
2575     }
2576   }
2577 
2578   return false;
2579 }
2580 
2581 /// Determine whether this is an Objective-C writeback conversion,
2582 /// used for parameter passing when performing automatic reference counting.
2583 ///
2584 /// \param FromType The type we're converting form.
2585 ///
2586 /// \param ToType The type we're converting to.
2587 ///
2588 /// \param ConvertedType The type that will be produced after applying
2589 /// this conversion.
2590 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2591                                      QualType &ConvertedType) {
2592   if (!getLangOpts().ObjCAutoRefCount ||
2593       Context.hasSameUnqualifiedType(FromType, ToType))
2594     return false;
2595 
2596   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2597   QualType ToPointee;
2598   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2599     ToPointee = ToPointer->getPointeeType();
2600   else
2601     return false;
2602 
2603   Qualifiers ToQuals = ToPointee.getQualifiers();
2604   if (!ToPointee->isObjCLifetimeType() ||
2605       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2606       !ToQuals.withoutObjCLifetime().empty())
2607     return false;
2608 
2609   // Argument must be a pointer to __strong to __weak.
2610   QualType FromPointee;
2611   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2612     FromPointee = FromPointer->getPointeeType();
2613   else
2614     return false;
2615 
2616   Qualifiers FromQuals = FromPointee.getQualifiers();
2617   if (!FromPointee->isObjCLifetimeType() ||
2618       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2619        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2620     return false;
2621 
2622   // Make sure that we have compatible qualifiers.
2623   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2624   if (!ToQuals.compatiblyIncludes(FromQuals))
2625     return false;
2626 
2627   // Remove qualifiers from the pointee type we're converting from; they
2628   // aren't used in the compatibility check belong, and we'll be adding back
2629   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2630   FromPointee = FromPointee.getUnqualifiedType();
2631 
2632   // The unqualified form of the pointee types must be compatible.
2633   ToPointee = ToPointee.getUnqualifiedType();
2634   bool IncompatibleObjC;
2635   if (Context.typesAreCompatible(FromPointee, ToPointee))
2636     FromPointee = ToPointee;
2637   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2638                                     IncompatibleObjC))
2639     return false;
2640 
2641   /// Construct the type we're converting to, which is a pointer to
2642   /// __autoreleasing pointee.
2643   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2644   ConvertedType = Context.getPointerType(FromPointee);
2645   return true;
2646 }
2647 
2648 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2649                                     QualType& ConvertedType) {
2650   QualType ToPointeeType;
2651   if (const BlockPointerType *ToBlockPtr =
2652         ToType->getAs<BlockPointerType>())
2653     ToPointeeType = ToBlockPtr->getPointeeType();
2654   else
2655     return false;
2656 
2657   QualType FromPointeeType;
2658   if (const BlockPointerType *FromBlockPtr =
2659       FromType->getAs<BlockPointerType>())
2660     FromPointeeType = FromBlockPtr->getPointeeType();
2661   else
2662     return false;
2663   // We have pointer to blocks, check whether the only
2664   // differences in the argument and result types are in Objective-C
2665   // pointer conversions. If so, we permit the conversion.
2666 
2667   const FunctionProtoType *FromFunctionType
2668     = FromPointeeType->getAs<FunctionProtoType>();
2669   const FunctionProtoType *ToFunctionType
2670     = ToPointeeType->getAs<FunctionProtoType>();
2671 
2672   if (!FromFunctionType || !ToFunctionType)
2673     return false;
2674 
2675   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2676     return true;
2677 
2678   // Perform the quick checks that will tell us whether these
2679   // function types are obviously different.
2680   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2681       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2682     return false;
2683 
2684   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2685   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2686   if (FromEInfo != ToEInfo)
2687     return false;
2688 
2689   bool IncompatibleObjC = false;
2690   if (Context.hasSameType(FromFunctionType->getReturnType(),
2691                           ToFunctionType->getReturnType())) {
2692     // Okay, the types match exactly. Nothing to do.
2693   } else {
2694     QualType RHS = FromFunctionType->getReturnType();
2695     QualType LHS = ToFunctionType->getReturnType();
2696     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2697         !RHS.hasQualifiers() && LHS.hasQualifiers())
2698        LHS = LHS.getUnqualifiedType();
2699 
2700      if (Context.hasSameType(RHS,LHS)) {
2701        // OK exact match.
2702      } else if (isObjCPointerConversion(RHS, LHS,
2703                                         ConvertedType, IncompatibleObjC)) {
2704      if (IncompatibleObjC)
2705        return false;
2706      // Okay, we have an Objective-C pointer conversion.
2707      }
2708      else
2709        return false;
2710    }
2711 
2712    // Check argument types.
2713    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2714         ArgIdx != NumArgs; ++ArgIdx) {
2715      IncompatibleObjC = false;
2716      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2717      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2718      if (Context.hasSameType(FromArgType, ToArgType)) {
2719        // Okay, the types match exactly. Nothing to do.
2720      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2721                                         ConvertedType, IncompatibleObjC)) {
2722        if (IncompatibleObjC)
2723          return false;
2724        // Okay, we have an Objective-C pointer conversion.
2725      } else
2726        // Argument types are too different. Abort.
2727        return false;
2728    }
2729 
2730    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2731    bool CanUseToFPT, CanUseFromFPT;
2732    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2733                                       CanUseToFPT, CanUseFromFPT,
2734                                       NewParamInfos))
2735      return false;
2736 
2737    ConvertedType = ToType;
2738    return true;
2739 }
2740 
2741 enum {
2742   ft_default,
2743   ft_different_class,
2744   ft_parameter_arity,
2745   ft_parameter_mismatch,
2746   ft_return_type,
2747   ft_qualifer_mismatch,
2748   ft_noexcept
2749 };
2750 
2751 /// Attempts to get the FunctionProtoType from a Type. Handles
2752 /// MemberFunctionPointers properly.
2753 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2754   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2755     return FPT;
2756 
2757   if (auto *MPT = FromType->getAs<MemberPointerType>())
2758     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2759 
2760   return nullptr;
2761 }
2762 
2763 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2764 /// function types.  Catches different number of parameter, mismatch in
2765 /// parameter types, and different return types.
2766 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2767                                       QualType FromType, QualType ToType) {
2768   // If either type is not valid, include no extra info.
2769   if (FromType.isNull() || ToType.isNull()) {
2770     PDiag << ft_default;
2771     return;
2772   }
2773 
2774   // Get the function type from the pointers.
2775   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2776     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2777                             *ToMember = ToType->getAs<MemberPointerType>();
2778     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2779       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2780             << QualType(FromMember->getClass(), 0);
2781       return;
2782     }
2783     FromType = FromMember->getPointeeType();
2784     ToType = ToMember->getPointeeType();
2785   }
2786 
2787   if (FromType->isPointerType())
2788     FromType = FromType->getPointeeType();
2789   if (ToType->isPointerType())
2790     ToType = ToType->getPointeeType();
2791 
2792   // Remove references.
2793   FromType = FromType.getNonReferenceType();
2794   ToType = ToType.getNonReferenceType();
2795 
2796   // Don't print extra info for non-specialized template functions.
2797   if (FromType->isInstantiationDependentType() &&
2798       !FromType->getAs<TemplateSpecializationType>()) {
2799     PDiag << ft_default;
2800     return;
2801   }
2802 
2803   // No extra info for same types.
2804   if (Context.hasSameType(FromType, ToType)) {
2805     PDiag << ft_default;
2806     return;
2807   }
2808 
2809   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2810                           *ToFunction = tryGetFunctionProtoType(ToType);
2811 
2812   // Both types need to be function types.
2813   if (!FromFunction || !ToFunction) {
2814     PDiag << ft_default;
2815     return;
2816   }
2817 
2818   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2819     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2820           << FromFunction->getNumParams();
2821     return;
2822   }
2823 
2824   // Handle different parameter types.
2825   unsigned ArgPos;
2826   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2827     PDiag << ft_parameter_mismatch << ArgPos + 1
2828           << ToFunction->getParamType(ArgPos)
2829           << FromFunction->getParamType(ArgPos);
2830     return;
2831   }
2832 
2833   // Handle different return type.
2834   if (!Context.hasSameType(FromFunction->getReturnType(),
2835                            ToFunction->getReturnType())) {
2836     PDiag << ft_return_type << ToFunction->getReturnType()
2837           << FromFunction->getReturnType();
2838     return;
2839   }
2840 
2841   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2842     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2843           << FromFunction->getMethodQuals();
2844     return;
2845   }
2846 
2847   // Handle exception specification differences on canonical type (in C++17
2848   // onwards).
2849   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2850           ->isNothrow() !=
2851       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2852           ->isNothrow()) {
2853     PDiag << ft_noexcept;
2854     return;
2855   }
2856 
2857   // Unable to find a difference, so add no extra info.
2858   PDiag << ft_default;
2859 }
2860 
2861 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2862 /// for equality of their argument types. Caller has already checked that
2863 /// they have same number of arguments.  If the parameters are different,
2864 /// ArgPos will have the parameter index of the first different parameter.
2865 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2866                                       const FunctionProtoType *NewType,
2867                                       unsigned *ArgPos) {
2868   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2869                                               N = NewType->param_type_begin(),
2870                                               E = OldType->param_type_end();
2871        O && (O != E); ++O, ++N) {
2872     if (!Context.hasSameType(O->getUnqualifiedType(),
2873                              N->getUnqualifiedType())) {
2874       if (ArgPos)
2875         *ArgPos = O - OldType->param_type_begin();
2876       return false;
2877     }
2878   }
2879   return true;
2880 }
2881 
2882 /// CheckPointerConversion - Check the pointer conversion from the
2883 /// expression From to the type ToType. This routine checks for
2884 /// ambiguous or inaccessible derived-to-base pointer
2885 /// conversions for which IsPointerConversion has already returned
2886 /// true. It returns true and produces a diagnostic if there was an
2887 /// error, or returns false otherwise.
2888 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2889                                   CastKind &Kind,
2890                                   CXXCastPath& BasePath,
2891                                   bool IgnoreBaseAccess,
2892                                   bool Diagnose) {
2893   QualType FromType = From->getType();
2894   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2895 
2896   Kind = CK_BitCast;
2897 
2898   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2899       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2900           Expr::NPCK_ZeroExpression) {
2901     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2902       DiagRuntimeBehavior(From->getExprLoc(), From,
2903                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2904                             << ToType << From->getSourceRange());
2905     else if (!isUnevaluatedContext())
2906       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2907         << ToType << From->getSourceRange();
2908   }
2909   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2910     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2911       QualType FromPointeeType = FromPtrType->getPointeeType(),
2912                ToPointeeType   = ToPtrType->getPointeeType();
2913 
2914       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2915           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2916         // We must have a derived-to-base conversion. Check an
2917         // ambiguous or inaccessible conversion.
2918         unsigned InaccessibleID = 0;
2919         unsigned AmbigiousID = 0;
2920         if (Diagnose) {
2921           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2922           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2923         }
2924         if (CheckDerivedToBaseConversion(
2925                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2926                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2927                 &BasePath, IgnoreBaseAccess))
2928           return true;
2929 
2930         // The conversion was successful.
2931         Kind = CK_DerivedToBase;
2932       }
2933 
2934       if (Diagnose && !IsCStyleOrFunctionalCast &&
2935           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2936         assert(getLangOpts().MSVCCompat &&
2937                "this should only be possible with MSVCCompat!");
2938         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2939             << From->getSourceRange();
2940       }
2941     }
2942   } else if (const ObjCObjectPointerType *ToPtrType =
2943                ToType->getAs<ObjCObjectPointerType>()) {
2944     if (const ObjCObjectPointerType *FromPtrType =
2945           FromType->getAs<ObjCObjectPointerType>()) {
2946       // Objective-C++ conversions are always okay.
2947       // FIXME: We should have a different class of conversions for the
2948       // Objective-C++ implicit conversions.
2949       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2950         return false;
2951     } else if (FromType->isBlockPointerType()) {
2952       Kind = CK_BlockPointerToObjCPointerCast;
2953     } else {
2954       Kind = CK_CPointerToObjCPointerCast;
2955     }
2956   } else if (ToType->isBlockPointerType()) {
2957     if (!FromType->isBlockPointerType())
2958       Kind = CK_AnyPointerToBlockPointerCast;
2959   }
2960 
2961   // We shouldn't fall into this case unless it's valid for other
2962   // reasons.
2963   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2964     Kind = CK_NullToPointer;
2965 
2966   return false;
2967 }
2968 
2969 /// IsMemberPointerConversion - Determines whether the conversion of the
2970 /// expression From, which has the (possibly adjusted) type FromType, can be
2971 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2972 /// If so, returns true and places the converted type (that might differ from
2973 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2974 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2975                                      QualType ToType,
2976                                      bool InOverloadResolution,
2977                                      QualType &ConvertedType) {
2978   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2979   if (!ToTypePtr)
2980     return false;
2981 
2982   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2983   if (From->isNullPointerConstant(Context,
2984                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2985                                         : Expr::NPC_ValueDependentIsNull)) {
2986     ConvertedType = ToType;
2987     return true;
2988   }
2989 
2990   // Otherwise, both types have to be member pointers.
2991   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2992   if (!FromTypePtr)
2993     return false;
2994 
2995   // A pointer to member of B can be converted to a pointer to member of D,
2996   // where D is derived from B (C++ 4.11p2).
2997   QualType FromClass(FromTypePtr->getClass(), 0);
2998   QualType ToClass(ToTypePtr->getClass(), 0);
2999 
3000   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3001       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3002     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3003                                                  ToClass.getTypePtr());
3004     return true;
3005   }
3006 
3007   return false;
3008 }
3009 
3010 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3011 /// expression From to the type ToType. This routine checks for ambiguous or
3012 /// virtual or inaccessible base-to-derived member pointer conversions
3013 /// for which IsMemberPointerConversion has already returned true. It returns
3014 /// true and produces a diagnostic if there was an error, or returns false
3015 /// otherwise.
3016 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3017                                         CastKind &Kind,
3018                                         CXXCastPath &BasePath,
3019                                         bool IgnoreBaseAccess) {
3020   QualType FromType = From->getType();
3021   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3022   if (!FromPtrType) {
3023     // This must be a null pointer to member pointer conversion
3024     assert(From->isNullPointerConstant(Context,
3025                                        Expr::NPC_ValueDependentIsNull) &&
3026            "Expr must be null pointer constant!");
3027     Kind = CK_NullToMemberPointer;
3028     return false;
3029   }
3030 
3031   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3032   assert(ToPtrType && "No member pointer cast has a target type "
3033                       "that is not a member pointer.");
3034 
3035   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3036   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3037 
3038   // FIXME: What about dependent types?
3039   assert(FromClass->isRecordType() && "Pointer into non-class.");
3040   assert(ToClass->isRecordType() && "Pointer into non-class.");
3041 
3042   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3043                      /*DetectVirtual=*/true);
3044   bool DerivationOkay =
3045       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3046   assert(DerivationOkay &&
3047          "Should not have been called if derivation isn't OK.");
3048   (void)DerivationOkay;
3049 
3050   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3051                                   getUnqualifiedType())) {
3052     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3053     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3054       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3055     return true;
3056   }
3057 
3058   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3059     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3060       << FromClass << ToClass << QualType(VBase, 0)
3061       << From->getSourceRange();
3062     return true;
3063   }
3064 
3065   if (!IgnoreBaseAccess)
3066     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3067                          Paths.front(),
3068                          diag::err_downcast_from_inaccessible_base);
3069 
3070   // Must be a base to derived member conversion.
3071   BuildBasePathArray(Paths, BasePath);
3072   Kind = CK_BaseToDerivedMemberPointer;
3073   return false;
3074 }
3075 
3076 /// Determine whether the lifetime conversion between the two given
3077 /// qualifiers sets is nontrivial.
3078 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3079                                                Qualifiers ToQuals) {
3080   // Converting anything to const __unsafe_unretained is trivial.
3081   if (ToQuals.hasConst() &&
3082       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3083     return false;
3084 
3085   return true;
3086 }
3087 
3088 /// IsQualificationConversion - Determines whether the conversion from
3089 /// an rvalue of type FromType to ToType is a qualification conversion
3090 /// (C++ 4.4).
3091 ///
3092 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3093 /// when the qualification conversion involves a change in the Objective-C
3094 /// object lifetime.
3095 bool
3096 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3097                                 bool CStyle, bool &ObjCLifetimeConversion) {
3098   FromType = Context.getCanonicalType(FromType);
3099   ToType = Context.getCanonicalType(ToType);
3100   ObjCLifetimeConversion = false;
3101 
3102   // If FromType and ToType are the same type, this is not a
3103   // qualification conversion.
3104   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3105     return false;
3106 
3107   // (C++ 4.4p4):
3108   //   A conversion can add cv-qualifiers at levels other than the first
3109   //   in multi-level pointers, subject to the following rules: [...]
3110   bool PreviousToQualsIncludeConst = true;
3111   bool UnwrappedAnyPointer = false;
3112   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3113     // Within each iteration of the loop, we check the qualifiers to
3114     // determine if this still looks like a qualification
3115     // conversion. Then, if all is well, we unwrap one more level of
3116     // pointers or pointers-to-members and do it all again
3117     // until there are no more pointers or pointers-to-members left to
3118     // unwrap.
3119     UnwrappedAnyPointer = true;
3120 
3121     Qualifiers FromQuals = FromType.getQualifiers();
3122     Qualifiers ToQuals = ToType.getQualifiers();
3123 
3124     // Ignore __unaligned qualifier if this type is void.
3125     if (ToType.getUnqualifiedType()->isVoidType())
3126       FromQuals.removeUnaligned();
3127 
3128     // Objective-C ARC:
3129     //   Check Objective-C lifetime conversions.
3130     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3131         UnwrappedAnyPointer) {
3132       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3133         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3134           ObjCLifetimeConversion = true;
3135         FromQuals.removeObjCLifetime();
3136         ToQuals.removeObjCLifetime();
3137       } else {
3138         // Qualification conversions cannot cast between different
3139         // Objective-C lifetime qualifiers.
3140         return false;
3141       }
3142     }
3143 
3144     // Allow addition/removal of GC attributes but not changing GC attributes.
3145     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3146         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3147       FromQuals.removeObjCGCAttr();
3148       ToQuals.removeObjCGCAttr();
3149     }
3150 
3151     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3152     //      2,j, and similarly for volatile.
3153     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3154       return false;
3155 
3156     //   -- if the cv 1,j and cv 2,j are different, then const is in
3157     //      every cv for 0 < k < j.
3158     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3159         && !PreviousToQualsIncludeConst)
3160       return false;
3161 
3162     // Keep track of whether all prior cv-qualifiers in the "to" type
3163     // include const.
3164     PreviousToQualsIncludeConst
3165       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3166   }
3167 
3168   // Allows address space promotion by language rules implemented in
3169   // Type::Qualifiers::isAddressSpaceSupersetOf.
3170   Qualifiers FromQuals = FromType.getQualifiers();
3171   Qualifiers ToQuals = ToType.getQualifiers();
3172   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3173       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3174     return false;
3175   }
3176 
3177   // We are left with FromType and ToType being the pointee types
3178   // after unwrapping the original FromType and ToType the same number
3179   // of types. If we unwrapped any pointers, and if FromType and
3180   // ToType have the same unqualified type (since we checked
3181   // qualifiers above), then this is a qualification conversion.
3182   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3183 }
3184 
3185 /// - Determine whether this is a conversion from a scalar type to an
3186 /// atomic type.
3187 ///
3188 /// If successful, updates \c SCS's second and third steps in the conversion
3189 /// sequence to finish the conversion.
3190 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3191                                 bool InOverloadResolution,
3192                                 StandardConversionSequence &SCS,
3193                                 bool CStyle) {
3194   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3195   if (!ToAtomic)
3196     return false;
3197 
3198   StandardConversionSequence InnerSCS;
3199   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3200                             InOverloadResolution, InnerSCS,
3201                             CStyle, /*AllowObjCWritebackConversion=*/false))
3202     return false;
3203 
3204   SCS.Second = InnerSCS.Second;
3205   SCS.setToType(1, InnerSCS.getToType(1));
3206   SCS.Third = InnerSCS.Third;
3207   SCS.QualificationIncludesObjCLifetime
3208     = InnerSCS.QualificationIncludesObjCLifetime;
3209   SCS.setToType(2, InnerSCS.getToType(2));
3210   return true;
3211 }
3212 
3213 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3214                                               CXXConstructorDecl *Constructor,
3215                                               QualType Type) {
3216   const FunctionProtoType *CtorType =
3217       Constructor->getType()->getAs<FunctionProtoType>();
3218   if (CtorType->getNumParams() > 0) {
3219     QualType FirstArg = CtorType->getParamType(0);
3220     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3221       return true;
3222   }
3223   return false;
3224 }
3225 
3226 static OverloadingResult
3227 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3228                                        CXXRecordDecl *To,
3229                                        UserDefinedConversionSequence &User,
3230                                        OverloadCandidateSet &CandidateSet,
3231                                        bool AllowExplicit) {
3232   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3233   for (auto *D : S.LookupConstructors(To)) {
3234     auto Info = getConstructorInfo(D);
3235     if (!Info)
3236       continue;
3237 
3238     bool Usable = !Info.Constructor->isInvalidDecl() &&
3239                   S.isInitListConstructor(Info.Constructor) &&
3240                   (AllowExplicit || !Info.Constructor->isExplicit());
3241     if (Usable) {
3242       // If the first argument is (a reference to) the target type,
3243       // suppress conversions.
3244       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3245           S.Context, Info.Constructor, ToType);
3246       if (Info.ConstructorTmpl)
3247         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3248                                        /*ExplicitArgs*/ nullptr, From,
3249                                        CandidateSet, SuppressUserConversions,
3250                                        /*PartialOverloading*/ false,
3251                                        AllowExplicit);
3252       else
3253         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3254                                CandidateSet, SuppressUserConversions,
3255                                /*PartialOverloading*/ false, AllowExplicit);
3256     }
3257   }
3258 
3259   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3260 
3261   OverloadCandidateSet::iterator Best;
3262   switch (auto Result =
3263               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3264   case OR_Deleted:
3265   case OR_Success: {
3266     // Record the standard conversion we used and the conversion function.
3267     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3268     QualType ThisType = Constructor->getThisType();
3269     // Initializer lists don't have conversions as such.
3270     User.Before.setAsIdentityConversion();
3271     User.HadMultipleCandidates = HadMultipleCandidates;
3272     User.ConversionFunction = Constructor;
3273     User.FoundConversionFunction = Best->FoundDecl;
3274     User.After.setAsIdentityConversion();
3275     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3276     User.After.setAllToTypes(ToType);
3277     return Result;
3278   }
3279 
3280   case OR_No_Viable_Function:
3281     return OR_No_Viable_Function;
3282   case OR_Ambiguous:
3283     return OR_Ambiguous;
3284   }
3285 
3286   llvm_unreachable("Invalid OverloadResult!");
3287 }
3288 
3289 /// Determines whether there is a user-defined conversion sequence
3290 /// (C++ [over.ics.user]) that converts expression From to the type
3291 /// ToType. If such a conversion exists, User will contain the
3292 /// user-defined conversion sequence that performs such a conversion
3293 /// and this routine will return true. Otherwise, this routine returns
3294 /// false and User is unspecified.
3295 ///
3296 /// \param AllowExplicit  true if the conversion should consider C++0x
3297 /// "explicit" conversion functions as well as non-explicit conversion
3298 /// functions (C++0x [class.conv.fct]p2).
3299 ///
3300 /// \param AllowObjCConversionOnExplicit true if the conversion should
3301 /// allow an extra Objective-C pointer conversion on uses of explicit
3302 /// constructors. Requires \c AllowExplicit to also be set.
3303 static OverloadingResult
3304 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3305                         UserDefinedConversionSequence &User,
3306                         OverloadCandidateSet &CandidateSet,
3307                         bool AllowExplicit,
3308                         bool AllowObjCConversionOnExplicit) {
3309   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3310   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3311 
3312   // Whether we will only visit constructors.
3313   bool ConstructorsOnly = false;
3314 
3315   // If the type we are conversion to is a class type, enumerate its
3316   // constructors.
3317   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3318     // C++ [over.match.ctor]p1:
3319     //   When objects of class type are direct-initialized (8.5), or
3320     //   copy-initialized from an expression of the same or a
3321     //   derived class type (8.5), overload resolution selects the
3322     //   constructor. [...] For copy-initialization, the candidate
3323     //   functions are all the converting constructors (12.3.1) of
3324     //   that class. The argument list is the expression-list within
3325     //   the parentheses of the initializer.
3326     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3327         (From->getType()->getAs<RecordType>() &&
3328          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3329       ConstructorsOnly = true;
3330 
3331     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3332       // We're not going to find any constructors.
3333     } else if (CXXRecordDecl *ToRecordDecl
3334                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3335 
3336       Expr **Args = &From;
3337       unsigned NumArgs = 1;
3338       bool ListInitializing = false;
3339       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3340         // But first, see if there is an init-list-constructor that will work.
3341         OverloadingResult Result = IsInitializerListConstructorConversion(
3342             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3343         if (Result != OR_No_Viable_Function)
3344           return Result;
3345         // Never mind.
3346         CandidateSet.clear(
3347             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3348 
3349         // If we're list-initializing, we pass the individual elements as
3350         // arguments, not the entire list.
3351         Args = InitList->getInits();
3352         NumArgs = InitList->getNumInits();
3353         ListInitializing = true;
3354       }
3355 
3356       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3357         auto Info = getConstructorInfo(D);
3358         if (!Info)
3359           continue;
3360 
3361         bool Usable = !Info.Constructor->isInvalidDecl();
3362         if (ListInitializing)
3363           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3364         else
3365           Usable = Usable &&
3366                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3367         if (Usable) {
3368           bool SuppressUserConversions = !ConstructorsOnly;
3369           if (SuppressUserConversions && ListInitializing) {
3370             SuppressUserConversions = false;
3371             if (NumArgs == 1) {
3372               // If the first argument is (a reference to) the target type,
3373               // suppress conversions.
3374               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3375                   S.Context, Info.Constructor, ToType);
3376             }
3377           }
3378           if (Info.ConstructorTmpl)
3379             S.AddTemplateOverloadCandidate(
3380                 Info.ConstructorTmpl, Info.FoundDecl,
3381                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3382                 CandidateSet, SuppressUserConversions,
3383                 /*PartialOverloading*/ false, AllowExplicit);
3384           else
3385             // Allow one user-defined conversion when user specifies a
3386             // From->ToType conversion via an static cast (c-style, etc).
3387             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3388                                    llvm::makeArrayRef(Args, NumArgs),
3389                                    CandidateSet, SuppressUserConversions,
3390                                    /*PartialOverloading*/ false, AllowExplicit);
3391         }
3392       }
3393     }
3394   }
3395 
3396   // Enumerate conversion functions, if we're allowed to.
3397   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3398   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3399     // No conversion functions from incomplete types.
3400   } else if (const RecordType *FromRecordType =
3401                  From->getType()->getAs<RecordType>()) {
3402     if (CXXRecordDecl *FromRecordDecl
3403          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3404       // Add all of the conversion functions as candidates.
3405       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3406       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3407         DeclAccessPair FoundDecl = I.getPair();
3408         NamedDecl *D = FoundDecl.getDecl();
3409         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3410         if (isa<UsingShadowDecl>(D))
3411           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3412 
3413         CXXConversionDecl *Conv;
3414         FunctionTemplateDecl *ConvTemplate;
3415         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3416           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3417         else
3418           Conv = cast<CXXConversionDecl>(D);
3419 
3420         if (AllowExplicit || !Conv->isExplicit()) {
3421           if (ConvTemplate)
3422             S.AddTemplateConversionCandidate(
3423                 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3424                 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3425           else
3426             S.AddConversionCandidate(
3427                 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3428                 AllowObjCConversionOnExplicit, AllowExplicit);
3429         }
3430       }
3431     }
3432   }
3433 
3434   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3435 
3436   OverloadCandidateSet::iterator Best;
3437   switch (auto Result =
3438               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3439   case OR_Success:
3440   case OR_Deleted:
3441     // Record the standard conversion we used and the conversion function.
3442     if (CXXConstructorDecl *Constructor
3443           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3444       // C++ [over.ics.user]p1:
3445       //   If the user-defined conversion is specified by a
3446       //   constructor (12.3.1), the initial standard conversion
3447       //   sequence converts the source type to the type required by
3448       //   the argument of the constructor.
3449       //
3450       QualType ThisType = Constructor->getThisType();
3451       if (isa<InitListExpr>(From)) {
3452         // Initializer lists don't have conversions as such.
3453         User.Before.setAsIdentityConversion();
3454       } else {
3455         if (Best->Conversions[0].isEllipsis())
3456           User.EllipsisConversion = true;
3457         else {
3458           User.Before = Best->Conversions[0].Standard;
3459           User.EllipsisConversion = false;
3460         }
3461       }
3462       User.HadMultipleCandidates = HadMultipleCandidates;
3463       User.ConversionFunction = Constructor;
3464       User.FoundConversionFunction = Best->FoundDecl;
3465       User.After.setAsIdentityConversion();
3466       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3467       User.After.setAllToTypes(ToType);
3468       return Result;
3469     }
3470     if (CXXConversionDecl *Conversion
3471                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3472       // C++ [over.ics.user]p1:
3473       //
3474       //   [...] If the user-defined conversion is specified by a
3475       //   conversion function (12.3.2), the initial standard
3476       //   conversion sequence converts the source type to the
3477       //   implicit object parameter of the conversion function.
3478       User.Before = Best->Conversions[0].Standard;
3479       User.HadMultipleCandidates = HadMultipleCandidates;
3480       User.ConversionFunction = Conversion;
3481       User.FoundConversionFunction = Best->FoundDecl;
3482       User.EllipsisConversion = false;
3483 
3484       // C++ [over.ics.user]p2:
3485       //   The second standard conversion sequence converts the
3486       //   result of the user-defined conversion to the target type
3487       //   for the sequence. Since an implicit conversion sequence
3488       //   is an initialization, the special rules for
3489       //   initialization by user-defined conversion apply when
3490       //   selecting the best user-defined conversion for a
3491       //   user-defined conversion sequence (see 13.3.3 and
3492       //   13.3.3.1).
3493       User.After = Best->FinalConversion;
3494       return Result;
3495     }
3496     llvm_unreachable("Not a constructor or conversion function?");
3497 
3498   case OR_No_Viable_Function:
3499     return OR_No_Viable_Function;
3500 
3501   case OR_Ambiguous:
3502     return OR_Ambiguous;
3503   }
3504 
3505   llvm_unreachable("Invalid OverloadResult!");
3506 }
3507 
3508 bool
3509 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3510   ImplicitConversionSequence ICS;
3511   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3512                                     OverloadCandidateSet::CSK_Normal);
3513   OverloadingResult OvResult =
3514     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3515                             CandidateSet, false, false);
3516 
3517   if (!(OvResult == OR_Ambiguous ||
3518         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3519     return false;
3520 
3521   auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From);
3522   if (OvResult == OR_Ambiguous)
3523     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3524         << From->getType() << ToType << From->getSourceRange();
3525   else { // OR_No_Viable_Function && !CandidateSet.empty()
3526     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3527                              diag::err_typecheck_nonviable_condition_incomplete,
3528                              From->getType(), From->getSourceRange()))
3529       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3530           << false << From->getType() << From->getSourceRange() << ToType;
3531   }
3532 
3533   CandidateSet.NoteCandidates(
3534                               *this, From, Cands);
3535   return true;
3536 }
3537 
3538 /// Compare the user-defined conversion functions or constructors
3539 /// of two user-defined conversion sequences to determine whether any ordering
3540 /// is possible.
3541 static ImplicitConversionSequence::CompareKind
3542 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3543                            FunctionDecl *Function2) {
3544   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3545     return ImplicitConversionSequence::Indistinguishable;
3546 
3547   // Objective-C++:
3548   //   If both conversion functions are implicitly-declared conversions from
3549   //   a lambda closure type to a function pointer and a block pointer,
3550   //   respectively, always prefer the conversion to a function pointer,
3551   //   because the function pointer is more lightweight and is more likely
3552   //   to keep code working.
3553   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3554   if (!Conv1)
3555     return ImplicitConversionSequence::Indistinguishable;
3556 
3557   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3558   if (!Conv2)
3559     return ImplicitConversionSequence::Indistinguishable;
3560 
3561   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3562     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3563     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3564     if (Block1 != Block2)
3565       return Block1 ? ImplicitConversionSequence::Worse
3566                     : ImplicitConversionSequence::Better;
3567   }
3568 
3569   return ImplicitConversionSequence::Indistinguishable;
3570 }
3571 
3572 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3573     const ImplicitConversionSequence &ICS) {
3574   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3575          (ICS.isUserDefined() &&
3576           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3577 }
3578 
3579 /// CompareImplicitConversionSequences - Compare two implicit
3580 /// conversion sequences to determine whether one is better than the
3581 /// other or if they are indistinguishable (C++ 13.3.3.2).
3582 static ImplicitConversionSequence::CompareKind
3583 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3584                                    const ImplicitConversionSequence& ICS1,
3585                                    const ImplicitConversionSequence& ICS2)
3586 {
3587   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3588   // conversion sequences (as defined in 13.3.3.1)
3589   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3590   //      conversion sequence than a user-defined conversion sequence or
3591   //      an ellipsis conversion sequence, and
3592   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3593   //      conversion sequence than an ellipsis conversion sequence
3594   //      (13.3.3.1.3).
3595   //
3596   // C++0x [over.best.ics]p10:
3597   //   For the purpose of ranking implicit conversion sequences as
3598   //   described in 13.3.3.2, the ambiguous conversion sequence is
3599   //   treated as a user-defined sequence that is indistinguishable
3600   //   from any other user-defined conversion sequence.
3601 
3602   // String literal to 'char *' conversion has been deprecated in C++03. It has
3603   // been removed from C++11. We still accept this conversion, if it happens at
3604   // the best viable function. Otherwise, this conversion is considered worse
3605   // than ellipsis conversion. Consider this as an extension; this is not in the
3606   // standard. For example:
3607   //
3608   // int &f(...);    // #1
3609   // void f(char*);  // #2
3610   // void g() { int &r = f("foo"); }
3611   //
3612   // In C++03, we pick #2 as the best viable function.
3613   // In C++11, we pick #1 as the best viable function, because ellipsis
3614   // conversion is better than string-literal to char* conversion (since there
3615   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3616   // convert arguments, #2 would be the best viable function in C++11.
3617   // If the best viable function has this conversion, a warning will be issued
3618   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3619 
3620   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3621       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3622       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3623     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3624                ? ImplicitConversionSequence::Worse
3625                : ImplicitConversionSequence::Better;
3626 
3627   if (ICS1.getKindRank() < ICS2.getKindRank())
3628     return ImplicitConversionSequence::Better;
3629   if (ICS2.getKindRank() < ICS1.getKindRank())
3630     return ImplicitConversionSequence::Worse;
3631 
3632   // The following checks require both conversion sequences to be of
3633   // the same kind.
3634   if (ICS1.getKind() != ICS2.getKind())
3635     return ImplicitConversionSequence::Indistinguishable;
3636 
3637   ImplicitConversionSequence::CompareKind Result =
3638       ImplicitConversionSequence::Indistinguishable;
3639 
3640   // Two implicit conversion sequences of the same form are
3641   // indistinguishable conversion sequences unless one of the
3642   // following rules apply: (C++ 13.3.3.2p3):
3643 
3644   // List-initialization sequence L1 is a better conversion sequence than
3645   // list-initialization sequence L2 if:
3646   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3647   //   if not that,
3648   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3649   //   and N1 is smaller than N2.,
3650   // even if one of the other rules in this paragraph would otherwise apply.
3651   if (!ICS1.isBad()) {
3652     if (ICS1.isStdInitializerListElement() &&
3653         !ICS2.isStdInitializerListElement())
3654       return ImplicitConversionSequence::Better;
3655     if (!ICS1.isStdInitializerListElement() &&
3656         ICS2.isStdInitializerListElement())
3657       return ImplicitConversionSequence::Worse;
3658   }
3659 
3660   if (ICS1.isStandard())
3661     // Standard conversion sequence S1 is a better conversion sequence than
3662     // standard conversion sequence S2 if [...]
3663     Result = CompareStandardConversionSequences(S, Loc,
3664                                                 ICS1.Standard, ICS2.Standard);
3665   else if (ICS1.isUserDefined()) {
3666     // User-defined conversion sequence U1 is a better conversion
3667     // sequence than another user-defined conversion sequence U2 if
3668     // they contain the same user-defined conversion function or
3669     // constructor and if the second standard conversion sequence of
3670     // U1 is better than the second standard conversion sequence of
3671     // U2 (C++ 13.3.3.2p3).
3672     if (ICS1.UserDefined.ConversionFunction ==
3673           ICS2.UserDefined.ConversionFunction)
3674       Result = CompareStandardConversionSequences(S, Loc,
3675                                                   ICS1.UserDefined.After,
3676                                                   ICS2.UserDefined.After);
3677     else
3678       Result = compareConversionFunctions(S,
3679                                           ICS1.UserDefined.ConversionFunction,
3680                                           ICS2.UserDefined.ConversionFunction);
3681   }
3682 
3683   return Result;
3684 }
3685 
3686 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3687 // determine if one is a proper subset of the other.
3688 static ImplicitConversionSequence::CompareKind
3689 compareStandardConversionSubsets(ASTContext &Context,
3690                                  const StandardConversionSequence& SCS1,
3691                                  const StandardConversionSequence& SCS2) {
3692   ImplicitConversionSequence::CompareKind Result
3693     = ImplicitConversionSequence::Indistinguishable;
3694 
3695   // the identity conversion sequence is considered to be a subsequence of
3696   // any non-identity conversion sequence
3697   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3698     return ImplicitConversionSequence::Better;
3699   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3700     return ImplicitConversionSequence::Worse;
3701 
3702   if (SCS1.Second != SCS2.Second) {
3703     if (SCS1.Second == ICK_Identity)
3704       Result = ImplicitConversionSequence::Better;
3705     else if (SCS2.Second == ICK_Identity)
3706       Result = ImplicitConversionSequence::Worse;
3707     else
3708       return ImplicitConversionSequence::Indistinguishable;
3709   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3710     return ImplicitConversionSequence::Indistinguishable;
3711 
3712   if (SCS1.Third == SCS2.Third) {
3713     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3714                              : ImplicitConversionSequence::Indistinguishable;
3715   }
3716 
3717   if (SCS1.Third == ICK_Identity)
3718     return Result == ImplicitConversionSequence::Worse
3719              ? ImplicitConversionSequence::Indistinguishable
3720              : ImplicitConversionSequence::Better;
3721 
3722   if (SCS2.Third == ICK_Identity)
3723     return Result == ImplicitConversionSequence::Better
3724              ? ImplicitConversionSequence::Indistinguishable
3725              : ImplicitConversionSequence::Worse;
3726 
3727   return ImplicitConversionSequence::Indistinguishable;
3728 }
3729 
3730 /// Determine whether one of the given reference bindings is better
3731 /// than the other based on what kind of bindings they are.
3732 static bool
3733 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3734                              const StandardConversionSequence &SCS2) {
3735   // C++0x [over.ics.rank]p3b4:
3736   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3737   //      implicit object parameter of a non-static member function declared
3738   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3739   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3740   //      lvalue reference to a function lvalue and S2 binds an rvalue
3741   //      reference*.
3742   //
3743   // FIXME: Rvalue references. We're going rogue with the above edits,
3744   // because the semantics in the current C++0x working paper (N3225 at the
3745   // time of this writing) break the standard definition of std::forward
3746   // and std::reference_wrapper when dealing with references to functions.
3747   // Proposed wording changes submitted to CWG for consideration.
3748   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3749       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3750     return false;
3751 
3752   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3753           SCS2.IsLvalueReference) ||
3754          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3755           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3756 }
3757 
3758 /// CompareStandardConversionSequences - Compare two standard
3759 /// conversion sequences to determine whether one is better than the
3760 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3761 static ImplicitConversionSequence::CompareKind
3762 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3763                                    const StandardConversionSequence& SCS1,
3764                                    const StandardConversionSequence& SCS2)
3765 {
3766   // Standard conversion sequence S1 is a better conversion sequence
3767   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3768 
3769   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3770   //     sequences in the canonical form defined by 13.3.3.1.1,
3771   //     excluding any Lvalue Transformation; the identity conversion
3772   //     sequence is considered to be a subsequence of any
3773   //     non-identity conversion sequence) or, if not that,
3774   if (ImplicitConversionSequence::CompareKind CK
3775         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3776     return CK;
3777 
3778   //  -- the rank of S1 is better than the rank of S2 (by the rules
3779   //     defined below), or, if not that,
3780   ImplicitConversionRank Rank1 = SCS1.getRank();
3781   ImplicitConversionRank Rank2 = SCS2.getRank();
3782   if (Rank1 < Rank2)
3783     return ImplicitConversionSequence::Better;
3784   else if (Rank2 < Rank1)
3785     return ImplicitConversionSequence::Worse;
3786 
3787   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3788   // are indistinguishable unless one of the following rules
3789   // applies:
3790 
3791   //   A conversion that is not a conversion of a pointer, or
3792   //   pointer to member, to bool is better than another conversion
3793   //   that is such a conversion.
3794   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3795     return SCS2.isPointerConversionToBool()
3796              ? ImplicitConversionSequence::Better
3797              : ImplicitConversionSequence::Worse;
3798 
3799   // C++ [over.ics.rank]p4b2:
3800   //
3801   //   If class B is derived directly or indirectly from class A,
3802   //   conversion of B* to A* is better than conversion of B* to
3803   //   void*, and conversion of A* to void* is better than conversion
3804   //   of B* to void*.
3805   bool SCS1ConvertsToVoid
3806     = SCS1.isPointerConversionToVoidPointer(S.Context);
3807   bool SCS2ConvertsToVoid
3808     = SCS2.isPointerConversionToVoidPointer(S.Context);
3809   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3810     // Exactly one of the conversion sequences is a conversion to
3811     // a void pointer; it's the worse conversion.
3812     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3813                               : ImplicitConversionSequence::Worse;
3814   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3815     // Neither conversion sequence converts to a void pointer; compare
3816     // their derived-to-base conversions.
3817     if (ImplicitConversionSequence::CompareKind DerivedCK
3818           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3819       return DerivedCK;
3820   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3821              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3822     // Both conversion sequences are conversions to void
3823     // pointers. Compare the source types to determine if there's an
3824     // inheritance relationship in their sources.
3825     QualType FromType1 = SCS1.getFromType();
3826     QualType FromType2 = SCS2.getFromType();
3827 
3828     // Adjust the types we're converting from via the array-to-pointer
3829     // conversion, if we need to.
3830     if (SCS1.First == ICK_Array_To_Pointer)
3831       FromType1 = S.Context.getArrayDecayedType(FromType1);
3832     if (SCS2.First == ICK_Array_To_Pointer)
3833       FromType2 = S.Context.getArrayDecayedType(FromType2);
3834 
3835     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3836     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3837 
3838     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3839       return ImplicitConversionSequence::Better;
3840     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3841       return ImplicitConversionSequence::Worse;
3842 
3843     // Objective-C++: If one interface is more specific than the
3844     // other, it is the better one.
3845     const ObjCObjectPointerType* FromObjCPtr1
3846       = FromType1->getAs<ObjCObjectPointerType>();
3847     const ObjCObjectPointerType* FromObjCPtr2
3848       = FromType2->getAs<ObjCObjectPointerType>();
3849     if (FromObjCPtr1 && FromObjCPtr2) {
3850       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3851                                                           FromObjCPtr2);
3852       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3853                                                            FromObjCPtr1);
3854       if (AssignLeft != AssignRight) {
3855         return AssignLeft? ImplicitConversionSequence::Better
3856                          : ImplicitConversionSequence::Worse;
3857       }
3858     }
3859   }
3860 
3861   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3862   // bullet 3).
3863   if (ImplicitConversionSequence::CompareKind QualCK
3864         = CompareQualificationConversions(S, SCS1, SCS2))
3865     return QualCK;
3866 
3867   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3868     // Check for a better reference binding based on the kind of bindings.
3869     if (isBetterReferenceBindingKind(SCS1, SCS2))
3870       return ImplicitConversionSequence::Better;
3871     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3872       return ImplicitConversionSequence::Worse;
3873 
3874     // C++ [over.ics.rank]p3b4:
3875     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3876     //      which the references refer are the same type except for
3877     //      top-level cv-qualifiers, and the type to which the reference
3878     //      initialized by S2 refers is more cv-qualified than the type
3879     //      to which the reference initialized by S1 refers.
3880     QualType T1 = SCS1.getToType(2);
3881     QualType T2 = SCS2.getToType(2);
3882     T1 = S.Context.getCanonicalType(T1);
3883     T2 = S.Context.getCanonicalType(T2);
3884     Qualifiers T1Quals, T2Quals;
3885     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3886     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3887     if (UnqualT1 == UnqualT2) {
3888       // Objective-C++ ARC: If the references refer to objects with different
3889       // lifetimes, prefer bindings that don't change lifetime.
3890       if (SCS1.ObjCLifetimeConversionBinding !=
3891                                           SCS2.ObjCLifetimeConversionBinding) {
3892         return SCS1.ObjCLifetimeConversionBinding
3893                                            ? ImplicitConversionSequence::Worse
3894                                            : ImplicitConversionSequence::Better;
3895       }
3896 
3897       // If the type is an array type, promote the element qualifiers to the
3898       // type for comparison.
3899       if (isa<ArrayType>(T1) && T1Quals)
3900         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3901       if (isa<ArrayType>(T2) && T2Quals)
3902         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3903       if (T2.isMoreQualifiedThan(T1))
3904         return ImplicitConversionSequence::Better;
3905       else if (T1.isMoreQualifiedThan(T2))
3906         return ImplicitConversionSequence::Worse;
3907     }
3908   }
3909 
3910   // In Microsoft mode, prefer an integral conversion to a
3911   // floating-to-integral conversion if the integral conversion
3912   // is between types of the same size.
3913   // For example:
3914   // void f(float);
3915   // void f(int);
3916   // int main {
3917   //    long a;
3918   //    f(a);
3919   // }
3920   // Here, MSVC will call f(int) instead of generating a compile error
3921   // as clang will do in standard mode.
3922   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3923       SCS2.Second == ICK_Floating_Integral &&
3924       S.Context.getTypeSize(SCS1.getFromType()) ==
3925           S.Context.getTypeSize(SCS1.getToType(2)))
3926     return ImplicitConversionSequence::Better;
3927 
3928   // Prefer a compatible vector conversion over a lax vector conversion
3929   // For example:
3930   //
3931   // typedef float __v4sf __attribute__((__vector_size__(16)));
3932   // void f(vector float);
3933   // void f(vector signed int);
3934   // int main() {
3935   //   __v4sf a;
3936   //   f(a);
3937   // }
3938   // Here, we'd like to choose f(vector float) and not
3939   // report an ambiguous call error
3940   if (SCS1.Second == ICK_Vector_Conversion &&
3941       SCS2.Second == ICK_Vector_Conversion) {
3942     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3943         SCS1.getFromType(), SCS1.getToType(2));
3944     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3945         SCS2.getFromType(), SCS2.getToType(2));
3946 
3947     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3948       return SCS1IsCompatibleVectorConversion
3949                  ? ImplicitConversionSequence::Better
3950                  : ImplicitConversionSequence::Worse;
3951   }
3952 
3953   return ImplicitConversionSequence::Indistinguishable;
3954 }
3955 
3956 /// CompareQualificationConversions - Compares two standard conversion
3957 /// sequences to determine whether they can be ranked based on their
3958 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3959 static ImplicitConversionSequence::CompareKind
3960 CompareQualificationConversions(Sema &S,
3961                                 const StandardConversionSequence& SCS1,
3962                                 const StandardConversionSequence& SCS2) {
3963   // C++ 13.3.3.2p3:
3964   //  -- S1 and S2 differ only in their qualification conversion and
3965   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3966   //     cv-qualification signature of type T1 is a proper subset of
3967   //     the cv-qualification signature of type T2, and S1 is not the
3968   //     deprecated string literal array-to-pointer conversion (4.2).
3969   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3970       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3971     return ImplicitConversionSequence::Indistinguishable;
3972 
3973   // FIXME: the example in the standard doesn't use a qualification
3974   // conversion (!)
3975   QualType T1 = SCS1.getToType(2);
3976   QualType T2 = SCS2.getToType(2);
3977   T1 = S.Context.getCanonicalType(T1);
3978   T2 = S.Context.getCanonicalType(T2);
3979   Qualifiers T1Quals, T2Quals;
3980   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3981   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3982 
3983   // If the types are the same, we won't learn anything by unwrapped
3984   // them.
3985   if (UnqualT1 == UnqualT2)
3986     return ImplicitConversionSequence::Indistinguishable;
3987 
3988   // If the type is an array type, promote the element qualifiers to the type
3989   // for comparison.
3990   if (isa<ArrayType>(T1) && T1Quals)
3991     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3992   if (isa<ArrayType>(T2) && T2Quals)
3993     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3994 
3995   ImplicitConversionSequence::CompareKind Result
3996     = ImplicitConversionSequence::Indistinguishable;
3997 
3998   // Objective-C++ ARC:
3999   //   Prefer qualification conversions not involving a change in lifetime
4000   //   to qualification conversions that do not change lifetime.
4001   if (SCS1.QualificationIncludesObjCLifetime !=
4002                                       SCS2.QualificationIncludesObjCLifetime) {
4003     Result = SCS1.QualificationIncludesObjCLifetime
4004                ? ImplicitConversionSequence::Worse
4005                : ImplicitConversionSequence::Better;
4006   }
4007 
4008   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4009     // Within each iteration of the loop, we check the qualifiers to
4010     // determine if this still looks like a qualification
4011     // conversion. Then, if all is well, we unwrap one more level of
4012     // pointers or pointers-to-members and do it all again
4013     // until there are no more pointers or pointers-to-members left
4014     // to unwrap. This essentially mimics what
4015     // IsQualificationConversion does, but here we're checking for a
4016     // strict subset of qualifiers.
4017     if (T1.getQualifiers().withoutObjCLifetime() ==
4018         T2.getQualifiers().withoutObjCLifetime())
4019       // The qualifiers are the same, so this doesn't tell us anything
4020       // about how the sequences rank.
4021       // ObjC ownership quals are omitted above as they interfere with
4022       // the ARC overload rule.
4023       ;
4024     else if (T2.isMoreQualifiedThan(T1)) {
4025       // T1 has fewer qualifiers, so it could be the better sequence.
4026       if (Result == ImplicitConversionSequence::Worse)
4027         // Neither has qualifiers that are a subset of the other's
4028         // qualifiers.
4029         return ImplicitConversionSequence::Indistinguishable;
4030 
4031       Result = ImplicitConversionSequence::Better;
4032     } else if (T1.isMoreQualifiedThan(T2)) {
4033       // T2 has fewer qualifiers, so it could be the better sequence.
4034       if (Result == ImplicitConversionSequence::Better)
4035         // Neither has qualifiers that are a subset of the other's
4036         // qualifiers.
4037         return ImplicitConversionSequence::Indistinguishable;
4038 
4039       Result = ImplicitConversionSequence::Worse;
4040     } else {
4041       // Qualifiers are disjoint.
4042       return ImplicitConversionSequence::Indistinguishable;
4043     }
4044 
4045     // If the types after this point are equivalent, we're done.
4046     if (S.Context.hasSameUnqualifiedType(T1, T2))
4047       break;
4048   }
4049 
4050   // Check that the winning standard conversion sequence isn't using
4051   // the deprecated string literal array to pointer conversion.
4052   switch (Result) {
4053   case ImplicitConversionSequence::Better:
4054     if (SCS1.DeprecatedStringLiteralToCharPtr)
4055       Result = ImplicitConversionSequence::Indistinguishable;
4056     break;
4057 
4058   case ImplicitConversionSequence::Indistinguishable:
4059     break;
4060 
4061   case ImplicitConversionSequence::Worse:
4062     if (SCS2.DeprecatedStringLiteralToCharPtr)
4063       Result = ImplicitConversionSequence::Indistinguishable;
4064     break;
4065   }
4066 
4067   return Result;
4068 }
4069 
4070 /// CompareDerivedToBaseConversions - Compares two standard conversion
4071 /// sequences to determine whether they can be ranked based on their
4072 /// various kinds of derived-to-base conversions (C++
4073 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4074 /// conversions between Objective-C interface types.
4075 static ImplicitConversionSequence::CompareKind
4076 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4077                                 const StandardConversionSequence& SCS1,
4078                                 const StandardConversionSequence& SCS2) {
4079   QualType FromType1 = SCS1.getFromType();
4080   QualType ToType1 = SCS1.getToType(1);
4081   QualType FromType2 = SCS2.getFromType();
4082   QualType ToType2 = SCS2.getToType(1);
4083 
4084   // Adjust the types we're converting from via the array-to-pointer
4085   // conversion, if we need to.
4086   if (SCS1.First == ICK_Array_To_Pointer)
4087     FromType1 = S.Context.getArrayDecayedType(FromType1);
4088   if (SCS2.First == ICK_Array_To_Pointer)
4089     FromType2 = S.Context.getArrayDecayedType(FromType2);
4090 
4091   // Canonicalize all of the types.
4092   FromType1 = S.Context.getCanonicalType(FromType1);
4093   ToType1 = S.Context.getCanonicalType(ToType1);
4094   FromType2 = S.Context.getCanonicalType(FromType2);
4095   ToType2 = S.Context.getCanonicalType(ToType2);
4096 
4097   // C++ [over.ics.rank]p4b3:
4098   //
4099   //   If class B is derived directly or indirectly from class A and
4100   //   class C is derived directly or indirectly from B,
4101   //
4102   // Compare based on pointer conversions.
4103   if (SCS1.Second == ICK_Pointer_Conversion &&
4104       SCS2.Second == ICK_Pointer_Conversion &&
4105       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4106       FromType1->isPointerType() && FromType2->isPointerType() &&
4107       ToType1->isPointerType() && ToType2->isPointerType()) {
4108     QualType FromPointee1
4109       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4110     QualType ToPointee1
4111       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4112     QualType FromPointee2
4113       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4114     QualType ToPointee2
4115       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4116 
4117     //   -- conversion of C* to B* is better than conversion of C* to A*,
4118     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4119       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4120         return ImplicitConversionSequence::Better;
4121       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4122         return ImplicitConversionSequence::Worse;
4123     }
4124 
4125     //   -- conversion of B* to A* is better than conversion of C* to A*,
4126     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4127       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4128         return ImplicitConversionSequence::Better;
4129       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4130         return ImplicitConversionSequence::Worse;
4131     }
4132   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4133              SCS2.Second == ICK_Pointer_Conversion) {
4134     const ObjCObjectPointerType *FromPtr1
4135       = FromType1->getAs<ObjCObjectPointerType>();
4136     const ObjCObjectPointerType *FromPtr2
4137       = FromType2->getAs<ObjCObjectPointerType>();
4138     const ObjCObjectPointerType *ToPtr1
4139       = ToType1->getAs<ObjCObjectPointerType>();
4140     const ObjCObjectPointerType *ToPtr2
4141       = ToType2->getAs<ObjCObjectPointerType>();
4142 
4143     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4144       // Apply the same conversion ranking rules for Objective-C pointer types
4145       // that we do for C++ pointers to class types. However, we employ the
4146       // Objective-C pseudo-subtyping relationship used for assignment of
4147       // Objective-C pointer types.
4148       bool FromAssignLeft
4149         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4150       bool FromAssignRight
4151         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4152       bool ToAssignLeft
4153         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4154       bool ToAssignRight
4155         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4156 
4157       // A conversion to an a non-id object pointer type or qualified 'id'
4158       // type is better than a conversion to 'id'.
4159       if (ToPtr1->isObjCIdType() &&
4160           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4161         return ImplicitConversionSequence::Worse;
4162       if (ToPtr2->isObjCIdType() &&
4163           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4164         return ImplicitConversionSequence::Better;
4165 
4166       // A conversion to a non-id object pointer type is better than a
4167       // conversion to a qualified 'id' type
4168       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4169         return ImplicitConversionSequence::Worse;
4170       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4171         return ImplicitConversionSequence::Better;
4172 
4173       // A conversion to an a non-Class object pointer type or qualified 'Class'
4174       // type is better than a conversion to 'Class'.
4175       if (ToPtr1->isObjCClassType() &&
4176           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4177         return ImplicitConversionSequence::Worse;
4178       if (ToPtr2->isObjCClassType() &&
4179           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4180         return ImplicitConversionSequence::Better;
4181 
4182       // A conversion to a non-Class object pointer type is better than a
4183       // conversion to a qualified 'Class' type.
4184       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4185         return ImplicitConversionSequence::Worse;
4186       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4187         return ImplicitConversionSequence::Better;
4188 
4189       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4190       if (S.Context.hasSameType(FromType1, FromType2) &&
4191           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4192           (ToAssignLeft != ToAssignRight)) {
4193         if (FromPtr1->isSpecialized()) {
4194           // "conversion of B<A> * to B * is better than conversion of B * to
4195           // C *.
4196           bool IsFirstSame =
4197               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4198           bool IsSecondSame =
4199               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4200           if (IsFirstSame) {
4201             if (!IsSecondSame)
4202               return ImplicitConversionSequence::Better;
4203           } else if (IsSecondSame)
4204             return ImplicitConversionSequence::Worse;
4205         }
4206         return ToAssignLeft? ImplicitConversionSequence::Worse
4207                            : ImplicitConversionSequence::Better;
4208       }
4209 
4210       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4211       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4212           (FromAssignLeft != FromAssignRight))
4213         return FromAssignLeft? ImplicitConversionSequence::Better
4214         : ImplicitConversionSequence::Worse;
4215     }
4216   }
4217 
4218   // Ranking of member-pointer types.
4219   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4220       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4221       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4222     const MemberPointerType * FromMemPointer1 =
4223                                         FromType1->getAs<MemberPointerType>();
4224     const MemberPointerType * ToMemPointer1 =
4225                                           ToType1->getAs<MemberPointerType>();
4226     const MemberPointerType * FromMemPointer2 =
4227                                           FromType2->getAs<MemberPointerType>();
4228     const MemberPointerType * ToMemPointer2 =
4229                                           ToType2->getAs<MemberPointerType>();
4230     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4231     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4232     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4233     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4234     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4235     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4236     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4237     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4238     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4239     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4240       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4241         return ImplicitConversionSequence::Worse;
4242       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4243         return ImplicitConversionSequence::Better;
4244     }
4245     // conversion of B::* to C::* is better than conversion of A::* to C::*
4246     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4247       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4248         return ImplicitConversionSequence::Better;
4249       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4250         return ImplicitConversionSequence::Worse;
4251     }
4252   }
4253 
4254   if (SCS1.Second == ICK_Derived_To_Base) {
4255     //   -- conversion of C to B is better than conversion of C to A,
4256     //   -- binding of an expression of type C to a reference of type
4257     //      B& is better than binding an expression of type C to a
4258     //      reference of type A&,
4259     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4260         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4261       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4262         return ImplicitConversionSequence::Better;
4263       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4264         return ImplicitConversionSequence::Worse;
4265     }
4266 
4267     //   -- conversion of B to A is better than conversion of C to A.
4268     //   -- binding of an expression of type B to a reference of type
4269     //      A& is better than binding an expression of type C to a
4270     //      reference of type A&,
4271     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4272         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4273       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4274         return ImplicitConversionSequence::Better;
4275       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4276         return ImplicitConversionSequence::Worse;
4277     }
4278   }
4279 
4280   return ImplicitConversionSequence::Indistinguishable;
4281 }
4282 
4283 /// Determine whether the given type is valid, e.g., it is not an invalid
4284 /// C++ class.
4285 static bool isTypeValid(QualType T) {
4286   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4287     return !Record->isInvalidDecl();
4288 
4289   return true;
4290 }
4291 
4292 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4293 /// determine whether they are reference-related,
4294 /// reference-compatible, reference-compatible with added
4295 /// qualification, or incompatible, for use in C++ initialization by
4296 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4297 /// type, and the first type (T1) is the pointee type of the reference
4298 /// type being initialized.
4299 Sema::ReferenceCompareResult
4300 Sema::CompareReferenceRelationship(SourceLocation Loc,
4301                                    QualType OrigT1, QualType OrigT2,
4302                                    bool &DerivedToBase,
4303                                    bool &ObjCConversion,
4304                                    bool &ObjCLifetimeConversion) {
4305   assert(!OrigT1->isReferenceType() &&
4306     "T1 must be the pointee type of the reference type");
4307   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4308 
4309   QualType T1 = Context.getCanonicalType(OrigT1);
4310   QualType T2 = Context.getCanonicalType(OrigT2);
4311   Qualifiers T1Quals, T2Quals;
4312   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4313   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4314 
4315   // C++ [dcl.init.ref]p4:
4316   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4317   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4318   //   T1 is a base class of T2.
4319   DerivedToBase = false;
4320   ObjCConversion = false;
4321   ObjCLifetimeConversion = false;
4322   QualType ConvertedT2;
4323   if (UnqualT1 == UnqualT2) {
4324     // Nothing to do.
4325   } else if (isCompleteType(Loc, OrigT2) &&
4326              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4327              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4328     DerivedToBase = true;
4329   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4330            UnqualT2->isObjCObjectOrInterfaceType() &&
4331            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4332     ObjCConversion = true;
4333   else if (UnqualT2->isFunctionType() &&
4334            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4335     // C++1z [dcl.init.ref]p4:
4336     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4337     //   function" and T1 is "function"
4338     //
4339     // We extend this to also apply to 'noreturn', so allow any function
4340     // conversion between function types.
4341     return Ref_Compatible;
4342   else
4343     return Ref_Incompatible;
4344 
4345   // At this point, we know that T1 and T2 are reference-related (at
4346   // least).
4347 
4348   // If the type is an array type, promote the element qualifiers to the type
4349   // for comparison.
4350   if (isa<ArrayType>(T1) && T1Quals)
4351     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4352   if (isa<ArrayType>(T2) && T2Quals)
4353     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4354 
4355   // C++ [dcl.init.ref]p4:
4356   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4357   //   reference-related to T2 and cv1 is the same cv-qualification
4358   //   as, or greater cv-qualification than, cv2. For purposes of
4359   //   overload resolution, cases for which cv1 is greater
4360   //   cv-qualification than cv2 are identified as
4361   //   reference-compatible with added qualification (see 13.3.3.2).
4362   //
4363   // Note that we also require equivalence of Objective-C GC and address-space
4364   // qualifiers when performing these computations, so that e.g., an int in
4365   // address space 1 is not reference-compatible with an int in address
4366   // space 2.
4367   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4368       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4369     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4370       ObjCLifetimeConversion = true;
4371 
4372     T1Quals.removeObjCLifetime();
4373     T2Quals.removeObjCLifetime();
4374   }
4375 
4376   // MS compiler ignores __unaligned qualifier for references; do the same.
4377   T1Quals.removeUnaligned();
4378   T2Quals.removeUnaligned();
4379 
4380   if (T1Quals.compatiblyIncludes(T2Quals))
4381     return Ref_Compatible;
4382   else
4383     return Ref_Related;
4384 }
4385 
4386 /// Look for a user-defined conversion to a value reference-compatible
4387 ///        with DeclType. Return true if something definite is found.
4388 static bool
4389 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4390                          QualType DeclType, SourceLocation DeclLoc,
4391                          Expr *Init, QualType T2, bool AllowRvalues,
4392                          bool AllowExplicit) {
4393   assert(T2->isRecordType() && "Can only find conversions of record types.");
4394   CXXRecordDecl *T2RecordDecl
4395     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4396 
4397   OverloadCandidateSet CandidateSet(
4398       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4399   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4400   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4401     NamedDecl *D = *I;
4402     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4403     if (isa<UsingShadowDecl>(D))
4404       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4405 
4406     FunctionTemplateDecl *ConvTemplate
4407       = dyn_cast<FunctionTemplateDecl>(D);
4408     CXXConversionDecl *Conv;
4409     if (ConvTemplate)
4410       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4411     else
4412       Conv = cast<CXXConversionDecl>(D);
4413 
4414     // If this is an explicit conversion, and we're not allowed to consider
4415     // explicit conversions, skip it.
4416     if (!AllowExplicit && Conv->isExplicit())
4417       continue;
4418 
4419     if (AllowRvalues) {
4420       bool DerivedToBase = false;
4421       bool ObjCConversion = false;
4422       bool ObjCLifetimeConversion = false;
4423 
4424       // If we are initializing an rvalue reference, don't permit conversion
4425       // functions that return lvalues.
4426       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4427         const ReferenceType *RefType
4428           = Conv->getConversionType()->getAs<LValueReferenceType>();
4429         if (RefType && !RefType->getPointeeType()->isFunctionType())
4430           continue;
4431       }
4432 
4433       if (!ConvTemplate &&
4434           S.CompareReferenceRelationship(
4435             DeclLoc,
4436             Conv->getConversionType().getNonReferenceType()
4437               .getUnqualifiedType(),
4438             DeclType.getNonReferenceType().getUnqualifiedType(),
4439             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4440           Sema::Ref_Incompatible)
4441         continue;
4442     } else {
4443       // If the conversion function doesn't return a reference type,
4444       // it can't be considered for this conversion. An rvalue reference
4445       // is only acceptable if its referencee is a function type.
4446 
4447       const ReferenceType *RefType =
4448         Conv->getConversionType()->getAs<ReferenceType>();
4449       if (!RefType ||
4450           (!RefType->isLValueReferenceType() &&
4451            !RefType->getPointeeType()->isFunctionType()))
4452         continue;
4453     }
4454 
4455     if (ConvTemplate)
4456       S.AddTemplateConversionCandidate(
4457           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4458           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4459     else
4460       S.AddConversionCandidate(
4461           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4462           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4463   }
4464 
4465   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4466 
4467   OverloadCandidateSet::iterator Best;
4468   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4469   case OR_Success:
4470     // C++ [over.ics.ref]p1:
4471     //
4472     //   [...] If the parameter binds directly to the result of
4473     //   applying a conversion function to the argument
4474     //   expression, the implicit conversion sequence is a
4475     //   user-defined conversion sequence (13.3.3.1.2), with the
4476     //   second standard conversion sequence either an identity
4477     //   conversion or, if the conversion function returns an
4478     //   entity of a type that is a derived class of the parameter
4479     //   type, a derived-to-base Conversion.
4480     if (!Best->FinalConversion.DirectBinding)
4481       return false;
4482 
4483     ICS.setUserDefined();
4484     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4485     ICS.UserDefined.After = Best->FinalConversion;
4486     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4487     ICS.UserDefined.ConversionFunction = Best->Function;
4488     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4489     ICS.UserDefined.EllipsisConversion = false;
4490     assert(ICS.UserDefined.After.ReferenceBinding &&
4491            ICS.UserDefined.After.DirectBinding &&
4492            "Expected a direct reference binding!");
4493     return true;
4494 
4495   case OR_Ambiguous:
4496     ICS.setAmbiguous();
4497     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4498          Cand != CandidateSet.end(); ++Cand)
4499       if (Cand->Viable)
4500         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4501     return true;
4502 
4503   case OR_No_Viable_Function:
4504   case OR_Deleted:
4505     // There was no suitable conversion, or we found a deleted
4506     // conversion; continue with other checks.
4507     return false;
4508   }
4509 
4510   llvm_unreachable("Invalid OverloadResult!");
4511 }
4512 
4513 /// Compute an implicit conversion sequence for reference
4514 /// initialization.
4515 static ImplicitConversionSequence
4516 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4517                  SourceLocation DeclLoc,
4518                  bool SuppressUserConversions,
4519                  bool AllowExplicit) {
4520   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4521 
4522   // Most paths end in a failed conversion.
4523   ImplicitConversionSequence ICS;
4524   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4525 
4526   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4527   QualType T2 = Init->getType();
4528 
4529   // If the initializer is the address of an overloaded function, try
4530   // to resolve the overloaded function. If all goes well, T2 is the
4531   // type of the resulting function.
4532   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4533     DeclAccessPair Found;
4534     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4535                                                                 false, Found))
4536       T2 = Fn->getType();
4537   }
4538 
4539   // Compute some basic properties of the types and the initializer.
4540   bool isRValRef = DeclType->isRValueReferenceType();
4541   bool DerivedToBase = false;
4542   bool ObjCConversion = false;
4543   bool ObjCLifetimeConversion = false;
4544   Expr::Classification InitCategory = Init->Classify(S.Context);
4545   Sema::ReferenceCompareResult RefRelationship
4546     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4547                                      ObjCConversion, ObjCLifetimeConversion);
4548 
4549 
4550   // C++0x [dcl.init.ref]p5:
4551   //   A reference to type "cv1 T1" is initialized by an expression
4552   //   of type "cv2 T2" as follows:
4553 
4554   //     -- If reference is an lvalue reference and the initializer expression
4555   if (!isRValRef) {
4556     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4557     //        reference-compatible with "cv2 T2," or
4558     //
4559     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4560     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4561       // C++ [over.ics.ref]p1:
4562       //   When a parameter of reference type binds directly (8.5.3)
4563       //   to an argument expression, the implicit conversion sequence
4564       //   is the identity conversion, unless the argument expression
4565       //   has a type that is a derived class of the parameter type,
4566       //   in which case the implicit conversion sequence is a
4567       //   derived-to-base Conversion (13.3.3.1).
4568       ICS.setStandard();
4569       ICS.Standard.First = ICK_Identity;
4570       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4571                          : ObjCConversion? ICK_Compatible_Conversion
4572                          : ICK_Identity;
4573       ICS.Standard.Third = ICK_Identity;
4574       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4575       ICS.Standard.setToType(0, T2);
4576       ICS.Standard.setToType(1, T1);
4577       ICS.Standard.setToType(2, T1);
4578       ICS.Standard.ReferenceBinding = true;
4579       ICS.Standard.DirectBinding = true;
4580       ICS.Standard.IsLvalueReference = !isRValRef;
4581       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4582       ICS.Standard.BindsToRvalue = false;
4583       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4584       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4585       ICS.Standard.CopyConstructor = nullptr;
4586       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4587 
4588       // Nothing more to do: the inaccessibility/ambiguity check for
4589       // derived-to-base conversions is suppressed when we're
4590       // computing the implicit conversion sequence (C++
4591       // [over.best.ics]p2).
4592       return ICS;
4593     }
4594 
4595     //       -- has a class type (i.e., T2 is a class type), where T1 is
4596     //          not reference-related to T2, and can be implicitly
4597     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4598     //          is reference-compatible with "cv3 T3" 92) (this
4599     //          conversion is selected by enumerating the applicable
4600     //          conversion functions (13.3.1.6) and choosing the best
4601     //          one through overload resolution (13.3)),
4602     if (!SuppressUserConversions && T2->isRecordType() &&
4603         S.isCompleteType(DeclLoc, T2) &&
4604         RefRelationship == Sema::Ref_Incompatible) {
4605       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4606                                    Init, T2, /*AllowRvalues=*/false,
4607                                    AllowExplicit))
4608         return ICS;
4609     }
4610   }
4611 
4612   //     -- Otherwise, the reference shall be an lvalue reference to a
4613   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4614   //        shall be an rvalue reference.
4615   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4616     return ICS;
4617 
4618   //       -- If the initializer expression
4619   //
4620   //            -- is an xvalue, class prvalue, array prvalue or function
4621   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4622   if (RefRelationship == Sema::Ref_Compatible &&
4623       (InitCategory.isXValue() ||
4624        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4625        (InitCategory.isLValue() && T2->isFunctionType()))) {
4626     ICS.setStandard();
4627     ICS.Standard.First = ICK_Identity;
4628     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4629                       : ObjCConversion? ICK_Compatible_Conversion
4630                       : ICK_Identity;
4631     ICS.Standard.Third = ICK_Identity;
4632     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4633     ICS.Standard.setToType(0, T2);
4634     ICS.Standard.setToType(1, T1);
4635     ICS.Standard.setToType(2, T1);
4636     ICS.Standard.ReferenceBinding = true;
4637     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4638     // binding unless we're binding to a class prvalue.
4639     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4640     // allow the use of rvalue references in C++98/03 for the benefit of
4641     // standard library implementors; therefore, we need the xvalue check here.
4642     ICS.Standard.DirectBinding =
4643       S.getLangOpts().CPlusPlus11 ||
4644       !(InitCategory.isPRValue() || T2->isRecordType());
4645     ICS.Standard.IsLvalueReference = !isRValRef;
4646     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4647     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4648     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4649     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4650     ICS.Standard.CopyConstructor = nullptr;
4651     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4652     return ICS;
4653   }
4654 
4655   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4656   //               reference-related to T2, and can be implicitly converted to
4657   //               an xvalue, class prvalue, or function lvalue of type
4658   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4659   //               "cv3 T3",
4660   //
4661   //          then the reference is bound to the value of the initializer
4662   //          expression in the first case and to the result of the conversion
4663   //          in the second case (or, in either case, to an appropriate base
4664   //          class subobject).
4665   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4666       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4667       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4668                                Init, T2, /*AllowRvalues=*/true,
4669                                AllowExplicit)) {
4670     // In the second case, if the reference is an rvalue reference
4671     // and the second standard conversion sequence of the
4672     // user-defined conversion sequence includes an lvalue-to-rvalue
4673     // conversion, the program is ill-formed.
4674     if (ICS.isUserDefined() && isRValRef &&
4675         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4676       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4677 
4678     return ICS;
4679   }
4680 
4681   // A temporary of function type cannot be created; don't even try.
4682   if (T1->isFunctionType())
4683     return ICS;
4684 
4685   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4686   //          initialized from the initializer expression using the
4687   //          rules for a non-reference copy initialization (8.5). The
4688   //          reference is then bound to the temporary. If T1 is
4689   //          reference-related to T2, cv1 must be the same
4690   //          cv-qualification as, or greater cv-qualification than,
4691   //          cv2; otherwise, the program is ill-formed.
4692   if (RefRelationship == Sema::Ref_Related) {
4693     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4694     // we would be reference-compatible or reference-compatible with
4695     // added qualification. But that wasn't the case, so the reference
4696     // initialization fails.
4697     //
4698     // Note that we only want to check address spaces and cvr-qualifiers here.
4699     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4700     Qualifiers T1Quals = T1.getQualifiers();
4701     Qualifiers T2Quals = T2.getQualifiers();
4702     T1Quals.removeObjCGCAttr();
4703     T1Quals.removeObjCLifetime();
4704     T2Quals.removeObjCGCAttr();
4705     T2Quals.removeObjCLifetime();
4706     // MS compiler ignores __unaligned qualifier for references; do the same.
4707     T1Quals.removeUnaligned();
4708     T2Quals.removeUnaligned();
4709     if (!T1Quals.compatiblyIncludes(T2Quals))
4710       return ICS;
4711   }
4712 
4713   // If at least one of the types is a class type, the types are not
4714   // related, and we aren't allowed any user conversions, the
4715   // reference binding fails. This case is important for breaking
4716   // recursion, since TryImplicitConversion below will attempt to
4717   // create a temporary through the use of a copy constructor.
4718   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4719       (T1->isRecordType() || T2->isRecordType()))
4720     return ICS;
4721 
4722   // If T1 is reference-related to T2 and the reference is an rvalue
4723   // reference, the initializer expression shall not be an lvalue.
4724   if (RefRelationship >= Sema::Ref_Related &&
4725       isRValRef && Init->Classify(S.Context).isLValue())
4726     return ICS;
4727 
4728   // C++ [over.ics.ref]p2:
4729   //   When a parameter of reference type is not bound directly to
4730   //   an argument expression, the conversion sequence is the one
4731   //   required to convert the argument expression to the
4732   //   underlying type of the reference according to
4733   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4734   //   to copy-initializing a temporary of the underlying type with
4735   //   the argument expression. Any difference in top-level
4736   //   cv-qualification is subsumed by the initialization itself
4737   //   and does not constitute a conversion.
4738   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4739                               /*AllowExplicit=*/false,
4740                               /*InOverloadResolution=*/false,
4741                               /*CStyle=*/false,
4742                               /*AllowObjCWritebackConversion=*/false,
4743                               /*AllowObjCConversionOnExplicit=*/false);
4744 
4745   // Of course, that's still a reference binding.
4746   if (ICS.isStandard()) {
4747     ICS.Standard.ReferenceBinding = true;
4748     ICS.Standard.IsLvalueReference = !isRValRef;
4749     ICS.Standard.BindsToFunctionLvalue = false;
4750     ICS.Standard.BindsToRvalue = true;
4751     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4752     ICS.Standard.ObjCLifetimeConversionBinding = false;
4753   } else if (ICS.isUserDefined()) {
4754     const ReferenceType *LValRefType =
4755         ICS.UserDefined.ConversionFunction->getReturnType()
4756             ->getAs<LValueReferenceType>();
4757 
4758     // C++ [over.ics.ref]p3:
4759     //   Except for an implicit object parameter, for which see 13.3.1, a
4760     //   standard conversion sequence cannot be formed if it requires [...]
4761     //   binding an rvalue reference to an lvalue other than a function
4762     //   lvalue.
4763     // Note that the function case is not possible here.
4764     if (DeclType->isRValueReferenceType() && LValRefType) {
4765       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4766       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4767       // reference to an rvalue!
4768       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4769       return ICS;
4770     }
4771 
4772     ICS.UserDefined.After.ReferenceBinding = true;
4773     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4774     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4775     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4776     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4777     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4778   }
4779 
4780   return ICS;
4781 }
4782 
4783 static ImplicitConversionSequence
4784 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4785                       bool SuppressUserConversions,
4786                       bool InOverloadResolution,
4787                       bool AllowObjCWritebackConversion,
4788                       bool AllowExplicit = false);
4789 
4790 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4791 /// initializer list From.
4792 static ImplicitConversionSequence
4793 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4794                   bool SuppressUserConversions,
4795                   bool InOverloadResolution,
4796                   bool AllowObjCWritebackConversion) {
4797   // C++11 [over.ics.list]p1:
4798   //   When an argument is an initializer list, it is not an expression and
4799   //   special rules apply for converting it to a parameter type.
4800 
4801   ImplicitConversionSequence Result;
4802   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4803 
4804   // We need a complete type for what follows. Incomplete types can never be
4805   // initialized from init lists.
4806   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4807     return Result;
4808 
4809   // Per DR1467:
4810   //   If the parameter type is a class X and the initializer list has a single
4811   //   element of type cv U, where U is X or a class derived from X, the
4812   //   implicit conversion sequence is the one required to convert the element
4813   //   to the parameter type.
4814   //
4815   //   Otherwise, if the parameter type is a character array [... ]
4816   //   and the initializer list has a single element that is an
4817   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4818   //   implicit conversion sequence is the identity conversion.
4819   if (From->getNumInits() == 1) {
4820     if (ToType->isRecordType()) {
4821       QualType InitType = From->getInit(0)->getType();
4822       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4823           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4824         return TryCopyInitialization(S, From->getInit(0), ToType,
4825                                      SuppressUserConversions,
4826                                      InOverloadResolution,
4827                                      AllowObjCWritebackConversion);
4828     }
4829     // FIXME: Check the other conditions here: array of character type,
4830     // initializer is a string literal.
4831     if (ToType->isArrayType()) {
4832       InitializedEntity Entity =
4833         InitializedEntity::InitializeParameter(S.Context, ToType,
4834                                                /*Consumed=*/false);
4835       if (S.CanPerformCopyInitialization(Entity, From)) {
4836         Result.setStandard();
4837         Result.Standard.setAsIdentityConversion();
4838         Result.Standard.setFromType(ToType);
4839         Result.Standard.setAllToTypes(ToType);
4840         return Result;
4841       }
4842     }
4843   }
4844 
4845   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4846   // C++11 [over.ics.list]p2:
4847   //   If the parameter type is std::initializer_list<X> or "array of X" and
4848   //   all the elements can be implicitly converted to X, the implicit
4849   //   conversion sequence is the worst conversion necessary to convert an
4850   //   element of the list to X.
4851   //
4852   // C++14 [over.ics.list]p3:
4853   //   Otherwise, if the parameter type is "array of N X", if the initializer
4854   //   list has exactly N elements or if it has fewer than N elements and X is
4855   //   default-constructible, and if all the elements of the initializer list
4856   //   can be implicitly converted to X, the implicit conversion sequence is
4857   //   the worst conversion necessary to convert an element of the list to X.
4858   //
4859   // FIXME: We're missing a lot of these checks.
4860   bool toStdInitializerList = false;
4861   QualType X;
4862   if (ToType->isArrayType())
4863     X = S.Context.getAsArrayType(ToType)->getElementType();
4864   else
4865     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4866   if (!X.isNull()) {
4867     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4868       Expr *Init = From->getInit(i);
4869       ImplicitConversionSequence ICS =
4870           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4871                                 InOverloadResolution,
4872                                 AllowObjCWritebackConversion);
4873       // If a single element isn't convertible, fail.
4874       if (ICS.isBad()) {
4875         Result = ICS;
4876         break;
4877       }
4878       // Otherwise, look for the worst conversion.
4879       if (Result.isBad() || CompareImplicitConversionSequences(
4880                                 S, From->getBeginLoc(), ICS, Result) ==
4881                                 ImplicitConversionSequence::Worse)
4882         Result = ICS;
4883     }
4884 
4885     // For an empty list, we won't have computed any conversion sequence.
4886     // Introduce the identity conversion sequence.
4887     if (From->getNumInits() == 0) {
4888       Result.setStandard();
4889       Result.Standard.setAsIdentityConversion();
4890       Result.Standard.setFromType(ToType);
4891       Result.Standard.setAllToTypes(ToType);
4892     }
4893 
4894     Result.setStdInitializerListElement(toStdInitializerList);
4895     return Result;
4896   }
4897 
4898   // C++14 [over.ics.list]p4:
4899   // C++11 [over.ics.list]p3:
4900   //   Otherwise, if the parameter is a non-aggregate class X and overload
4901   //   resolution chooses a single best constructor [...] the implicit
4902   //   conversion sequence is a user-defined conversion sequence. If multiple
4903   //   constructors are viable but none is better than the others, the
4904   //   implicit conversion sequence is a user-defined conversion sequence.
4905   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4906     // This function can deal with initializer lists.
4907     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4908                                     /*AllowExplicit=*/false,
4909                                     InOverloadResolution, /*CStyle=*/false,
4910                                     AllowObjCWritebackConversion,
4911                                     /*AllowObjCConversionOnExplicit=*/false);
4912   }
4913 
4914   // C++14 [over.ics.list]p5:
4915   // C++11 [over.ics.list]p4:
4916   //   Otherwise, if the parameter has an aggregate type which can be
4917   //   initialized from the initializer list [...] the implicit conversion
4918   //   sequence is a user-defined conversion sequence.
4919   if (ToType->isAggregateType()) {
4920     // Type is an aggregate, argument is an init list. At this point it comes
4921     // down to checking whether the initialization works.
4922     // FIXME: Find out whether this parameter is consumed or not.
4923     InitializedEntity Entity =
4924         InitializedEntity::InitializeParameter(S.Context, ToType,
4925                                                /*Consumed=*/false);
4926     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
4927                                                                  From)) {
4928       Result.setUserDefined();
4929       Result.UserDefined.Before.setAsIdentityConversion();
4930       // Initializer lists don't have a type.
4931       Result.UserDefined.Before.setFromType(QualType());
4932       Result.UserDefined.Before.setAllToTypes(QualType());
4933 
4934       Result.UserDefined.After.setAsIdentityConversion();
4935       Result.UserDefined.After.setFromType(ToType);
4936       Result.UserDefined.After.setAllToTypes(ToType);
4937       Result.UserDefined.ConversionFunction = nullptr;
4938     }
4939     return Result;
4940   }
4941 
4942   // C++14 [over.ics.list]p6:
4943   // C++11 [over.ics.list]p5:
4944   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4945   if (ToType->isReferenceType()) {
4946     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4947     // mention initializer lists in any way. So we go by what list-
4948     // initialization would do and try to extrapolate from that.
4949 
4950     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4951 
4952     // If the initializer list has a single element that is reference-related
4953     // to the parameter type, we initialize the reference from that.
4954     if (From->getNumInits() == 1) {
4955       Expr *Init = From->getInit(0);
4956 
4957       QualType T2 = Init->getType();
4958 
4959       // If the initializer is the address of an overloaded function, try
4960       // to resolve the overloaded function. If all goes well, T2 is the
4961       // type of the resulting function.
4962       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4963         DeclAccessPair Found;
4964         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4965                                    Init, ToType, false, Found))
4966           T2 = Fn->getType();
4967       }
4968 
4969       // Compute some basic properties of the types and the initializer.
4970       bool dummy1 = false;
4971       bool dummy2 = false;
4972       bool dummy3 = false;
4973       Sema::ReferenceCompareResult RefRelationship =
4974           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4975                                          dummy2, dummy3);
4976 
4977       if (RefRelationship >= Sema::Ref_Related) {
4978         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4979                                 SuppressUserConversions,
4980                                 /*AllowExplicit=*/false);
4981       }
4982     }
4983 
4984     // Otherwise, we bind the reference to a temporary created from the
4985     // initializer list.
4986     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4987                                InOverloadResolution,
4988                                AllowObjCWritebackConversion);
4989     if (Result.isFailure())
4990       return Result;
4991     assert(!Result.isEllipsis() &&
4992            "Sub-initialization cannot result in ellipsis conversion.");
4993 
4994     // Can we even bind to a temporary?
4995     if (ToType->isRValueReferenceType() ||
4996         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4997       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4998                                             Result.UserDefined.After;
4999       SCS.ReferenceBinding = true;
5000       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5001       SCS.BindsToRvalue = true;
5002       SCS.BindsToFunctionLvalue = false;
5003       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5004       SCS.ObjCLifetimeConversionBinding = false;
5005     } else
5006       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5007                     From, ToType);
5008     return Result;
5009   }
5010 
5011   // C++14 [over.ics.list]p7:
5012   // C++11 [over.ics.list]p6:
5013   //   Otherwise, if the parameter type is not a class:
5014   if (!ToType->isRecordType()) {
5015     //    - if the initializer list has one element that is not itself an
5016     //      initializer list, the implicit conversion sequence is the one
5017     //      required to convert the element to the parameter type.
5018     unsigned NumInits = From->getNumInits();
5019     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5020       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5021                                      SuppressUserConversions,
5022                                      InOverloadResolution,
5023                                      AllowObjCWritebackConversion);
5024     //    - if the initializer list has no elements, the implicit conversion
5025     //      sequence is the identity conversion.
5026     else if (NumInits == 0) {
5027       Result.setStandard();
5028       Result.Standard.setAsIdentityConversion();
5029       Result.Standard.setFromType(ToType);
5030       Result.Standard.setAllToTypes(ToType);
5031     }
5032     return Result;
5033   }
5034 
5035   // C++14 [over.ics.list]p8:
5036   // C++11 [over.ics.list]p7:
5037   //   In all cases other than those enumerated above, no conversion is possible
5038   return Result;
5039 }
5040 
5041 /// TryCopyInitialization - Try to copy-initialize a value of type
5042 /// ToType from the expression From. Return the implicit conversion
5043 /// sequence required to pass this argument, which may be a bad
5044 /// conversion sequence (meaning that the argument cannot be passed to
5045 /// a parameter of this type). If @p SuppressUserConversions, then we
5046 /// do not permit any user-defined conversion sequences.
5047 static ImplicitConversionSequence
5048 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5049                       bool SuppressUserConversions,
5050                       bool InOverloadResolution,
5051                       bool AllowObjCWritebackConversion,
5052                       bool AllowExplicit) {
5053   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5054     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5055                              InOverloadResolution,AllowObjCWritebackConversion);
5056 
5057   if (ToType->isReferenceType())
5058     return TryReferenceInit(S, From, ToType,
5059                             /*FIXME:*/ From->getBeginLoc(),
5060                             SuppressUserConversions, AllowExplicit);
5061 
5062   return TryImplicitConversion(S, From, ToType,
5063                                SuppressUserConversions,
5064                                /*AllowExplicit=*/false,
5065                                InOverloadResolution,
5066                                /*CStyle=*/false,
5067                                AllowObjCWritebackConversion,
5068                                /*AllowObjCConversionOnExplicit=*/false);
5069 }
5070 
5071 static bool TryCopyInitialization(const CanQualType FromQTy,
5072                                   const CanQualType ToQTy,
5073                                   Sema &S,
5074                                   SourceLocation Loc,
5075                                   ExprValueKind FromVK) {
5076   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5077   ImplicitConversionSequence ICS =
5078     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5079 
5080   return !ICS.isBad();
5081 }
5082 
5083 /// TryObjectArgumentInitialization - Try to initialize the object
5084 /// parameter of the given member function (@c Method) from the
5085 /// expression @p From.
5086 static ImplicitConversionSequence
5087 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5088                                 Expr::Classification FromClassification,
5089                                 CXXMethodDecl *Method,
5090                                 CXXRecordDecl *ActingContext) {
5091   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5092   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5093   //                 const volatile object.
5094   Qualifiers Quals = Method->getMethodQualifiers();
5095   if (isa<CXXDestructorDecl>(Method)) {
5096     Quals.addConst();
5097     Quals.addVolatile();
5098   }
5099 
5100   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5101 
5102   // Set up the conversion sequence as a "bad" conversion, to allow us
5103   // to exit early.
5104   ImplicitConversionSequence ICS;
5105 
5106   // We need to have an object of class type.
5107   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5108     FromType = PT->getPointeeType();
5109 
5110     // When we had a pointer, it's implicitly dereferenced, so we
5111     // better have an lvalue.
5112     assert(FromClassification.isLValue());
5113   }
5114 
5115   assert(FromType->isRecordType());
5116 
5117   // C++0x [over.match.funcs]p4:
5118   //   For non-static member functions, the type of the implicit object
5119   //   parameter is
5120   //
5121   //     - "lvalue reference to cv X" for functions declared without a
5122   //        ref-qualifier or with the & ref-qualifier
5123   //     - "rvalue reference to cv X" for functions declared with the &&
5124   //        ref-qualifier
5125   //
5126   // where X is the class of which the function is a member and cv is the
5127   // cv-qualification on the member function declaration.
5128   //
5129   // However, when finding an implicit conversion sequence for the argument, we
5130   // are not allowed to perform user-defined conversions
5131   // (C++ [over.match.funcs]p5). We perform a simplified version of
5132   // reference binding here, that allows class rvalues to bind to
5133   // non-constant references.
5134 
5135   // First check the qualifiers.
5136   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5137   if (ImplicitParamType.getCVRQualifiers()
5138                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5139       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5140     ICS.setBad(BadConversionSequence::bad_qualifiers,
5141                FromType, ImplicitParamType);
5142     return ICS;
5143   }
5144 
5145   if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
5146     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5147     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5148     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5149       ICS.setBad(BadConversionSequence::bad_qualifiers,
5150                  FromType, ImplicitParamType);
5151       return ICS;
5152     }
5153   }
5154 
5155   // Check that we have either the same type or a derived type. It
5156   // affects the conversion rank.
5157   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5158   ImplicitConversionKind SecondKind;
5159   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5160     SecondKind = ICK_Identity;
5161   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5162     SecondKind = ICK_Derived_To_Base;
5163   else {
5164     ICS.setBad(BadConversionSequence::unrelated_class,
5165                FromType, ImplicitParamType);
5166     return ICS;
5167   }
5168 
5169   // Check the ref-qualifier.
5170   switch (Method->getRefQualifier()) {
5171   case RQ_None:
5172     // Do nothing; we don't care about lvalueness or rvalueness.
5173     break;
5174 
5175   case RQ_LValue:
5176     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5177       // non-const lvalue reference cannot bind to an rvalue
5178       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5179                  ImplicitParamType);
5180       return ICS;
5181     }
5182     break;
5183 
5184   case RQ_RValue:
5185     if (!FromClassification.isRValue()) {
5186       // rvalue reference cannot bind to an lvalue
5187       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5188                  ImplicitParamType);
5189       return ICS;
5190     }
5191     break;
5192   }
5193 
5194   // Success. Mark this as a reference binding.
5195   ICS.setStandard();
5196   ICS.Standard.setAsIdentityConversion();
5197   ICS.Standard.Second = SecondKind;
5198   ICS.Standard.setFromType(FromType);
5199   ICS.Standard.setAllToTypes(ImplicitParamType);
5200   ICS.Standard.ReferenceBinding = true;
5201   ICS.Standard.DirectBinding = true;
5202   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5203   ICS.Standard.BindsToFunctionLvalue = false;
5204   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5205   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5206     = (Method->getRefQualifier() == RQ_None);
5207   return ICS;
5208 }
5209 
5210 /// PerformObjectArgumentInitialization - Perform initialization of
5211 /// the implicit object parameter for the given Method with the given
5212 /// expression.
5213 ExprResult
5214 Sema::PerformObjectArgumentInitialization(Expr *From,
5215                                           NestedNameSpecifier *Qualifier,
5216                                           NamedDecl *FoundDecl,
5217                                           CXXMethodDecl *Method) {
5218   QualType FromRecordType, DestType;
5219   QualType ImplicitParamRecordType  =
5220     Method->getThisType()->getAs<PointerType>()->getPointeeType();
5221 
5222   Expr::Classification FromClassification;
5223   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5224     FromRecordType = PT->getPointeeType();
5225     DestType = Method->getThisType();
5226     FromClassification = Expr::Classification::makeSimpleLValue();
5227   } else {
5228     FromRecordType = From->getType();
5229     DestType = ImplicitParamRecordType;
5230     FromClassification = From->Classify(Context);
5231 
5232     // When performing member access on an rvalue, materialize a temporary.
5233     if (From->isRValue()) {
5234       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5235                                             Method->getRefQualifier() !=
5236                                                 RefQualifierKind::RQ_RValue);
5237     }
5238   }
5239 
5240   // Note that we always use the true parent context when performing
5241   // the actual argument initialization.
5242   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5243       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5244       Method->getParent());
5245   if (ICS.isBad()) {
5246     switch (ICS.Bad.Kind) {
5247     case BadConversionSequence::bad_qualifiers: {
5248       Qualifiers FromQs = FromRecordType.getQualifiers();
5249       Qualifiers ToQs = DestType.getQualifiers();
5250       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5251       if (CVR) {
5252         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5253             << Method->getDeclName() << FromRecordType << (CVR - 1)
5254             << From->getSourceRange();
5255         Diag(Method->getLocation(), diag::note_previous_decl)
5256           << Method->getDeclName();
5257         return ExprError();
5258       }
5259       break;
5260     }
5261 
5262     case BadConversionSequence::lvalue_ref_to_rvalue:
5263     case BadConversionSequence::rvalue_ref_to_lvalue: {
5264       bool IsRValueQualified =
5265         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5266       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5267           << Method->getDeclName() << FromClassification.isRValue()
5268           << IsRValueQualified;
5269       Diag(Method->getLocation(), diag::note_previous_decl)
5270         << Method->getDeclName();
5271       return ExprError();
5272     }
5273 
5274     case BadConversionSequence::no_conversion:
5275     case BadConversionSequence::unrelated_class:
5276       break;
5277     }
5278 
5279     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5280            << ImplicitParamRecordType << FromRecordType
5281            << From->getSourceRange();
5282   }
5283 
5284   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5285     ExprResult FromRes =
5286       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5287     if (FromRes.isInvalid())
5288       return ExprError();
5289     From = FromRes.get();
5290   }
5291 
5292   if (!Context.hasSameType(From->getType(), DestType)) {
5293     CastKind CK;
5294     if (FromRecordType.getAddressSpace() != DestType.getAddressSpace())
5295       CK = CK_AddressSpaceConversion;
5296     else
5297       CK = CK_NoOp;
5298     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5299   }
5300   return From;
5301 }
5302 
5303 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5304 /// expression From to bool (C++0x [conv]p3).
5305 static ImplicitConversionSequence
5306 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5307   return TryImplicitConversion(S, From, S.Context.BoolTy,
5308                                /*SuppressUserConversions=*/false,
5309                                /*AllowExplicit=*/true,
5310                                /*InOverloadResolution=*/false,
5311                                /*CStyle=*/false,
5312                                /*AllowObjCWritebackConversion=*/false,
5313                                /*AllowObjCConversionOnExplicit=*/false);
5314 }
5315 
5316 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5317 /// of the expression From to bool (C++0x [conv]p3).
5318 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5319   if (checkPlaceholderForOverload(*this, From))
5320     return ExprError();
5321 
5322   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5323   if (!ICS.isBad())
5324     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5325 
5326   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5327     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5328            << From->getType() << From->getSourceRange();
5329   return ExprError();
5330 }
5331 
5332 /// Check that the specified conversion is permitted in a converted constant
5333 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5334 /// is acceptable.
5335 static bool CheckConvertedConstantConversions(Sema &S,
5336                                               StandardConversionSequence &SCS) {
5337   // Since we know that the target type is an integral or unscoped enumeration
5338   // type, most conversion kinds are impossible. All possible First and Third
5339   // conversions are fine.
5340   switch (SCS.Second) {
5341   case ICK_Identity:
5342   case ICK_Function_Conversion:
5343   case ICK_Integral_Promotion:
5344   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5345   case ICK_Zero_Queue_Conversion:
5346     return true;
5347 
5348   case ICK_Boolean_Conversion:
5349     // Conversion from an integral or unscoped enumeration type to bool is
5350     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5351     // conversion, so we allow it in a converted constant expression.
5352     //
5353     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5354     // a lot of popular code. We should at least add a warning for this
5355     // (non-conforming) extension.
5356     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5357            SCS.getToType(2)->isBooleanType();
5358 
5359   case ICK_Pointer_Conversion:
5360   case ICK_Pointer_Member:
5361     // C++1z: null pointer conversions and null member pointer conversions are
5362     // only permitted if the source type is std::nullptr_t.
5363     return SCS.getFromType()->isNullPtrType();
5364 
5365   case ICK_Floating_Promotion:
5366   case ICK_Complex_Promotion:
5367   case ICK_Floating_Conversion:
5368   case ICK_Complex_Conversion:
5369   case ICK_Floating_Integral:
5370   case ICK_Compatible_Conversion:
5371   case ICK_Derived_To_Base:
5372   case ICK_Vector_Conversion:
5373   case ICK_Vector_Splat:
5374   case ICK_Complex_Real:
5375   case ICK_Block_Pointer_Conversion:
5376   case ICK_TransparentUnionConversion:
5377   case ICK_Writeback_Conversion:
5378   case ICK_Zero_Event_Conversion:
5379   case ICK_C_Only_Conversion:
5380   case ICK_Incompatible_Pointer_Conversion:
5381     return false;
5382 
5383   case ICK_Lvalue_To_Rvalue:
5384   case ICK_Array_To_Pointer:
5385   case ICK_Function_To_Pointer:
5386     llvm_unreachable("found a first conversion kind in Second");
5387 
5388   case ICK_Qualification:
5389     llvm_unreachable("found a third conversion kind in Second");
5390 
5391   case ICK_Num_Conversion_Kinds:
5392     break;
5393   }
5394 
5395   llvm_unreachable("unknown conversion kind");
5396 }
5397 
5398 /// CheckConvertedConstantExpression - Check that the expression From is a
5399 /// converted constant expression of type T, perform the conversion and produce
5400 /// the converted expression, per C++11 [expr.const]p3.
5401 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5402                                                    QualType T, APValue &Value,
5403                                                    Sema::CCEKind CCE,
5404                                                    bool RequireInt) {
5405   assert(S.getLangOpts().CPlusPlus11 &&
5406          "converted constant expression outside C++11");
5407 
5408   if (checkPlaceholderForOverload(S, From))
5409     return ExprError();
5410 
5411   // C++1z [expr.const]p3:
5412   //  A converted constant expression of type T is an expression,
5413   //  implicitly converted to type T, where the converted
5414   //  expression is a constant expression and the implicit conversion
5415   //  sequence contains only [... list of conversions ...].
5416   // C++1z [stmt.if]p2:
5417   //  If the if statement is of the form if constexpr, the value of the
5418   //  condition shall be a contextually converted constant expression of type
5419   //  bool.
5420   ImplicitConversionSequence ICS =
5421       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5422           ? TryContextuallyConvertToBool(S, From)
5423           : TryCopyInitialization(S, From, T,
5424                                   /*SuppressUserConversions=*/false,
5425                                   /*InOverloadResolution=*/false,
5426                                   /*AllowObjCWritebackConversion=*/false,
5427                                   /*AllowExplicit=*/false);
5428   StandardConversionSequence *SCS = nullptr;
5429   switch (ICS.getKind()) {
5430   case ImplicitConversionSequence::StandardConversion:
5431     SCS = &ICS.Standard;
5432     break;
5433   case ImplicitConversionSequence::UserDefinedConversion:
5434     // We are converting to a non-class type, so the Before sequence
5435     // must be trivial.
5436     SCS = &ICS.UserDefined.After;
5437     break;
5438   case ImplicitConversionSequence::AmbiguousConversion:
5439   case ImplicitConversionSequence::BadConversion:
5440     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5441       return S.Diag(From->getBeginLoc(),
5442                     diag::err_typecheck_converted_constant_expression)
5443              << From->getType() << From->getSourceRange() << T;
5444     return ExprError();
5445 
5446   case ImplicitConversionSequence::EllipsisConversion:
5447     llvm_unreachable("ellipsis conversion in converted constant expression");
5448   }
5449 
5450   // Check that we would only use permitted conversions.
5451   if (!CheckConvertedConstantConversions(S, *SCS)) {
5452     return S.Diag(From->getBeginLoc(),
5453                   diag::err_typecheck_converted_constant_expression_disallowed)
5454            << From->getType() << From->getSourceRange() << T;
5455   }
5456   // [...] and where the reference binding (if any) binds directly.
5457   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5458     return S.Diag(From->getBeginLoc(),
5459                   diag::err_typecheck_converted_constant_expression_indirect)
5460            << From->getType() << From->getSourceRange() << T;
5461   }
5462 
5463   ExprResult Result =
5464       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5465   if (Result.isInvalid())
5466     return Result;
5467 
5468   // Check for a narrowing implicit conversion.
5469   APValue PreNarrowingValue;
5470   QualType PreNarrowingType;
5471   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5472                                 PreNarrowingType)) {
5473   case NK_Dependent_Narrowing:
5474     // Implicit conversion to a narrower type, but the expression is
5475     // value-dependent so we can't tell whether it's actually narrowing.
5476   case NK_Variable_Narrowing:
5477     // Implicit conversion to a narrower type, and the value is not a constant
5478     // expression. We'll diagnose this in a moment.
5479   case NK_Not_Narrowing:
5480     break;
5481 
5482   case NK_Constant_Narrowing:
5483     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5484         << CCE << /*Constant*/ 1
5485         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5486     break;
5487 
5488   case NK_Type_Narrowing:
5489     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5490         << CCE << /*Constant*/ 0 << From->getType() << T;
5491     break;
5492   }
5493 
5494   if (Result.get()->isValueDependent()) {
5495     Value = APValue();
5496     return Result;
5497   }
5498 
5499   // Check the expression is a constant expression.
5500   SmallVector<PartialDiagnosticAt, 8> Notes;
5501   Expr::EvalResult Eval;
5502   Eval.Diag = &Notes;
5503   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5504                                    ? Expr::EvaluateForMangling
5505                                    : Expr::EvaluateForCodeGen;
5506 
5507   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5508       (RequireInt && !Eval.Val.isInt())) {
5509     // The expression can't be folded, so we can't keep it at this position in
5510     // the AST.
5511     Result = ExprError();
5512   } else {
5513     Value = Eval.Val;
5514 
5515     if (Notes.empty()) {
5516       // It's a constant expression.
5517       return ConstantExpr::Create(S.Context, Result.get(), Value);
5518     }
5519   }
5520 
5521   // It's not a constant expression. Produce an appropriate diagnostic.
5522   if (Notes.size() == 1 &&
5523       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5524     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5525   else {
5526     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5527         << CCE << From->getSourceRange();
5528     for (unsigned I = 0; I < Notes.size(); ++I)
5529       S.Diag(Notes[I].first, Notes[I].second);
5530   }
5531   return ExprError();
5532 }
5533 
5534 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5535                                                   APValue &Value, CCEKind CCE) {
5536   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5537 }
5538 
5539 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5540                                                   llvm::APSInt &Value,
5541                                                   CCEKind CCE) {
5542   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5543 
5544   APValue V;
5545   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5546   if (!R.isInvalid() && !R.get()->isValueDependent())
5547     Value = V.getInt();
5548   return R;
5549 }
5550 
5551 
5552 /// dropPointerConversions - If the given standard conversion sequence
5553 /// involves any pointer conversions, remove them.  This may change
5554 /// the result type of the conversion sequence.
5555 static void dropPointerConversion(StandardConversionSequence &SCS) {
5556   if (SCS.Second == ICK_Pointer_Conversion) {
5557     SCS.Second = ICK_Identity;
5558     SCS.Third = ICK_Identity;
5559     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5560   }
5561 }
5562 
5563 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5564 /// convert the expression From to an Objective-C pointer type.
5565 static ImplicitConversionSequence
5566 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5567   // Do an implicit conversion to 'id'.
5568   QualType Ty = S.Context.getObjCIdType();
5569   ImplicitConversionSequence ICS
5570     = TryImplicitConversion(S, From, Ty,
5571                             // FIXME: Are these flags correct?
5572                             /*SuppressUserConversions=*/false,
5573                             /*AllowExplicit=*/true,
5574                             /*InOverloadResolution=*/false,
5575                             /*CStyle=*/false,
5576                             /*AllowObjCWritebackConversion=*/false,
5577                             /*AllowObjCConversionOnExplicit=*/true);
5578 
5579   // Strip off any final conversions to 'id'.
5580   switch (ICS.getKind()) {
5581   case ImplicitConversionSequence::BadConversion:
5582   case ImplicitConversionSequence::AmbiguousConversion:
5583   case ImplicitConversionSequence::EllipsisConversion:
5584     break;
5585 
5586   case ImplicitConversionSequence::UserDefinedConversion:
5587     dropPointerConversion(ICS.UserDefined.After);
5588     break;
5589 
5590   case ImplicitConversionSequence::StandardConversion:
5591     dropPointerConversion(ICS.Standard);
5592     break;
5593   }
5594 
5595   return ICS;
5596 }
5597 
5598 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5599 /// conversion of the expression From to an Objective-C pointer type.
5600 /// Returns a valid but null ExprResult if no conversion sequence exists.
5601 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5602   if (checkPlaceholderForOverload(*this, From))
5603     return ExprError();
5604 
5605   QualType Ty = Context.getObjCIdType();
5606   ImplicitConversionSequence ICS =
5607     TryContextuallyConvertToObjCPointer(*this, From);
5608   if (!ICS.isBad())
5609     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5610   return ExprResult();
5611 }
5612 
5613 /// Determine whether the provided type is an integral type, or an enumeration
5614 /// type of a permitted flavor.
5615 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5616   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5617                                  : T->isIntegralOrUnscopedEnumerationType();
5618 }
5619 
5620 static ExprResult
5621 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5622                             Sema::ContextualImplicitConverter &Converter,
5623                             QualType T, UnresolvedSetImpl &ViableConversions) {
5624 
5625   if (Converter.Suppress)
5626     return ExprError();
5627 
5628   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5629   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5630     CXXConversionDecl *Conv =
5631         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5632     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5633     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5634   }
5635   return From;
5636 }
5637 
5638 static bool
5639 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5640                            Sema::ContextualImplicitConverter &Converter,
5641                            QualType T, bool HadMultipleCandidates,
5642                            UnresolvedSetImpl &ExplicitConversions) {
5643   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5644     DeclAccessPair Found = ExplicitConversions[0];
5645     CXXConversionDecl *Conversion =
5646         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5647 
5648     // The user probably meant to invoke the given explicit
5649     // conversion; use it.
5650     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5651     std::string TypeStr;
5652     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5653 
5654     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5655         << FixItHint::CreateInsertion(From->getBeginLoc(),
5656                                       "static_cast<" + TypeStr + ">(")
5657         << FixItHint::CreateInsertion(
5658                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5659     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5660 
5661     // If we aren't in a SFINAE context, build a call to the
5662     // explicit conversion function.
5663     if (SemaRef.isSFINAEContext())
5664       return true;
5665 
5666     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5667     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5668                                                        HadMultipleCandidates);
5669     if (Result.isInvalid())
5670       return true;
5671     // Record usage of conversion in an implicit cast.
5672     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5673                                     CK_UserDefinedConversion, Result.get(),
5674                                     nullptr, Result.get()->getValueKind());
5675   }
5676   return false;
5677 }
5678 
5679 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5680                              Sema::ContextualImplicitConverter &Converter,
5681                              QualType T, bool HadMultipleCandidates,
5682                              DeclAccessPair &Found) {
5683   CXXConversionDecl *Conversion =
5684       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5685   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5686 
5687   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5688   if (!Converter.SuppressConversion) {
5689     if (SemaRef.isSFINAEContext())
5690       return true;
5691 
5692     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5693         << From->getSourceRange();
5694   }
5695 
5696   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5697                                                      HadMultipleCandidates);
5698   if (Result.isInvalid())
5699     return true;
5700   // Record usage of conversion in an implicit cast.
5701   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5702                                   CK_UserDefinedConversion, Result.get(),
5703                                   nullptr, Result.get()->getValueKind());
5704   return false;
5705 }
5706 
5707 static ExprResult finishContextualImplicitConversion(
5708     Sema &SemaRef, SourceLocation Loc, Expr *From,
5709     Sema::ContextualImplicitConverter &Converter) {
5710   if (!Converter.match(From->getType()) && !Converter.Suppress)
5711     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5712         << From->getSourceRange();
5713 
5714   return SemaRef.DefaultLvalueConversion(From);
5715 }
5716 
5717 static void
5718 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5719                                   UnresolvedSetImpl &ViableConversions,
5720                                   OverloadCandidateSet &CandidateSet) {
5721   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5722     DeclAccessPair FoundDecl = ViableConversions[I];
5723     NamedDecl *D = FoundDecl.getDecl();
5724     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5725     if (isa<UsingShadowDecl>(D))
5726       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5727 
5728     CXXConversionDecl *Conv;
5729     FunctionTemplateDecl *ConvTemplate;
5730     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5731       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5732     else
5733       Conv = cast<CXXConversionDecl>(D);
5734 
5735     if (ConvTemplate)
5736       SemaRef.AddTemplateConversionCandidate(
5737           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5738           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5739     else
5740       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5741                                      ToType, CandidateSet,
5742                                      /*AllowObjCConversionOnExplicit=*/false,
5743                                      /*AllowExplicit*/ true);
5744   }
5745 }
5746 
5747 /// Attempt to convert the given expression to a type which is accepted
5748 /// by the given converter.
5749 ///
5750 /// This routine will attempt to convert an expression of class type to a
5751 /// type accepted by the specified converter. In C++11 and before, the class
5752 /// must have a single non-explicit conversion function converting to a matching
5753 /// type. In C++1y, there can be multiple such conversion functions, but only
5754 /// one target type.
5755 ///
5756 /// \param Loc The source location of the construct that requires the
5757 /// conversion.
5758 ///
5759 /// \param From The expression we're converting from.
5760 ///
5761 /// \param Converter Used to control and diagnose the conversion process.
5762 ///
5763 /// \returns The expression, converted to an integral or enumeration type if
5764 /// successful.
5765 ExprResult Sema::PerformContextualImplicitConversion(
5766     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5767   // We can't perform any more checking for type-dependent expressions.
5768   if (From->isTypeDependent())
5769     return From;
5770 
5771   // Process placeholders immediately.
5772   if (From->hasPlaceholderType()) {
5773     ExprResult result = CheckPlaceholderExpr(From);
5774     if (result.isInvalid())
5775       return result;
5776     From = result.get();
5777   }
5778 
5779   // If the expression already has a matching type, we're golden.
5780   QualType T = From->getType();
5781   if (Converter.match(T))
5782     return DefaultLvalueConversion(From);
5783 
5784   // FIXME: Check for missing '()' if T is a function type?
5785 
5786   // We can only perform contextual implicit conversions on objects of class
5787   // type.
5788   const RecordType *RecordTy = T->getAs<RecordType>();
5789   if (!RecordTy || !getLangOpts().CPlusPlus) {
5790     if (!Converter.Suppress)
5791       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5792     return From;
5793   }
5794 
5795   // We must have a complete class type.
5796   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5797     ContextualImplicitConverter &Converter;
5798     Expr *From;
5799 
5800     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5801         : Converter(Converter), From(From) {}
5802 
5803     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5804       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5805     }
5806   } IncompleteDiagnoser(Converter, From);
5807 
5808   if (Converter.Suppress ? !isCompleteType(Loc, T)
5809                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5810     return From;
5811 
5812   // Look for a conversion to an integral or enumeration type.
5813   UnresolvedSet<4>
5814       ViableConversions; // These are *potentially* viable in C++1y.
5815   UnresolvedSet<4> ExplicitConversions;
5816   const auto &Conversions =
5817       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5818 
5819   bool HadMultipleCandidates =
5820       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5821 
5822   // To check that there is only one target type, in C++1y:
5823   QualType ToType;
5824   bool HasUniqueTargetType = true;
5825 
5826   // Collect explicit or viable (potentially in C++1y) conversions.
5827   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5828     NamedDecl *D = (*I)->getUnderlyingDecl();
5829     CXXConversionDecl *Conversion;
5830     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5831     if (ConvTemplate) {
5832       if (getLangOpts().CPlusPlus14)
5833         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5834       else
5835         continue; // C++11 does not consider conversion operator templates(?).
5836     } else
5837       Conversion = cast<CXXConversionDecl>(D);
5838 
5839     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5840            "Conversion operator templates are considered potentially "
5841            "viable in C++1y");
5842 
5843     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5844     if (Converter.match(CurToType) || ConvTemplate) {
5845 
5846       if (Conversion->isExplicit()) {
5847         // FIXME: For C++1y, do we need this restriction?
5848         // cf. diagnoseNoViableConversion()
5849         if (!ConvTemplate)
5850           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5851       } else {
5852         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5853           if (ToType.isNull())
5854             ToType = CurToType.getUnqualifiedType();
5855           else if (HasUniqueTargetType &&
5856                    (CurToType.getUnqualifiedType() != ToType))
5857             HasUniqueTargetType = false;
5858         }
5859         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5860       }
5861     }
5862   }
5863 
5864   if (getLangOpts().CPlusPlus14) {
5865     // C++1y [conv]p6:
5866     // ... An expression e of class type E appearing in such a context
5867     // is said to be contextually implicitly converted to a specified
5868     // type T and is well-formed if and only if e can be implicitly
5869     // converted to a type T that is determined as follows: E is searched
5870     // for conversion functions whose return type is cv T or reference to
5871     // cv T such that T is allowed by the context. There shall be
5872     // exactly one such T.
5873 
5874     // If no unique T is found:
5875     if (ToType.isNull()) {
5876       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5877                                      HadMultipleCandidates,
5878                                      ExplicitConversions))
5879         return ExprError();
5880       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5881     }
5882 
5883     // If more than one unique Ts are found:
5884     if (!HasUniqueTargetType)
5885       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5886                                          ViableConversions);
5887 
5888     // If one unique T is found:
5889     // First, build a candidate set from the previously recorded
5890     // potentially viable conversions.
5891     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5892     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5893                                       CandidateSet);
5894 
5895     // Then, perform overload resolution over the candidate set.
5896     OverloadCandidateSet::iterator Best;
5897     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5898     case OR_Success: {
5899       // Apply this conversion.
5900       DeclAccessPair Found =
5901           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5902       if (recordConversion(*this, Loc, From, Converter, T,
5903                            HadMultipleCandidates, Found))
5904         return ExprError();
5905       break;
5906     }
5907     case OR_Ambiguous:
5908       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5909                                          ViableConversions);
5910     case OR_No_Viable_Function:
5911       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5912                                      HadMultipleCandidates,
5913                                      ExplicitConversions))
5914         return ExprError();
5915       LLVM_FALLTHROUGH;
5916     case OR_Deleted:
5917       // We'll complain below about a non-integral condition type.
5918       break;
5919     }
5920   } else {
5921     switch (ViableConversions.size()) {
5922     case 0: {
5923       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5924                                      HadMultipleCandidates,
5925                                      ExplicitConversions))
5926         return ExprError();
5927 
5928       // We'll complain below about a non-integral condition type.
5929       break;
5930     }
5931     case 1: {
5932       // Apply this conversion.
5933       DeclAccessPair Found = ViableConversions[0];
5934       if (recordConversion(*this, Loc, From, Converter, T,
5935                            HadMultipleCandidates, Found))
5936         return ExprError();
5937       break;
5938     }
5939     default:
5940       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5941                                          ViableConversions);
5942     }
5943   }
5944 
5945   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5946 }
5947 
5948 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5949 /// an acceptable non-member overloaded operator for a call whose
5950 /// arguments have types T1 (and, if non-empty, T2). This routine
5951 /// implements the check in C++ [over.match.oper]p3b2 concerning
5952 /// enumeration types.
5953 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5954                                                    FunctionDecl *Fn,
5955                                                    ArrayRef<Expr *> Args) {
5956   QualType T1 = Args[0]->getType();
5957   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5958 
5959   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5960     return true;
5961 
5962   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5963     return true;
5964 
5965   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5966   if (Proto->getNumParams() < 1)
5967     return false;
5968 
5969   if (T1->isEnumeralType()) {
5970     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5971     if (Context.hasSameUnqualifiedType(T1, ArgType))
5972       return true;
5973   }
5974 
5975   if (Proto->getNumParams() < 2)
5976     return false;
5977 
5978   if (!T2.isNull() && T2->isEnumeralType()) {
5979     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5980     if (Context.hasSameUnqualifiedType(T2, ArgType))
5981       return true;
5982   }
5983 
5984   return false;
5985 }
5986 
5987 /// AddOverloadCandidate - Adds the given function to the set of
5988 /// candidate functions, using the given function call arguments.  If
5989 /// @p SuppressUserConversions, then don't allow user-defined
5990 /// conversions via constructors or conversion operators.
5991 ///
5992 /// \param PartialOverloading true if we are performing "partial" overloading
5993 /// based on an incomplete set of function arguments. This feature is used by
5994 /// code completion.
5995 void Sema::AddOverloadCandidate(
5996     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
5997     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
5998     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
5999     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) {
6000   const FunctionProtoType *Proto
6001     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6002   assert(Proto && "Functions without a prototype cannot be overloaded");
6003   assert(!Function->getDescribedFunctionTemplate() &&
6004          "Use AddTemplateOverloadCandidate for function templates");
6005 
6006   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6007     if (!isa<CXXConstructorDecl>(Method)) {
6008       // If we get here, it's because we're calling a member function
6009       // that is named without a member access expression (e.g.,
6010       // "this->f") that was either written explicitly or created
6011       // implicitly. This can happen with a qualified call to a member
6012       // function, e.g., X::f(). We use an empty type for the implied
6013       // object argument (C++ [over.call.func]p3), and the acting context
6014       // is irrelevant.
6015       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6016                          Expr::Classification::makeSimpleLValue(), Args,
6017                          CandidateSet, SuppressUserConversions,
6018                          PartialOverloading, EarlyConversions);
6019       return;
6020     }
6021     // We treat a constructor like a non-member function, since its object
6022     // argument doesn't participate in overload resolution.
6023   }
6024 
6025   if (!CandidateSet.isNewCandidate(Function))
6026     return;
6027 
6028   // C++ [over.match.oper]p3:
6029   //   if no operand has a class type, only those non-member functions in the
6030   //   lookup set that have a first parameter of type T1 or "reference to
6031   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6032   //   is a right operand) a second parameter of type T2 or "reference to
6033   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6034   //   candidate functions.
6035   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6036       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6037     return;
6038 
6039   // C++11 [class.copy]p11: [DR1402]
6040   //   A defaulted move constructor that is defined as deleted is ignored by
6041   //   overload resolution.
6042   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6043   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6044       Constructor->isMoveConstructor())
6045     return;
6046 
6047   // Overload resolution is always an unevaluated context.
6048   EnterExpressionEvaluationContext Unevaluated(
6049       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6050 
6051   // Add this candidate
6052   OverloadCandidate &Candidate =
6053       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6054   Candidate.FoundDecl = FoundDecl;
6055   Candidate.Function = Function;
6056   Candidate.Viable = true;
6057   Candidate.IsSurrogate = false;
6058   Candidate.IsADLCandidate = IsADLCandidate;
6059   Candidate.IgnoreObjectArgument = false;
6060   Candidate.ExplicitCallArguments = Args.size();
6061 
6062   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6063       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6064     Candidate.Viable = false;
6065     Candidate.FailureKind = ovl_non_default_multiversion_function;
6066     return;
6067   }
6068 
6069   if (Constructor) {
6070     // C++ [class.copy]p3:
6071     //   A member function template is never instantiated to perform the copy
6072     //   of a class object to an object of its class type.
6073     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6074     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6075         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6076          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6077                        ClassType))) {
6078       Candidate.Viable = false;
6079       Candidate.FailureKind = ovl_fail_illegal_constructor;
6080       return;
6081     }
6082 
6083     // C++ [over.match.funcs]p8: (proposed DR resolution)
6084     //   A constructor inherited from class type C that has a first parameter
6085     //   of type "reference to P" (including such a constructor instantiated
6086     //   from a template) is excluded from the set of candidate functions when
6087     //   constructing an object of type cv D if the argument list has exactly
6088     //   one argument and D is reference-related to P and P is reference-related
6089     //   to C.
6090     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6091     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6092         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6093       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6094       QualType C = Context.getRecordType(Constructor->getParent());
6095       QualType D = Context.getRecordType(Shadow->getParent());
6096       SourceLocation Loc = Args.front()->getExprLoc();
6097       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6098           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6099         Candidate.Viable = false;
6100         Candidate.FailureKind = ovl_fail_inhctor_slice;
6101         return;
6102       }
6103     }
6104 
6105     // Check that the constructor is capable of constructing an object in the
6106     // destination address space.
6107     if (!Qualifiers::isAddressSpaceSupersetOf(
6108             Constructor->getMethodQualifiers().getAddressSpace(),
6109             CandidateSet.getDestAS())) {
6110       Candidate.Viable = false;
6111       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6112     }
6113   }
6114 
6115   unsigned NumParams = Proto->getNumParams();
6116 
6117   // (C++ 13.3.2p2): A candidate function having fewer than m
6118   // parameters is viable only if it has an ellipsis in its parameter
6119   // list (8.3.5).
6120   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6121       !Proto->isVariadic()) {
6122     Candidate.Viable = false;
6123     Candidate.FailureKind = ovl_fail_too_many_arguments;
6124     return;
6125   }
6126 
6127   // (C++ 13.3.2p2): A candidate function having more than m parameters
6128   // is viable only if the (m+1)st parameter has a default argument
6129   // (8.3.6). For the purposes of overload resolution, the
6130   // parameter list is truncated on the right, so that there are
6131   // exactly m parameters.
6132   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6133   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6134     // Not enough arguments.
6135     Candidate.Viable = false;
6136     Candidate.FailureKind = ovl_fail_too_few_arguments;
6137     return;
6138   }
6139 
6140   // (CUDA B.1): Check for invalid calls between targets.
6141   if (getLangOpts().CUDA)
6142     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6143       // Skip the check for callers that are implicit members, because in this
6144       // case we may not yet know what the member's target is; the target is
6145       // inferred for the member automatically, based on the bases and fields of
6146       // the class.
6147       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6148         Candidate.Viable = false;
6149         Candidate.FailureKind = ovl_fail_bad_target;
6150         return;
6151       }
6152 
6153   // Determine the implicit conversion sequences for each of the
6154   // arguments.
6155   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6156     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6157       // We already formed a conversion sequence for this parameter during
6158       // template argument deduction.
6159     } else if (ArgIdx < NumParams) {
6160       // (C++ 13.3.2p3): for F to be a viable function, there shall
6161       // exist for each argument an implicit conversion sequence
6162       // (13.3.3.1) that converts that argument to the corresponding
6163       // parameter of F.
6164       QualType ParamType = Proto->getParamType(ArgIdx);
6165       Candidate.Conversions[ArgIdx] = TryCopyInitialization(
6166           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6167           /*InOverloadResolution=*/true,
6168           /*AllowObjCWritebackConversion=*/
6169           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6170       if (Candidate.Conversions[ArgIdx].isBad()) {
6171         Candidate.Viable = false;
6172         Candidate.FailureKind = ovl_fail_bad_conversion;
6173         return;
6174       }
6175     } else {
6176       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6177       // argument for which there is no corresponding parameter is
6178       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6179       Candidate.Conversions[ArgIdx].setEllipsis();
6180     }
6181   }
6182 
6183   if (!AllowExplicit) {
6184     ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function);
6185     if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) {
6186       Candidate.Viable = false;
6187       Candidate.FailureKind = ovl_fail_explicit_resolved;
6188       return;
6189     }
6190   }
6191 
6192   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6193     Candidate.Viable = false;
6194     Candidate.FailureKind = ovl_fail_enable_if;
6195     Candidate.DeductionFailure.Data = FailedAttr;
6196     return;
6197   }
6198 
6199   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6200     Candidate.Viable = false;
6201     Candidate.FailureKind = ovl_fail_ext_disabled;
6202     return;
6203   }
6204 }
6205 
6206 ObjCMethodDecl *
6207 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6208                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6209   if (Methods.size() <= 1)
6210     return nullptr;
6211 
6212   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6213     bool Match = true;
6214     ObjCMethodDecl *Method = Methods[b];
6215     unsigned NumNamedArgs = Sel.getNumArgs();
6216     // Method might have more arguments than selector indicates. This is due
6217     // to addition of c-style arguments in method.
6218     if (Method->param_size() > NumNamedArgs)
6219       NumNamedArgs = Method->param_size();
6220     if (Args.size() < NumNamedArgs)
6221       continue;
6222 
6223     for (unsigned i = 0; i < NumNamedArgs; i++) {
6224       // We can't do any type-checking on a type-dependent argument.
6225       if (Args[i]->isTypeDependent()) {
6226         Match = false;
6227         break;
6228       }
6229 
6230       ParmVarDecl *param = Method->parameters()[i];
6231       Expr *argExpr = Args[i];
6232       assert(argExpr && "SelectBestMethod(): missing expression");
6233 
6234       // Strip the unbridged-cast placeholder expression off unless it's
6235       // a consumed argument.
6236       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6237           !param->hasAttr<CFConsumedAttr>())
6238         argExpr = stripARCUnbridgedCast(argExpr);
6239 
6240       // If the parameter is __unknown_anytype, move on to the next method.
6241       if (param->getType() == Context.UnknownAnyTy) {
6242         Match = false;
6243         break;
6244       }
6245 
6246       ImplicitConversionSequence ConversionState
6247         = TryCopyInitialization(*this, argExpr, param->getType(),
6248                                 /*SuppressUserConversions*/false,
6249                                 /*InOverloadResolution=*/true,
6250                                 /*AllowObjCWritebackConversion=*/
6251                                 getLangOpts().ObjCAutoRefCount,
6252                                 /*AllowExplicit*/false);
6253       // This function looks for a reasonably-exact match, so we consider
6254       // incompatible pointer conversions to be a failure here.
6255       if (ConversionState.isBad() ||
6256           (ConversionState.isStandard() &&
6257            ConversionState.Standard.Second ==
6258                ICK_Incompatible_Pointer_Conversion)) {
6259         Match = false;
6260         break;
6261       }
6262     }
6263     // Promote additional arguments to variadic methods.
6264     if (Match && Method->isVariadic()) {
6265       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6266         if (Args[i]->isTypeDependent()) {
6267           Match = false;
6268           break;
6269         }
6270         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6271                                                           nullptr);
6272         if (Arg.isInvalid()) {
6273           Match = false;
6274           break;
6275         }
6276       }
6277     } else {
6278       // Check for extra arguments to non-variadic methods.
6279       if (Args.size() != NumNamedArgs)
6280         Match = false;
6281       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6282         // Special case when selectors have no argument. In this case, select
6283         // one with the most general result type of 'id'.
6284         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6285           QualType ReturnT = Methods[b]->getReturnType();
6286           if (ReturnT->isObjCIdType())
6287             return Methods[b];
6288         }
6289       }
6290     }
6291 
6292     if (Match)
6293       return Method;
6294   }
6295   return nullptr;
6296 }
6297 
6298 static bool
6299 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6300                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6301                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6302                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6303   if (ThisArg) {
6304     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6305     assert(!isa<CXXConstructorDecl>(Method) &&
6306            "Shouldn't have `this` for ctors!");
6307     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6308     ExprResult R = S.PerformObjectArgumentInitialization(
6309         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6310     if (R.isInvalid())
6311       return false;
6312     ConvertedThis = R.get();
6313   } else {
6314     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6315       (void)MD;
6316       assert((MissingImplicitThis || MD->isStatic() ||
6317               isa<CXXConstructorDecl>(MD)) &&
6318              "Expected `this` for non-ctor instance methods");
6319     }
6320     ConvertedThis = nullptr;
6321   }
6322 
6323   // Ignore any variadic arguments. Converting them is pointless, since the
6324   // user can't refer to them in the function condition.
6325   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6326 
6327   // Convert the arguments.
6328   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6329     ExprResult R;
6330     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6331                                         S.Context, Function->getParamDecl(I)),
6332                                     SourceLocation(), Args[I]);
6333 
6334     if (R.isInvalid())
6335       return false;
6336 
6337     ConvertedArgs.push_back(R.get());
6338   }
6339 
6340   if (Trap.hasErrorOccurred())
6341     return false;
6342 
6343   // Push default arguments if needed.
6344   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6345     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6346       ParmVarDecl *P = Function->getParamDecl(i);
6347       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6348                          ? P->getUninstantiatedDefaultArg()
6349                          : P->getDefaultArg();
6350       // This can only happen in code completion, i.e. when PartialOverloading
6351       // is true.
6352       if (!DefArg)
6353         return false;
6354       ExprResult R =
6355           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6356                                           S.Context, Function->getParamDecl(i)),
6357                                       SourceLocation(), DefArg);
6358       if (R.isInvalid())
6359         return false;
6360       ConvertedArgs.push_back(R.get());
6361     }
6362 
6363     if (Trap.hasErrorOccurred())
6364       return false;
6365   }
6366   return true;
6367 }
6368 
6369 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6370                                   bool MissingImplicitThis) {
6371   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6372   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6373     return nullptr;
6374 
6375   SFINAETrap Trap(*this);
6376   SmallVector<Expr *, 16> ConvertedArgs;
6377   // FIXME: We should look into making enable_if late-parsed.
6378   Expr *DiscardedThis;
6379   if (!convertArgsForAvailabilityChecks(
6380           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6381           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6382     return *EnableIfAttrs.begin();
6383 
6384   for (auto *EIA : EnableIfAttrs) {
6385     APValue Result;
6386     // FIXME: This doesn't consider value-dependent cases, because doing so is
6387     // very difficult. Ideally, we should handle them more gracefully.
6388     if (EIA->getCond()->isValueDependent() ||
6389         !EIA->getCond()->EvaluateWithSubstitution(
6390             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6391       return EIA;
6392 
6393     if (!Result.isInt() || !Result.getInt().getBoolValue())
6394       return EIA;
6395   }
6396   return nullptr;
6397 }
6398 
6399 template <typename CheckFn>
6400 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6401                                         bool ArgDependent, SourceLocation Loc,
6402                                         CheckFn &&IsSuccessful) {
6403   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6404   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6405     if (ArgDependent == DIA->getArgDependent())
6406       Attrs.push_back(DIA);
6407   }
6408 
6409   // Common case: No diagnose_if attributes, so we can quit early.
6410   if (Attrs.empty())
6411     return false;
6412 
6413   auto WarningBegin = std::stable_partition(
6414       Attrs.begin(), Attrs.end(),
6415       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6416 
6417   // Note that diagnose_if attributes are late-parsed, so they appear in the
6418   // correct order (unlike enable_if attributes).
6419   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6420                                IsSuccessful);
6421   if (ErrAttr != WarningBegin) {
6422     const DiagnoseIfAttr *DIA = *ErrAttr;
6423     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6424     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6425         << DIA->getParent() << DIA->getCond()->getSourceRange();
6426     return true;
6427   }
6428 
6429   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6430     if (IsSuccessful(DIA)) {
6431       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6432       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6433           << DIA->getParent() << DIA->getCond()->getSourceRange();
6434     }
6435 
6436   return false;
6437 }
6438 
6439 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6440                                                const Expr *ThisArg,
6441                                                ArrayRef<const Expr *> Args,
6442                                                SourceLocation Loc) {
6443   return diagnoseDiagnoseIfAttrsWith(
6444       *this, Function, /*ArgDependent=*/true, Loc,
6445       [&](const DiagnoseIfAttr *DIA) {
6446         APValue Result;
6447         // It's sane to use the same Args for any redecl of this function, since
6448         // EvaluateWithSubstitution only cares about the position of each
6449         // argument in the arg list, not the ParmVarDecl* it maps to.
6450         if (!DIA->getCond()->EvaluateWithSubstitution(
6451                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6452           return false;
6453         return Result.isInt() && Result.getInt().getBoolValue();
6454       });
6455 }
6456 
6457 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6458                                                  SourceLocation Loc) {
6459   return diagnoseDiagnoseIfAttrsWith(
6460       *this, ND, /*ArgDependent=*/false, Loc,
6461       [&](const DiagnoseIfAttr *DIA) {
6462         bool Result;
6463         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6464                Result;
6465       });
6466 }
6467 
6468 /// Add all of the function declarations in the given function set to
6469 /// the overload candidate set.
6470 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6471                                  ArrayRef<Expr *> Args,
6472                                  OverloadCandidateSet &CandidateSet,
6473                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6474                                  bool SuppressUserConversions,
6475                                  bool PartialOverloading,
6476                                  bool FirstArgumentIsBase) {
6477   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6478     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6479     ArrayRef<Expr *> FunctionArgs = Args;
6480 
6481     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6482     FunctionDecl *FD =
6483         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6484 
6485     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6486       QualType ObjectType;
6487       Expr::Classification ObjectClassification;
6488       if (Args.size() > 0) {
6489         if (Expr *E = Args[0]) {
6490           // Use the explicit base to restrict the lookup:
6491           ObjectType = E->getType();
6492           // Pointers in the object arguments are implicitly dereferenced, so we
6493           // always classify them as l-values.
6494           if (!ObjectType.isNull() && ObjectType->isPointerType())
6495             ObjectClassification = Expr::Classification::makeSimpleLValue();
6496           else
6497             ObjectClassification = E->Classify(Context);
6498         } // .. else there is an implicit base.
6499         FunctionArgs = Args.slice(1);
6500       }
6501       if (FunTmpl) {
6502         AddMethodTemplateCandidate(
6503             FunTmpl, F.getPair(),
6504             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6505             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6506             FunctionArgs, CandidateSet, SuppressUserConversions,
6507             PartialOverloading);
6508       } else {
6509         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6510                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6511                            ObjectClassification, FunctionArgs, CandidateSet,
6512                            SuppressUserConversions, PartialOverloading);
6513       }
6514     } else {
6515       // This branch handles both standalone functions and static methods.
6516 
6517       // Slice the first argument (which is the base) when we access
6518       // static method as non-static.
6519       if (Args.size() > 0 &&
6520           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6521                         !isa<CXXConstructorDecl>(FD)))) {
6522         assert(cast<CXXMethodDecl>(FD)->isStatic());
6523         FunctionArgs = Args.slice(1);
6524       }
6525       if (FunTmpl) {
6526         AddTemplateOverloadCandidate(
6527             FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6528             CandidateSet, SuppressUserConversions, PartialOverloading);
6529       } else {
6530         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6531                              SuppressUserConversions, PartialOverloading);
6532       }
6533     }
6534   }
6535 }
6536 
6537 /// AddMethodCandidate - Adds a named decl (which is some kind of
6538 /// method) as a method candidate to the given overload set.
6539 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6540                               QualType ObjectType,
6541                               Expr::Classification ObjectClassification,
6542                               ArrayRef<Expr *> Args,
6543                               OverloadCandidateSet& CandidateSet,
6544                               bool SuppressUserConversions) {
6545   NamedDecl *Decl = FoundDecl.getDecl();
6546   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6547 
6548   if (isa<UsingShadowDecl>(Decl))
6549     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6550 
6551   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6552     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6553            "Expected a member function template");
6554     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6555                                /*ExplicitArgs*/ nullptr, ObjectType,
6556                                ObjectClassification, Args, CandidateSet,
6557                                SuppressUserConversions);
6558   } else {
6559     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6560                        ObjectType, ObjectClassification, Args, CandidateSet,
6561                        SuppressUserConversions);
6562   }
6563 }
6564 
6565 /// AddMethodCandidate - Adds the given C++ member function to the set
6566 /// of candidate functions, using the given function call arguments
6567 /// and the object argument (@c Object). For example, in a call
6568 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6569 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6570 /// allow user-defined conversions via constructors or conversion
6571 /// operators.
6572 void
6573 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6574                          CXXRecordDecl *ActingContext, QualType ObjectType,
6575                          Expr::Classification ObjectClassification,
6576                          ArrayRef<Expr *> Args,
6577                          OverloadCandidateSet &CandidateSet,
6578                          bool SuppressUserConversions,
6579                          bool PartialOverloading,
6580                          ConversionSequenceList EarlyConversions) {
6581   const FunctionProtoType *Proto
6582     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6583   assert(Proto && "Methods without a prototype cannot be overloaded");
6584   assert(!isa<CXXConstructorDecl>(Method) &&
6585          "Use AddOverloadCandidate for constructors");
6586 
6587   if (!CandidateSet.isNewCandidate(Method))
6588     return;
6589 
6590   // C++11 [class.copy]p23: [DR1402]
6591   //   A defaulted move assignment operator that is defined as deleted is
6592   //   ignored by overload resolution.
6593   if (Method->isDefaulted() && Method->isDeleted() &&
6594       Method->isMoveAssignmentOperator())
6595     return;
6596 
6597   // Overload resolution is always an unevaluated context.
6598   EnterExpressionEvaluationContext Unevaluated(
6599       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6600 
6601   // Add this candidate
6602   OverloadCandidate &Candidate =
6603       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6604   Candidate.FoundDecl = FoundDecl;
6605   Candidate.Function = Method;
6606   Candidate.IsSurrogate = false;
6607   Candidate.IgnoreObjectArgument = false;
6608   Candidate.ExplicitCallArguments = Args.size();
6609 
6610   unsigned NumParams = Proto->getNumParams();
6611 
6612   // (C++ 13.3.2p2): A candidate function having fewer than m
6613   // parameters is viable only if it has an ellipsis in its parameter
6614   // list (8.3.5).
6615   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6616       !Proto->isVariadic()) {
6617     Candidate.Viable = false;
6618     Candidate.FailureKind = ovl_fail_too_many_arguments;
6619     return;
6620   }
6621 
6622   // (C++ 13.3.2p2): A candidate function having more than m parameters
6623   // is viable only if the (m+1)st parameter has a default argument
6624   // (8.3.6). For the purposes of overload resolution, the
6625   // parameter list is truncated on the right, so that there are
6626   // exactly m parameters.
6627   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6628   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6629     // Not enough arguments.
6630     Candidate.Viable = false;
6631     Candidate.FailureKind = ovl_fail_too_few_arguments;
6632     return;
6633   }
6634 
6635   Candidate.Viable = true;
6636 
6637   if (Method->isStatic() || ObjectType.isNull())
6638     // The implicit object argument is ignored.
6639     Candidate.IgnoreObjectArgument = true;
6640   else {
6641     // Determine the implicit conversion sequence for the object
6642     // parameter.
6643     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6644         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6645         Method, ActingContext);
6646     if (Candidate.Conversions[0].isBad()) {
6647       Candidate.Viable = false;
6648       Candidate.FailureKind = ovl_fail_bad_conversion;
6649       return;
6650     }
6651   }
6652 
6653   // (CUDA B.1): Check for invalid calls between targets.
6654   if (getLangOpts().CUDA)
6655     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6656       if (!IsAllowedCUDACall(Caller, Method)) {
6657         Candidate.Viable = false;
6658         Candidate.FailureKind = ovl_fail_bad_target;
6659         return;
6660       }
6661 
6662   // Determine the implicit conversion sequences for each of the
6663   // arguments.
6664   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6665     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6666       // We already formed a conversion sequence for this parameter during
6667       // template argument deduction.
6668     } else if (ArgIdx < NumParams) {
6669       // (C++ 13.3.2p3): for F to be a viable function, there shall
6670       // exist for each argument an implicit conversion sequence
6671       // (13.3.3.1) that converts that argument to the corresponding
6672       // parameter of F.
6673       QualType ParamType = Proto->getParamType(ArgIdx);
6674       Candidate.Conversions[ArgIdx + 1]
6675         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6676                                 SuppressUserConversions,
6677                                 /*InOverloadResolution=*/true,
6678                                 /*AllowObjCWritebackConversion=*/
6679                                   getLangOpts().ObjCAutoRefCount);
6680       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6681         Candidate.Viable = false;
6682         Candidate.FailureKind = ovl_fail_bad_conversion;
6683         return;
6684       }
6685     } else {
6686       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6687       // argument for which there is no corresponding parameter is
6688       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6689       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6690     }
6691   }
6692 
6693   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6694     Candidate.Viable = false;
6695     Candidate.FailureKind = ovl_fail_enable_if;
6696     Candidate.DeductionFailure.Data = FailedAttr;
6697     return;
6698   }
6699 
6700   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6701       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6702     Candidate.Viable = false;
6703     Candidate.FailureKind = ovl_non_default_multiversion_function;
6704   }
6705 }
6706 
6707 /// Add a C++ member function template as a candidate to the candidate
6708 /// set, using template argument deduction to produce an appropriate member
6709 /// function template specialization.
6710 void
6711 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6712                                  DeclAccessPair FoundDecl,
6713                                  CXXRecordDecl *ActingContext,
6714                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6715                                  QualType ObjectType,
6716                                  Expr::Classification ObjectClassification,
6717                                  ArrayRef<Expr *> Args,
6718                                  OverloadCandidateSet& CandidateSet,
6719                                  bool SuppressUserConversions,
6720                                  bool PartialOverloading) {
6721   if (!CandidateSet.isNewCandidate(MethodTmpl))
6722     return;
6723 
6724   // C++ [over.match.funcs]p7:
6725   //   In each case where a candidate is a function template, candidate
6726   //   function template specializations are generated using template argument
6727   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6728   //   candidate functions in the usual way.113) A given name can refer to one
6729   //   or more function templates and also to a set of overloaded non-template
6730   //   functions. In such a case, the candidate functions generated from each
6731   //   function template are combined with the set of non-template candidate
6732   //   functions.
6733   TemplateDeductionInfo Info(CandidateSet.getLocation());
6734   FunctionDecl *Specialization = nullptr;
6735   ConversionSequenceList Conversions;
6736   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6737           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6738           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6739             return CheckNonDependentConversions(
6740                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6741                 SuppressUserConversions, ActingContext, ObjectType,
6742                 ObjectClassification);
6743           })) {
6744     OverloadCandidate &Candidate =
6745         CandidateSet.addCandidate(Conversions.size(), Conversions);
6746     Candidate.FoundDecl = FoundDecl;
6747     Candidate.Function = MethodTmpl->getTemplatedDecl();
6748     Candidate.Viable = false;
6749     Candidate.IsSurrogate = false;
6750     Candidate.IgnoreObjectArgument =
6751         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6752         ObjectType.isNull();
6753     Candidate.ExplicitCallArguments = Args.size();
6754     if (Result == TDK_NonDependentConversionFailure)
6755       Candidate.FailureKind = ovl_fail_bad_conversion;
6756     else {
6757       Candidate.FailureKind = ovl_fail_bad_deduction;
6758       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6759                                                             Info);
6760     }
6761     return;
6762   }
6763 
6764   // Add the function template specialization produced by template argument
6765   // deduction as a candidate.
6766   assert(Specialization && "Missing member function template specialization?");
6767   assert(isa<CXXMethodDecl>(Specialization) &&
6768          "Specialization is not a member function?");
6769   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6770                      ActingContext, ObjectType, ObjectClassification, Args,
6771                      CandidateSet, SuppressUserConversions, PartialOverloading,
6772                      Conversions);
6773 }
6774 
6775 /// Add a C++ function template specialization as a candidate
6776 /// in the candidate set, using template argument deduction to produce
6777 /// an appropriate function template specialization.
6778 void Sema::AddTemplateOverloadCandidate(
6779     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6780     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6781     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6782     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) {
6783   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6784     return;
6785 
6786   // C++ [over.match.funcs]p7:
6787   //   In each case where a candidate is a function template, candidate
6788   //   function template specializations are generated using template argument
6789   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6790   //   candidate functions in the usual way.113) A given name can refer to one
6791   //   or more function templates and also to a set of overloaded non-template
6792   //   functions. In such a case, the candidate functions generated from each
6793   //   function template are combined with the set of non-template candidate
6794   //   functions.
6795   TemplateDeductionInfo Info(CandidateSet.getLocation());
6796   FunctionDecl *Specialization = nullptr;
6797   ConversionSequenceList Conversions;
6798   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6799           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6800           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6801             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6802                                                 Args, CandidateSet, Conversions,
6803                                                 SuppressUserConversions);
6804           })) {
6805     OverloadCandidate &Candidate =
6806         CandidateSet.addCandidate(Conversions.size(), Conversions);
6807     Candidate.FoundDecl = FoundDecl;
6808     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6809     Candidate.Viable = false;
6810     Candidate.IsSurrogate = false;
6811     Candidate.IsADLCandidate = IsADLCandidate;
6812     // Ignore the object argument if there is one, since we don't have an object
6813     // type.
6814     Candidate.IgnoreObjectArgument =
6815         isa<CXXMethodDecl>(Candidate.Function) &&
6816         !isa<CXXConstructorDecl>(Candidate.Function);
6817     Candidate.ExplicitCallArguments = Args.size();
6818     if (Result == TDK_NonDependentConversionFailure)
6819       Candidate.FailureKind = ovl_fail_bad_conversion;
6820     else {
6821       Candidate.FailureKind = ovl_fail_bad_deduction;
6822       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6823                                                             Info);
6824     }
6825     return;
6826   }
6827 
6828   // Add the function template specialization produced by template argument
6829   // deduction as a candidate.
6830   assert(Specialization && "Missing function template specialization?");
6831   AddOverloadCandidate(
6832       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
6833       PartialOverloading, AllowExplicit,
6834       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions);
6835 }
6836 
6837 /// Check that implicit conversion sequences can be formed for each argument
6838 /// whose corresponding parameter has a non-dependent type, per DR1391's
6839 /// [temp.deduct.call]p10.
6840 bool Sema::CheckNonDependentConversions(
6841     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6842     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6843     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6844     CXXRecordDecl *ActingContext, QualType ObjectType,
6845     Expr::Classification ObjectClassification) {
6846   // FIXME: The cases in which we allow explicit conversions for constructor
6847   // arguments never consider calling a constructor template. It's not clear
6848   // that is correct.
6849   const bool AllowExplicit = false;
6850 
6851   auto *FD = FunctionTemplate->getTemplatedDecl();
6852   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6853   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6854   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6855 
6856   Conversions =
6857       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6858 
6859   // Overload resolution is always an unevaluated context.
6860   EnterExpressionEvaluationContext Unevaluated(
6861       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6862 
6863   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6864   // require that, but this check should never result in a hard error, and
6865   // overload resolution is permitted to sidestep instantiations.
6866   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6867       !ObjectType.isNull()) {
6868     Conversions[0] = TryObjectArgumentInitialization(
6869         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6870         Method, ActingContext);
6871     if (Conversions[0].isBad())
6872       return true;
6873   }
6874 
6875   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6876        ++I) {
6877     QualType ParamType = ParamTypes[I];
6878     if (!ParamType->isDependentType()) {
6879       Conversions[ThisConversions + I]
6880         = TryCopyInitialization(*this, Args[I], ParamType,
6881                                 SuppressUserConversions,
6882                                 /*InOverloadResolution=*/true,
6883                                 /*AllowObjCWritebackConversion=*/
6884                                   getLangOpts().ObjCAutoRefCount,
6885                                 AllowExplicit);
6886       if (Conversions[ThisConversions + I].isBad())
6887         return true;
6888     }
6889   }
6890 
6891   return false;
6892 }
6893 
6894 /// Determine whether this is an allowable conversion from the result
6895 /// of an explicit conversion operator to the expected type, per C++
6896 /// [over.match.conv]p1 and [over.match.ref]p1.
6897 ///
6898 /// \param ConvType The return type of the conversion function.
6899 ///
6900 /// \param ToType The type we are converting to.
6901 ///
6902 /// \param AllowObjCPointerConversion Allow a conversion from one
6903 /// Objective-C pointer to another.
6904 ///
6905 /// \returns true if the conversion is allowable, false otherwise.
6906 static bool isAllowableExplicitConversion(Sema &S,
6907                                           QualType ConvType, QualType ToType,
6908                                           bool AllowObjCPointerConversion) {
6909   QualType ToNonRefType = ToType.getNonReferenceType();
6910 
6911   // Easy case: the types are the same.
6912   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6913     return true;
6914 
6915   // Allow qualification conversions.
6916   bool ObjCLifetimeConversion;
6917   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6918                                   ObjCLifetimeConversion))
6919     return true;
6920 
6921   // If we're not allowed to consider Objective-C pointer conversions,
6922   // we're done.
6923   if (!AllowObjCPointerConversion)
6924     return false;
6925 
6926   // Is this an Objective-C pointer conversion?
6927   bool IncompatibleObjC = false;
6928   QualType ConvertedType;
6929   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6930                                    IncompatibleObjC);
6931 }
6932 
6933 /// AddConversionCandidate - Add a C++ conversion function as a
6934 /// candidate in the candidate set (C++ [over.match.conv],
6935 /// C++ [over.match.copy]). From is the expression we're converting from,
6936 /// and ToType is the type that we're eventually trying to convert to
6937 /// (which may or may not be the same type as the type that the
6938 /// conversion function produces).
6939 void Sema::AddConversionCandidate(
6940     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
6941     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
6942     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
6943     bool AllowExplicit, bool AllowResultConversion) {
6944   assert(!Conversion->getDescribedFunctionTemplate() &&
6945          "Conversion function templates use AddTemplateConversionCandidate");
6946   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6947   if (!CandidateSet.isNewCandidate(Conversion))
6948     return;
6949 
6950   // If the conversion function has an undeduced return type, trigger its
6951   // deduction now.
6952   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6953     if (DeduceReturnType(Conversion, From->getExprLoc()))
6954       return;
6955     ConvType = Conversion->getConversionType().getNonReferenceType();
6956   }
6957 
6958   // If we don't allow any conversion of the result type, ignore conversion
6959   // functions that don't convert to exactly (possibly cv-qualified) T.
6960   if (!AllowResultConversion &&
6961       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6962     return;
6963 
6964   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6965   // operator is only a candidate if its return type is the target type or
6966   // can be converted to the target type with a qualification conversion.
6967   if (Conversion->isExplicit() &&
6968       !isAllowableExplicitConversion(*this, ConvType, ToType,
6969                                      AllowObjCConversionOnExplicit))
6970     return;
6971 
6972   // Overload resolution is always an unevaluated context.
6973   EnterExpressionEvaluationContext Unevaluated(
6974       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6975 
6976   // Add this candidate
6977   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6978   Candidate.FoundDecl = FoundDecl;
6979   Candidate.Function = Conversion;
6980   Candidate.IsSurrogate = false;
6981   Candidate.IgnoreObjectArgument = false;
6982   Candidate.FinalConversion.setAsIdentityConversion();
6983   Candidate.FinalConversion.setFromType(ConvType);
6984   Candidate.FinalConversion.setAllToTypes(ToType);
6985   Candidate.Viable = true;
6986   Candidate.ExplicitCallArguments = 1;
6987 
6988   // C++ [over.match.funcs]p4:
6989   //   For conversion functions, the function is considered to be a member of
6990   //   the class of the implicit implied object argument for the purpose of
6991   //   defining the type of the implicit object parameter.
6992   //
6993   // Determine the implicit conversion sequence for the implicit
6994   // object parameter.
6995   QualType ImplicitParamType = From->getType();
6996   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6997     ImplicitParamType = FromPtrType->getPointeeType();
6998   CXXRecordDecl *ConversionContext
6999     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
7000 
7001   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7002       *this, CandidateSet.getLocation(), From->getType(),
7003       From->Classify(Context), Conversion, ConversionContext);
7004 
7005   if (Candidate.Conversions[0].isBad()) {
7006     Candidate.Viable = false;
7007     Candidate.FailureKind = ovl_fail_bad_conversion;
7008     return;
7009   }
7010 
7011   // We won't go through a user-defined type conversion function to convert a
7012   // derived to base as such conversions are given Conversion Rank. They only
7013   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7014   QualType FromCanon
7015     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7016   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7017   if (FromCanon == ToCanon ||
7018       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7019     Candidate.Viable = false;
7020     Candidate.FailureKind = ovl_fail_trivial_conversion;
7021     return;
7022   }
7023 
7024   // To determine what the conversion from the result of calling the
7025   // conversion function to the type we're eventually trying to
7026   // convert to (ToType), we need to synthesize a call to the
7027   // conversion function and attempt copy initialization from it. This
7028   // makes sure that we get the right semantics with respect to
7029   // lvalues/rvalues and the type. Fortunately, we can allocate this
7030   // call on the stack and we don't need its arguments to be
7031   // well-formed.
7032   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7033                             VK_LValue, From->getBeginLoc());
7034   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7035                                 Context.getPointerType(Conversion->getType()),
7036                                 CK_FunctionToPointerDecay,
7037                                 &ConversionRef, VK_RValue);
7038 
7039   QualType ConversionType = Conversion->getConversionType();
7040   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7041     Candidate.Viable = false;
7042     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7043     return;
7044   }
7045 
7046   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7047 
7048   // Note that it is safe to allocate CallExpr on the stack here because
7049   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7050   // allocator).
7051   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7052 
7053   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7054   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7055       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7056 
7057   ImplicitConversionSequence ICS =
7058       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7059                             /*SuppressUserConversions=*/true,
7060                             /*InOverloadResolution=*/false,
7061                             /*AllowObjCWritebackConversion=*/false);
7062 
7063   switch (ICS.getKind()) {
7064   case ImplicitConversionSequence::StandardConversion:
7065     Candidate.FinalConversion = ICS.Standard;
7066 
7067     // C++ [over.ics.user]p3:
7068     //   If the user-defined conversion is specified by a specialization of a
7069     //   conversion function template, the second standard conversion sequence
7070     //   shall have exact match rank.
7071     if (Conversion->getPrimaryTemplate() &&
7072         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7073       Candidate.Viable = false;
7074       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7075       return;
7076     }
7077 
7078     // C++0x [dcl.init.ref]p5:
7079     //    In the second case, if the reference is an rvalue reference and
7080     //    the second standard conversion sequence of the user-defined
7081     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7082     //    program is ill-formed.
7083     if (ToType->isRValueReferenceType() &&
7084         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7085       Candidate.Viable = false;
7086       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7087       return;
7088     }
7089     break;
7090 
7091   case ImplicitConversionSequence::BadConversion:
7092     Candidate.Viable = false;
7093     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7094     return;
7095 
7096   default:
7097     llvm_unreachable(
7098            "Can only end up with a standard conversion sequence or failure");
7099   }
7100 
7101   if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() !=
7102                             ExplicitSpecKind::ResolvedFalse) {
7103     Candidate.Viable = false;
7104     Candidate.FailureKind = ovl_fail_explicit_resolved;
7105     return;
7106   }
7107 
7108   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7109     Candidate.Viable = false;
7110     Candidate.FailureKind = ovl_fail_enable_if;
7111     Candidate.DeductionFailure.Data = FailedAttr;
7112     return;
7113   }
7114 
7115   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7116       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7117     Candidate.Viable = false;
7118     Candidate.FailureKind = ovl_non_default_multiversion_function;
7119   }
7120 }
7121 
7122 /// Adds a conversion function template specialization
7123 /// candidate to the overload set, using template argument deduction
7124 /// to deduce the template arguments of the conversion function
7125 /// template from the type that we are converting to (C++
7126 /// [temp.deduct.conv]).
7127 void Sema::AddTemplateConversionCandidate(
7128     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7129     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7130     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7131     bool AllowExplicit, bool AllowResultConversion) {
7132   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7133          "Only conversion function templates permitted here");
7134 
7135   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7136     return;
7137 
7138   TemplateDeductionInfo Info(CandidateSet.getLocation());
7139   CXXConversionDecl *Specialization = nullptr;
7140   if (TemplateDeductionResult Result
7141         = DeduceTemplateArguments(FunctionTemplate, ToType,
7142                                   Specialization, Info)) {
7143     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7144     Candidate.FoundDecl = FoundDecl;
7145     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7146     Candidate.Viable = false;
7147     Candidate.FailureKind = ovl_fail_bad_deduction;
7148     Candidate.IsSurrogate = false;
7149     Candidate.IgnoreObjectArgument = false;
7150     Candidate.ExplicitCallArguments = 1;
7151     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7152                                                           Info);
7153     return;
7154   }
7155 
7156   // Add the conversion function template specialization produced by
7157   // template argument deduction as a candidate.
7158   assert(Specialization && "Missing function template specialization?");
7159   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7160                          CandidateSet, AllowObjCConversionOnExplicit,
7161                          AllowExplicit, AllowResultConversion);
7162 }
7163 
7164 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7165 /// converts the given @c Object to a function pointer via the
7166 /// conversion function @c Conversion, and then attempts to call it
7167 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7168 /// the type of function that we'll eventually be calling.
7169 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7170                                  DeclAccessPair FoundDecl,
7171                                  CXXRecordDecl *ActingContext,
7172                                  const FunctionProtoType *Proto,
7173                                  Expr *Object,
7174                                  ArrayRef<Expr *> Args,
7175                                  OverloadCandidateSet& CandidateSet) {
7176   if (!CandidateSet.isNewCandidate(Conversion))
7177     return;
7178 
7179   // Overload resolution is always an unevaluated context.
7180   EnterExpressionEvaluationContext Unevaluated(
7181       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7182 
7183   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7184   Candidate.FoundDecl = FoundDecl;
7185   Candidate.Function = nullptr;
7186   Candidate.Surrogate = Conversion;
7187   Candidate.Viable = true;
7188   Candidate.IsSurrogate = true;
7189   Candidate.IgnoreObjectArgument = false;
7190   Candidate.ExplicitCallArguments = Args.size();
7191 
7192   // Determine the implicit conversion sequence for the implicit
7193   // object parameter.
7194   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7195       *this, CandidateSet.getLocation(), Object->getType(),
7196       Object->Classify(Context), Conversion, ActingContext);
7197   if (ObjectInit.isBad()) {
7198     Candidate.Viable = false;
7199     Candidate.FailureKind = ovl_fail_bad_conversion;
7200     Candidate.Conversions[0] = ObjectInit;
7201     return;
7202   }
7203 
7204   // The first conversion is actually a user-defined conversion whose
7205   // first conversion is ObjectInit's standard conversion (which is
7206   // effectively a reference binding). Record it as such.
7207   Candidate.Conversions[0].setUserDefined();
7208   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7209   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7210   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7211   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7212   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7213   Candidate.Conversions[0].UserDefined.After
7214     = Candidate.Conversions[0].UserDefined.Before;
7215   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7216 
7217   // Find the
7218   unsigned NumParams = Proto->getNumParams();
7219 
7220   // (C++ 13.3.2p2): A candidate function having fewer than m
7221   // parameters is viable only if it has an ellipsis in its parameter
7222   // list (8.3.5).
7223   if (Args.size() > NumParams && !Proto->isVariadic()) {
7224     Candidate.Viable = false;
7225     Candidate.FailureKind = ovl_fail_too_many_arguments;
7226     return;
7227   }
7228 
7229   // Function types don't have any default arguments, so just check if
7230   // we have enough arguments.
7231   if (Args.size() < NumParams) {
7232     // Not enough arguments.
7233     Candidate.Viable = false;
7234     Candidate.FailureKind = ovl_fail_too_few_arguments;
7235     return;
7236   }
7237 
7238   // Determine the implicit conversion sequences for each of the
7239   // arguments.
7240   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7241     if (ArgIdx < NumParams) {
7242       // (C++ 13.3.2p3): for F to be a viable function, there shall
7243       // exist for each argument an implicit conversion sequence
7244       // (13.3.3.1) that converts that argument to the corresponding
7245       // parameter of F.
7246       QualType ParamType = Proto->getParamType(ArgIdx);
7247       Candidate.Conversions[ArgIdx + 1]
7248         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7249                                 /*SuppressUserConversions=*/false,
7250                                 /*InOverloadResolution=*/false,
7251                                 /*AllowObjCWritebackConversion=*/
7252                                   getLangOpts().ObjCAutoRefCount);
7253       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7254         Candidate.Viable = false;
7255         Candidate.FailureKind = ovl_fail_bad_conversion;
7256         return;
7257       }
7258     } else {
7259       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7260       // argument for which there is no corresponding parameter is
7261       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7262       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7263     }
7264   }
7265 
7266   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7267     Candidate.Viable = false;
7268     Candidate.FailureKind = ovl_fail_enable_if;
7269     Candidate.DeductionFailure.Data = FailedAttr;
7270     return;
7271   }
7272 }
7273 
7274 /// Add overload candidates for overloaded operators that are
7275 /// member functions.
7276 ///
7277 /// Add the overloaded operator candidates that are member functions
7278 /// for the operator Op that was used in an operator expression such
7279 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7280 /// CandidateSet will store the added overload candidates. (C++
7281 /// [over.match.oper]).
7282 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7283                                        SourceLocation OpLoc,
7284                                        ArrayRef<Expr *> Args,
7285                                        OverloadCandidateSet& CandidateSet,
7286                                        SourceRange OpRange) {
7287   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7288 
7289   // C++ [over.match.oper]p3:
7290   //   For a unary operator @ with an operand of a type whose
7291   //   cv-unqualified version is T1, and for a binary operator @ with
7292   //   a left operand of a type whose cv-unqualified version is T1 and
7293   //   a right operand of a type whose cv-unqualified version is T2,
7294   //   three sets of candidate functions, designated member
7295   //   candidates, non-member candidates and built-in candidates, are
7296   //   constructed as follows:
7297   QualType T1 = Args[0]->getType();
7298 
7299   //     -- If T1 is a complete class type or a class currently being
7300   //        defined, the set of member candidates is the result of the
7301   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7302   //        the set of member candidates is empty.
7303   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7304     // Complete the type if it can be completed.
7305     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7306       return;
7307     // If the type is neither complete nor being defined, bail out now.
7308     if (!T1Rec->getDecl()->getDefinition())
7309       return;
7310 
7311     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7312     LookupQualifiedName(Operators, T1Rec->getDecl());
7313     Operators.suppressDiagnostics();
7314 
7315     for (LookupResult::iterator Oper = Operators.begin(),
7316                              OperEnd = Operators.end();
7317          Oper != OperEnd;
7318          ++Oper)
7319       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7320                          Args[0]->Classify(Context), Args.slice(1),
7321                          CandidateSet, /*SuppressUserConversion=*/false);
7322   }
7323 }
7324 
7325 /// AddBuiltinCandidate - Add a candidate for a built-in
7326 /// operator. ResultTy and ParamTys are the result and parameter types
7327 /// of the built-in candidate, respectively. Args and NumArgs are the
7328 /// arguments being passed to the candidate. IsAssignmentOperator
7329 /// should be true when this built-in candidate is an assignment
7330 /// operator. NumContextualBoolArguments is the number of arguments
7331 /// (at the beginning of the argument list) that will be contextually
7332 /// converted to bool.
7333 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7334                                OverloadCandidateSet& CandidateSet,
7335                                bool IsAssignmentOperator,
7336                                unsigned NumContextualBoolArguments) {
7337   // Overload resolution is always an unevaluated context.
7338   EnterExpressionEvaluationContext Unevaluated(
7339       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7340 
7341   // Add this candidate
7342   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7343   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7344   Candidate.Function = nullptr;
7345   Candidate.IsSurrogate = false;
7346   Candidate.IgnoreObjectArgument = false;
7347   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7348 
7349   // Determine the implicit conversion sequences for each of the
7350   // arguments.
7351   Candidate.Viable = true;
7352   Candidate.ExplicitCallArguments = Args.size();
7353   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7354     // C++ [over.match.oper]p4:
7355     //   For the built-in assignment operators, conversions of the
7356     //   left operand are restricted as follows:
7357     //     -- no temporaries are introduced to hold the left operand, and
7358     //     -- no user-defined conversions are applied to the left
7359     //        operand to achieve a type match with the left-most
7360     //        parameter of a built-in candidate.
7361     //
7362     // We block these conversions by turning off user-defined
7363     // conversions, since that is the only way that initialization of
7364     // a reference to a non-class type can occur from something that
7365     // is not of the same type.
7366     if (ArgIdx < NumContextualBoolArguments) {
7367       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7368              "Contextual conversion to bool requires bool type");
7369       Candidate.Conversions[ArgIdx]
7370         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7371     } else {
7372       Candidate.Conversions[ArgIdx]
7373         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7374                                 ArgIdx == 0 && IsAssignmentOperator,
7375                                 /*InOverloadResolution=*/false,
7376                                 /*AllowObjCWritebackConversion=*/
7377                                   getLangOpts().ObjCAutoRefCount);
7378     }
7379     if (Candidate.Conversions[ArgIdx].isBad()) {
7380       Candidate.Viable = false;
7381       Candidate.FailureKind = ovl_fail_bad_conversion;
7382       break;
7383     }
7384   }
7385 }
7386 
7387 namespace {
7388 
7389 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7390 /// candidate operator functions for built-in operators (C++
7391 /// [over.built]). The types are separated into pointer types and
7392 /// enumeration types.
7393 class BuiltinCandidateTypeSet  {
7394   /// TypeSet - A set of types.
7395   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7396                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7397 
7398   /// PointerTypes - The set of pointer types that will be used in the
7399   /// built-in candidates.
7400   TypeSet PointerTypes;
7401 
7402   /// MemberPointerTypes - The set of member pointer types that will be
7403   /// used in the built-in candidates.
7404   TypeSet MemberPointerTypes;
7405 
7406   /// EnumerationTypes - The set of enumeration types that will be
7407   /// used in the built-in candidates.
7408   TypeSet EnumerationTypes;
7409 
7410   /// The set of vector types that will be used in the built-in
7411   /// candidates.
7412   TypeSet VectorTypes;
7413 
7414   /// A flag indicating non-record types are viable candidates
7415   bool HasNonRecordTypes;
7416 
7417   /// A flag indicating whether either arithmetic or enumeration types
7418   /// were present in the candidate set.
7419   bool HasArithmeticOrEnumeralTypes;
7420 
7421   /// A flag indicating whether the nullptr type was present in the
7422   /// candidate set.
7423   bool HasNullPtrType;
7424 
7425   /// Sema - The semantic analysis instance where we are building the
7426   /// candidate type set.
7427   Sema &SemaRef;
7428 
7429   /// Context - The AST context in which we will build the type sets.
7430   ASTContext &Context;
7431 
7432   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7433                                                const Qualifiers &VisibleQuals);
7434   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7435 
7436 public:
7437   /// iterator - Iterates through the types that are part of the set.
7438   typedef TypeSet::iterator iterator;
7439 
7440   BuiltinCandidateTypeSet(Sema &SemaRef)
7441     : HasNonRecordTypes(false),
7442       HasArithmeticOrEnumeralTypes(false),
7443       HasNullPtrType(false),
7444       SemaRef(SemaRef),
7445       Context(SemaRef.Context) { }
7446 
7447   void AddTypesConvertedFrom(QualType Ty,
7448                              SourceLocation Loc,
7449                              bool AllowUserConversions,
7450                              bool AllowExplicitConversions,
7451                              const Qualifiers &VisibleTypeConversionsQuals);
7452 
7453   /// pointer_begin - First pointer type found;
7454   iterator pointer_begin() { return PointerTypes.begin(); }
7455 
7456   /// pointer_end - Past the last pointer type found;
7457   iterator pointer_end() { return PointerTypes.end(); }
7458 
7459   /// member_pointer_begin - First member pointer type found;
7460   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7461 
7462   /// member_pointer_end - Past the last member pointer type found;
7463   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7464 
7465   /// enumeration_begin - First enumeration type found;
7466   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7467 
7468   /// enumeration_end - Past the last enumeration type found;
7469   iterator enumeration_end() { return EnumerationTypes.end(); }
7470 
7471   iterator vector_begin() { return VectorTypes.begin(); }
7472   iterator vector_end() { return VectorTypes.end(); }
7473 
7474   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7475   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7476   bool hasNullPtrType() const { return HasNullPtrType; }
7477 };
7478 
7479 } // end anonymous namespace
7480 
7481 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7482 /// the set of pointer types along with any more-qualified variants of
7483 /// that type. For example, if @p Ty is "int const *", this routine
7484 /// will add "int const *", "int const volatile *", "int const
7485 /// restrict *", and "int const volatile restrict *" to the set of
7486 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7487 /// false otherwise.
7488 ///
7489 /// FIXME: what to do about extended qualifiers?
7490 bool
7491 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7492                                              const Qualifiers &VisibleQuals) {
7493 
7494   // Insert this type.
7495   if (!PointerTypes.insert(Ty))
7496     return false;
7497 
7498   QualType PointeeTy;
7499   const PointerType *PointerTy = Ty->getAs<PointerType>();
7500   bool buildObjCPtr = false;
7501   if (!PointerTy) {
7502     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7503     PointeeTy = PTy->getPointeeType();
7504     buildObjCPtr = true;
7505   } else {
7506     PointeeTy = PointerTy->getPointeeType();
7507   }
7508 
7509   // Don't add qualified variants of arrays. For one, they're not allowed
7510   // (the qualifier would sink to the element type), and for another, the
7511   // only overload situation where it matters is subscript or pointer +- int,
7512   // and those shouldn't have qualifier variants anyway.
7513   if (PointeeTy->isArrayType())
7514     return true;
7515 
7516   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7517   bool hasVolatile = VisibleQuals.hasVolatile();
7518   bool hasRestrict = VisibleQuals.hasRestrict();
7519 
7520   // Iterate through all strict supersets of BaseCVR.
7521   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7522     if ((CVR | BaseCVR) != CVR) continue;
7523     // Skip over volatile if no volatile found anywhere in the types.
7524     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7525 
7526     // Skip over restrict if no restrict found anywhere in the types, or if
7527     // the type cannot be restrict-qualified.
7528     if ((CVR & Qualifiers::Restrict) &&
7529         (!hasRestrict ||
7530          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7531       continue;
7532 
7533     // Build qualified pointee type.
7534     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7535 
7536     // Build qualified pointer type.
7537     QualType QPointerTy;
7538     if (!buildObjCPtr)
7539       QPointerTy = Context.getPointerType(QPointeeTy);
7540     else
7541       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7542 
7543     // Insert qualified pointer type.
7544     PointerTypes.insert(QPointerTy);
7545   }
7546 
7547   return true;
7548 }
7549 
7550 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7551 /// to the set of pointer types along with any more-qualified variants of
7552 /// that type. For example, if @p Ty is "int const *", this routine
7553 /// will add "int const *", "int const volatile *", "int const
7554 /// restrict *", and "int const volatile restrict *" to the set of
7555 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7556 /// false otherwise.
7557 ///
7558 /// FIXME: what to do about extended qualifiers?
7559 bool
7560 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7561     QualType Ty) {
7562   // Insert this type.
7563   if (!MemberPointerTypes.insert(Ty))
7564     return false;
7565 
7566   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7567   assert(PointerTy && "type was not a member pointer type!");
7568 
7569   QualType PointeeTy = PointerTy->getPointeeType();
7570   // Don't add qualified variants of arrays. For one, they're not allowed
7571   // (the qualifier would sink to the element type), and for another, the
7572   // only overload situation where it matters is subscript or pointer +- int,
7573   // and those shouldn't have qualifier variants anyway.
7574   if (PointeeTy->isArrayType())
7575     return true;
7576   const Type *ClassTy = PointerTy->getClass();
7577 
7578   // Iterate through all strict supersets of the pointee type's CVR
7579   // qualifiers.
7580   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7581   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7582     if ((CVR | BaseCVR) != CVR) continue;
7583 
7584     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7585     MemberPointerTypes.insert(
7586       Context.getMemberPointerType(QPointeeTy, ClassTy));
7587   }
7588 
7589   return true;
7590 }
7591 
7592 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7593 /// Ty can be implicit converted to the given set of @p Types. We're
7594 /// primarily interested in pointer types and enumeration types. We also
7595 /// take member pointer types, for the conditional operator.
7596 /// AllowUserConversions is true if we should look at the conversion
7597 /// functions of a class type, and AllowExplicitConversions if we
7598 /// should also include the explicit conversion functions of a class
7599 /// type.
7600 void
7601 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7602                                                SourceLocation Loc,
7603                                                bool AllowUserConversions,
7604                                                bool AllowExplicitConversions,
7605                                                const Qualifiers &VisibleQuals) {
7606   // Only deal with canonical types.
7607   Ty = Context.getCanonicalType(Ty);
7608 
7609   // Look through reference types; they aren't part of the type of an
7610   // expression for the purposes of conversions.
7611   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7612     Ty = RefTy->getPointeeType();
7613 
7614   // If we're dealing with an array type, decay to the pointer.
7615   if (Ty->isArrayType())
7616     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7617 
7618   // Otherwise, we don't care about qualifiers on the type.
7619   Ty = Ty.getLocalUnqualifiedType();
7620 
7621   // Flag if we ever add a non-record type.
7622   const RecordType *TyRec = Ty->getAs<RecordType>();
7623   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7624 
7625   // Flag if we encounter an arithmetic type.
7626   HasArithmeticOrEnumeralTypes =
7627     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7628 
7629   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7630     PointerTypes.insert(Ty);
7631   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7632     // Insert our type, and its more-qualified variants, into the set
7633     // of types.
7634     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7635       return;
7636   } else if (Ty->isMemberPointerType()) {
7637     // Member pointers are far easier, since the pointee can't be converted.
7638     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7639       return;
7640   } else if (Ty->isEnumeralType()) {
7641     HasArithmeticOrEnumeralTypes = true;
7642     EnumerationTypes.insert(Ty);
7643   } else if (Ty->isVectorType()) {
7644     // We treat vector types as arithmetic types in many contexts as an
7645     // extension.
7646     HasArithmeticOrEnumeralTypes = true;
7647     VectorTypes.insert(Ty);
7648   } else if (Ty->isNullPtrType()) {
7649     HasNullPtrType = true;
7650   } else if (AllowUserConversions && TyRec) {
7651     // No conversion functions in incomplete types.
7652     if (!SemaRef.isCompleteType(Loc, Ty))
7653       return;
7654 
7655     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7656     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7657       if (isa<UsingShadowDecl>(D))
7658         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7659 
7660       // Skip conversion function templates; they don't tell us anything
7661       // about which builtin types we can convert to.
7662       if (isa<FunctionTemplateDecl>(D))
7663         continue;
7664 
7665       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7666       if (AllowExplicitConversions || !Conv->isExplicit()) {
7667         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7668                               VisibleQuals);
7669       }
7670     }
7671   }
7672 }
7673 /// Helper function for adjusting address spaces for the pointer or reference
7674 /// operands of builtin operators depending on the argument.
7675 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7676                                                         Expr *Arg) {
7677   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7678 }
7679 
7680 /// Helper function for AddBuiltinOperatorCandidates() that adds
7681 /// the volatile- and non-volatile-qualified assignment operators for the
7682 /// given type to the candidate set.
7683 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7684                                                    QualType T,
7685                                                    ArrayRef<Expr *> Args,
7686                                     OverloadCandidateSet &CandidateSet) {
7687   QualType ParamTypes[2];
7688 
7689   // T& operator=(T&, T)
7690   ParamTypes[0] = S.Context.getLValueReferenceType(
7691       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7692   ParamTypes[1] = T;
7693   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7694                         /*IsAssignmentOperator=*/true);
7695 
7696   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7697     // volatile T& operator=(volatile T&, T)
7698     ParamTypes[0] = S.Context.getLValueReferenceType(
7699         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7700                                                 Args[0]));
7701     ParamTypes[1] = T;
7702     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7703                           /*IsAssignmentOperator=*/true);
7704   }
7705 }
7706 
7707 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7708 /// if any, found in visible type conversion functions found in ArgExpr's type.
7709 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7710     Qualifiers VRQuals;
7711     const RecordType *TyRec;
7712     if (const MemberPointerType *RHSMPType =
7713         ArgExpr->getType()->getAs<MemberPointerType>())
7714       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7715     else
7716       TyRec = ArgExpr->getType()->getAs<RecordType>();
7717     if (!TyRec) {
7718       // Just to be safe, assume the worst case.
7719       VRQuals.addVolatile();
7720       VRQuals.addRestrict();
7721       return VRQuals;
7722     }
7723 
7724     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7725     if (!ClassDecl->hasDefinition())
7726       return VRQuals;
7727 
7728     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7729       if (isa<UsingShadowDecl>(D))
7730         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7731       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7732         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7733         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7734           CanTy = ResTypeRef->getPointeeType();
7735         // Need to go down the pointer/mempointer chain and add qualifiers
7736         // as see them.
7737         bool done = false;
7738         while (!done) {
7739           if (CanTy.isRestrictQualified())
7740             VRQuals.addRestrict();
7741           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7742             CanTy = ResTypePtr->getPointeeType();
7743           else if (const MemberPointerType *ResTypeMPtr =
7744                 CanTy->getAs<MemberPointerType>())
7745             CanTy = ResTypeMPtr->getPointeeType();
7746           else
7747             done = true;
7748           if (CanTy.isVolatileQualified())
7749             VRQuals.addVolatile();
7750           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7751             return VRQuals;
7752         }
7753       }
7754     }
7755     return VRQuals;
7756 }
7757 
7758 namespace {
7759 
7760 /// Helper class to manage the addition of builtin operator overload
7761 /// candidates. It provides shared state and utility methods used throughout
7762 /// the process, as well as a helper method to add each group of builtin
7763 /// operator overloads from the standard to a candidate set.
7764 class BuiltinOperatorOverloadBuilder {
7765   // Common instance state available to all overload candidate addition methods.
7766   Sema &S;
7767   ArrayRef<Expr *> Args;
7768   Qualifiers VisibleTypeConversionsQuals;
7769   bool HasArithmeticOrEnumeralCandidateType;
7770   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7771   OverloadCandidateSet &CandidateSet;
7772 
7773   static constexpr int ArithmeticTypesCap = 24;
7774   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7775 
7776   // Define some indices used to iterate over the arithmetic types in
7777   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7778   // types are that preserved by promotion (C++ [over.built]p2).
7779   unsigned FirstIntegralType,
7780            LastIntegralType;
7781   unsigned FirstPromotedIntegralType,
7782            LastPromotedIntegralType;
7783   unsigned FirstPromotedArithmeticType,
7784            LastPromotedArithmeticType;
7785   unsigned NumArithmeticTypes;
7786 
7787   void InitArithmeticTypes() {
7788     // Start of promoted types.
7789     FirstPromotedArithmeticType = 0;
7790     ArithmeticTypes.push_back(S.Context.FloatTy);
7791     ArithmeticTypes.push_back(S.Context.DoubleTy);
7792     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7793     if (S.Context.getTargetInfo().hasFloat128Type())
7794       ArithmeticTypes.push_back(S.Context.Float128Ty);
7795 
7796     // Start of integral types.
7797     FirstIntegralType = ArithmeticTypes.size();
7798     FirstPromotedIntegralType = ArithmeticTypes.size();
7799     ArithmeticTypes.push_back(S.Context.IntTy);
7800     ArithmeticTypes.push_back(S.Context.LongTy);
7801     ArithmeticTypes.push_back(S.Context.LongLongTy);
7802     if (S.Context.getTargetInfo().hasInt128Type())
7803       ArithmeticTypes.push_back(S.Context.Int128Ty);
7804     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7805     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7806     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7807     if (S.Context.getTargetInfo().hasInt128Type())
7808       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7809     LastPromotedIntegralType = ArithmeticTypes.size();
7810     LastPromotedArithmeticType = ArithmeticTypes.size();
7811     // End of promoted types.
7812 
7813     ArithmeticTypes.push_back(S.Context.BoolTy);
7814     ArithmeticTypes.push_back(S.Context.CharTy);
7815     ArithmeticTypes.push_back(S.Context.WCharTy);
7816     if (S.Context.getLangOpts().Char8)
7817       ArithmeticTypes.push_back(S.Context.Char8Ty);
7818     ArithmeticTypes.push_back(S.Context.Char16Ty);
7819     ArithmeticTypes.push_back(S.Context.Char32Ty);
7820     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7821     ArithmeticTypes.push_back(S.Context.ShortTy);
7822     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7823     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7824     LastIntegralType = ArithmeticTypes.size();
7825     NumArithmeticTypes = ArithmeticTypes.size();
7826     // End of integral types.
7827     // FIXME: What about complex? What about half?
7828 
7829     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7830            "Enough inline storage for all arithmetic types.");
7831   }
7832 
7833   /// Helper method to factor out the common pattern of adding overloads
7834   /// for '++' and '--' builtin operators.
7835   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7836                                            bool HasVolatile,
7837                                            bool HasRestrict) {
7838     QualType ParamTypes[2] = {
7839       S.Context.getLValueReferenceType(CandidateTy),
7840       S.Context.IntTy
7841     };
7842 
7843     // Non-volatile version.
7844     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7845 
7846     // Use a heuristic to reduce number of builtin candidates in the set:
7847     // add volatile version only if there are conversions to a volatile type.
7848     if (HasVolatile) {
7849       ParamTypes[0] =
7850         S.Context.getLValueReferenceType(
7851           S.Context.getVolatileType(CandidateTy));
7852       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7853     }
7854 
7855     // Add restrict version only if there are conversions to a restrict type
7856     // and our candidate type is a non-restrict-qualified pointer.
7857     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7858         !CandidateTy.isRestrictQualified()) {
7859       ParamTypes[0]
7860         = S.Context.getLValueReferenceType(
7861             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7862       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7863 
7864       if (HasVolatile) {
7865         ParamTypes[0]
7866           = S.Context.getLValueReferenceType(
7867               S.Context.getCVRQualifiedType(CandidateTy,
7868                                             (Qualifiers::Volatile |
7869                                              Qualifiers::Restrict)));
7870         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7871       }
7872     }
7873 
7874   }
7875 
7876 public:
7877   BuiltinOperatorOverloadBuilder(
7878     Sema &S, ArrayRef<Expr *> Args,
7879     Qualifiers VisibleTypeConversionsQuals,
7880     bool HasArithmeticOrEnumeralCandidateType,
7881     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7882     OverloadCandidateSet &CandidateSet)
7883     : S(S), Args(Args),
7884       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7885       HasArithmeticOrEnumeralCandidateType(
7886         HasArithmeticOrEnumeralCandidateType),
7887       CandidateTypes(CandidateTypes),
7888       CandidateSet(CandidateSet) {
7889 
7890     InitArithmeticTypes();
7891   }
7892 
7893   // Increment is deprecated for bool since C++17.
7894   //
7895   // C++ [over.built]p3:
7896   //
7897   //   For every pair (T, VQ), where T is an arithmetic type other
7898   //   than bool, and VQ is either volatile or empty, there exist
7899   //   candidate operator functions of the form
7900   //
7901   //       VQ T&      operator++(VQ T&);
7902   //       T          operator++(VQ T&, int);
7903   //
7904   // C++ [over.built]p4:
7905   //
7906   //   For every pair (T, VQ), where T is an arithmetic type other
7907   //   than bool, and VQ is either volatile or empty, there exist
7908   //   candidate operator functions of the form
7909   //
7910   //       VQ T&      operator--(VQ T&);
7911   //       T          operator--(VQ T&, int);
7912   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7913     if (!HasArithmeticOrEnumeralCandidateType)
7914       return;
7915 
7916     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7917       const auto TypeOfT = ArithmeticTypes[Arith];
7918       if (TypeOfT == S.Context.BoolTy) {
7919         if (Op == OO_MinusMinus)
7920           continue;
7921         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7922           continue;
7923       }
7924       addPlusPlusMinusMinusStyleOverloads(
7925         TypeOfT,
7926         VisibleTypeConversionsQuals.hasVolatile(),
7927         VisibleTypeConversionsQuals.hasRestrict());
7928     }
7929   }
7930 
7931   // C++ [over.built]p5:
7932   //
7933   //   For every pair (T, VQ), where T is a cv-qualified or
7934   //   cv-unqualified object type, and VQ is either volatile or
7935   //   empty, there exist candidate operator functions of the form
7936   //
7937   //       T*VQ&      operator++(T*VQ&);
7938   //       T*VQ&      operator--(T*VQ&);
7939   //       T*         operator++(T*VQ&, int);
7940   //       T*         operator--(T*VQ&, int);
7941   void addPlusPlusMinusMinusPointerOverloads() {
7942     for (BuiltinCandidateTypeSet::iterator
7943               Ptr = CandidateTypes[0].pointer_begin(),
7944            PtrEnd = CandidateTypes[0].pointer_end();
7945          Ptr != PtrEnd; ++Ptr) {
7946       // Skip pointer types that aren't pointers to object types.
7947       if (!(*Ptr)->getPointeeType()->isObjectType())
7948         continue;
7949 
7950       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7951         (!(*Ptr).isVolatileQualified() &&
7952          VisibleTypeConversionsQuals.hasVolatile()),
7953         (!(*Ptr).isRestrictQualified() &&
7954          VisibleTypeConversionsQuals.hasRestrict()));
7955     }
7956   }
7957 
7958   // C++ [over.built]p6:
7959   //   For every cv-qualified or cv-unqualified object type T, there
7960   //   exist candidate operator functions of the form
7961   //
7962   //       T&         operator*(T*);
7963   //
7964   // C++ [over.built]p7:
7965   //   For every function type T that does not have cv-qualifiers or a
7966   //   ref-qualifier, there exist candidate operator functions of the form
7967   //       T&         operator*(T*);
7968   void addUnaryStarPointerOverloads() {
7969     for (BuiltinCandidateTypeSet::iterator
7970               Ptr = CandidateTypes[0].pointer_begin(),
7971            PtrEnd = CandidateTypes[0].pointer_end();
7972          Ptr != PtrEnd; ++Ptr) {
7973       QualType ParamTy = *Ptr;
7974       QualType PointeeTy = ParamTy->getPointeeType();
7975       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7976         continue;
7977 
7978       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7979         if (Proto->getMethodQuals() || Proto->getRefQualifier())
7980           continue;
7981 
7982       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7983     }
7984   }
7985 
7986   // C++ [over.built]p9:
7987   //  For every promoted arithmetic type T, there exist candidate
7988   //  operator functions of the form
7989   //
7990   //       T         operator+(T);
7991   //       T         operator-(T);
7992   void addUnaryPlusOrMinusArithmeticOverloads() {
7993     if (!HasArithmeticOrEnumeralCandidateType)
7994       return;
7995 
7996     for (unsigned Arith = FirstPromotedArithmeticType;
7997          Arith < LastPromotedArithmeticType; ++Arith) {
7998       QualType ArithTy = ArithmeticTypes[Arith];
7999       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8000     }
8001 
8002     // Extension: We also add these operators for vector types.
8003     for (BuiltinCandidateTypeSet::iterator
8004               Vec = CandidateTypes[0].vector_begin(),
8005            VecEnd = CandidateTypes[0].vector_end();
8006          Vec != VecEnd; ++Vec) {
8007       QualType VecTy = *Vec;
8008       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8009     }
8010   }
8011 
8012   // C++ [over.built]p8:
8013   //   For every type T, there exist candidate operator functions of
8014   //   the form
8015   //
8016   //       T*         operator+(T*);
8017   void addUnaryPlusPointerOverloads() {
8018     for (BuiltinCandidateTypeSet::iterator
8019               Ptr = CandidateTypes[0].pointer_begin(),
8020            PtrEnd = CandidateTypes[0].pointer_end();
8021          Ptr != PtrEnd; ++Ptr) {
8022       QualType ParamTy = *Ptr;
8023       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8024     }
8025   }
8026 
8027   // C++ [over.built]p10:
8028   //   For every promoted integral type T, there exist candidate
8029   //   operator functions of the form
8030   //
8031   //        T         operator~(T);
8032   void addUnaryTildePromotedIntegralOverloads() {
8033     if (!HasArithmeticOrEnumeralCandidateType)
8034       return;
8035 
8036     for (unsigned Int = FirstPromotedIntegralType;
8037          Int < LastPromotedIntegralType; ++Int) {
8038       QualType IntTy = ArithmeticTypes[Int];
8039       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8040     }
8041 
8042     // Extension: We also add this operator for vector types.
8043     for (BuiltinCandidateTypeSet::iterator
8044               Vec = CandidateTypes[0].vector_begin(),
8045            VecEnd = CandidateTypes[0].vector_end();
8046          Vec != VecEnd; ++Vec) {
8047       QualType VecTy = *Vec;
8048       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8049     }
8050   }
8051 
8052   // C++ [over.match.oper]p16:
8053   //   For every pointer to member type T or type std::nullptr_t, there
8054   //   exist candidate operator functions of the form
8055   //
8056   //        bool operator==(T,T);
8057   //        bool operator!=(T,T);
8058   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8059     /// Set of (canonical) types that we've already handled.
8060     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8061 
8062     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8063       for (BuiltinCandidateTypeSet::iterator
8064                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8065              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8066            MemPtr != MemPtrEnd;
8067            ++MemPtr) {
8068         // Don't add the same builtin candidate twice.
8069         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8070           continue;
8071 
8072         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8073         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8074       }
8075 
8076       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8077         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8078         if (AddedTypes.insert(NullPtrTy).second) {
8079           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8080           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8081         }
8082       }
8083     }
8084   }
8085 
8086   // C++ [over.built]p15:
8087   //
8088   //   For every T, where T is an enumeration type or a pointer type,
8089   //   there exist candidate operator functions of the form
8090   //
8091   //        bool       operator<(T, T);
8092   //        bool       operator>(T, T);
8093   //        bool       operator<=(T, T);
8094   //        bool       operator>=(T, T);
8095   //        bool       operator==(T, T);
8096   //        bool       operator!=(T, T);
8097   //           R       operator<=>(T, T)
8098   void addGenericBinaryPointerOrEnumeralOverloads() {
8099     // C++ [over.match.oper]p3:
8100     //   [...]the built-in candidates include all of the candidate operator
8101     //   functions defined in 13.6 that, compared to the given operator, [...]
8102     //   do not have the same parameter-type-list as any non-template non-member
8103     //   candidate.
8104     //
8105     // Note that in practice, this only affects enumeration types because there
8106     // aren't any built-in candidates of record type, and a user-defined operator
8107     // must have an operand of record or enumeration type. Also, the only other
8108     // overloaded operator with enumeration arguments, operator=,
8109     // cannot be overloaded for enumeration types, so this is the only place
8110     // where we must suppress candidates like this.
8111     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8112       UserDefinedBinaryOperators;
8113 
8114     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8115       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8116           CandidateTypes[ArgIdx].enumeration_end()) {
8117         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8118                                          CEnd = CandidateSet.end();
8119              C != CEnd; ++C) {
8120           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8121             continue;
8122 
8123           if (C->Function->isFunctionTemplateSpecialization())
8124             continue;
8125 
8126           QualType FirstParamType =
8127             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8128           QualType SecondParamType =
8129             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8130 
8131           // Skip if either parameter isn't of enumeral type.
8132           if (!FirstParamType->isEnumeralType() ||
8133               !SecondParamType->isEnumeralType())
8134             continue;
8135 
8136           // Add this operator to the set of known user-defined operators.
8137           UserDefinedBinaryOperators.insert(
8138             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8139                            S.Context.getCanonicalType(SecondParamType)));
8140         }
8141       }
8142     }
8143 
8144     /// Set of (canonical) types that we've already handled.
8145     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8146 
8147     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8148       for (BuiltinCandidateTypeSet::iterator
8149                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8150              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8151            Ptr != PtrEnd; ++Ptr) {
8152         // Don't add the same builtin candidate twice.
8153         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8154           continue;
8155 
8156         QualType ParamTypes[2] = { *Ptr, *Ptr };
8157         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8158       }
8159       for (BuiltinCandidateTypeSet::iterator
8160                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8161              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8162            Enum != EnumEnd; ++Enum) {
8163         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8164 
8165         // Don't add the same builtin candidate twice, or if a user defined
8166         // candidate exists.
8167         if (!AddedTypes.insert(CanonType).second ||
8168             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8169                                                             CanonType)))
8170           continue;
8171         QualType ParamTypes[2] = { *Enum, *Enum };
8172         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8173       }
8174     }
8175   }
8176 
8177   // C++ [over.built]p13:
8178   //
8179   //   For every cv-qualified or cv-unqualified object type T
8180   //   there exist candidate operator functions of the form
8181   //
8182   //      T*         operator+(T*, ptrdiff_t);
8183   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8184   //      T*         operator-(T*, ptrdiff_t);
8185   //      T*         operator+(ptrdiff_t, T*);
8186   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8187   //
8188   // C++ [over.built]p14:
8189   //
8190   //   For every T, where T is a pointer to object type, there
8191   //   exist candidate operator functions of the form
8192   //
8193   //      ptrdiff_t  operator-(T, T);
8194   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8195     /// Set of (canonical) types that we've already handled.
8196     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8197 
8198     for (int Arg = 0; Arg < 2; ++Arg) {
8199       QualType AsymmetricParamTypes[2] = {
8200         S.Context.getPointerDiffType(),
8201         S.Context.getPointerDiffType(),
8202       };
8203       for (BuiltinCandidateTypeSet::iterator
8204                 Ptr = CandidateTypes[Arg].pointer_begin(),
8205              PtrEnd = CandidateTypes[Arg].pointer_end();
8206            Ptr != PtrEnd; ++Ptr) {
8207         QualType PointeeTy = (*Ptr)->getPointeeType();
8208         if (!PointeeTy->isObjectType())
8209           continue;
8210 
8211         AsymmetricParamTypes[Arg] = *Ptr;
8212         if (Arg == 0 || Op == OO_Plus) {
8213           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8214           // T* operator+(ptrdiff_t, T*);
8215           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8216         }
8217         if (Op == OO_Minus) {
8218           // ptrdiff_t operator-(T, T);
8219           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8220             continue;
8221 
8222           QualType ParamTypes[2] = { *Ptr, *Ptr };
8223           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8224         }
8225       }
8226     }
8227   }
8228 
8229   // C++ [over.built]p12:
8230   //
8231   //   For every pair of promoted arithmetic types L and R, there
8232   //   exist candidate operator functions of the form
8233   //
8234   //        LR         operator*(L, R);
8235   //        LR         operator/(L, R);
8236   //        LR         operator+(L, R);
8237   //        LR         operator-(L, R);
8238   //        bool       operator<(L, R);
8239   //        bool       operator>(L, R);
8240   //        bool       operator<=(L, R);
8241   //        bool       operator>=(L, R);
8242   //        bool       operator==(L, R);
8243   //        bool       operator!=(L, R);
8244   //
8245   //   where LR is the result of the usual arithmetic conversions
8246   //   between types L and R.
8247   //
8248   // C++ [over.built]p24:
8249   //
8250   //   For every pair of promoted arithmetic types L and R, there exist
8251   //   candidate operator functions of the form
8252   //
8253   //        LR       operator?(bool, L, R);
8254   //
8255   //   where LR is the result of the usual arithmetic conversions
8256   //   between types L and R.
8257   // Our candidates ignore the first parameter.
8258   void addGenericBinaryArithmeticOverloads() {
8259     if (!HasArithmeticOrEnumeralCandidateType)
8260       return;
8261 
8262     for (unsigned Left = FirstPromotedArithmeticType;
8263          Left < LastPromotedArithmeticType; ++Left) {
8264       for (unsigned Right = FirstPromotedArithmeticType;
8265            Right < LastPromotedArithmeticType; ++Right) {
8266         QualType LandR[2] = { ArithmeticTypes[Left],
8267                               ArithmeticTypes[Right] };
8268         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8269       }
8270     }
8271 
8272     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8273     // conditional operator for vector types.
8274     for (BuiltinCandidateTypeSet::iterator
8275               Vec1 = CandidateTypes[0].vector_begin(),
8276            Vec1End = CandidateTypes[0].vector_end();
8277          Vec1 != Vec1End; ++Vec1) {
8278       for (BuiltinCandidateTypeSet::iterator
8279                 Vec2 = CandidateTypes[1].vector_begin(),
8280              Vec2End = CandidateTypes[1].vector_end();
8281            Vec2 != Vec2End; ++Vec2) {
8282         QualType LandR[2] = { *Vec1, *Vec2 };
8283         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8284       }
8285     }
8286   }
8287 
8288   // C++2a [over.built]p14:
8289   //
8290   //   For every integral type T there exists a candidate operator function
8291   //   of the form
8292   //
8293   //        std::strong_ordering operator<=>(T, T)
8294   //
8295   // C++2a [over.built]p15:
8296   //
8297   //   For every pair of floating-point types L and R, there exists a candidate
8298   //   operator function of the form
8299   //
8300   //       std::partial_ordering operator<=>(L, R);
8301   //
8302   // FIXME: The current specification for integral types doesn't play nice with
8303   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8304   // comparisons. Under the current spec this can lead to ambiguity during
8305   // overload resolution. For example:
8306   //
8307   //   enum A : int {a};
8308   //   auto x = (a <=> (long)42);
8309   //
8310   //   error: call is ambiguous for arguments 'A' and 'long'.
8311   //   note: candidate operator<=>(int, int)
8312   //   note: candidate operator<=>(long, long)
8313   //
8314   // To avoid this error, this function deviates from the specification and adds
8315   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8316   // arithmetic types (the same as the generic relational overloads).
8317   //
8318   // For now this function acts as a placeholder.
8319   void addThreeWayArithmeticOverloads() {
8320     addGenericBinaryArithmeticOverloads();
8321   }
8322 
8323   // C++ [over.built]p17:
8324   //
8325   //   For every pair of promoted integral types L and R, there
8326   //   exist candidate operator functions of the form
8327   //
8328   //      LR         operator%(L, R);
8329   //      LR         operator&(L, R);
8330   //      LR         operator^(L, R);
8331   //      LR         operator|(L, R);
8332   //      L          operator<<(L, R);
8333   //      L          operator>>(L, R);
8334   //
8335   //   where LR is the result of the usual arithmetic conversions
8336   //   between types L and R.
8337   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8338     if (!HasArithmeticOrEnumeralCandidateType)
8339       return;
8340 
8341     for (unsigned Left = FirstPromotedIntegralType;
8342          Left < LastPromotedIntegralType; ++Left) {
8343       for (unsigned Right = FirstPromotedIntegralType;
8344            Right < LastPromotedIntegralType; ++Right) {
8345         QualType LandR[2] = { ArithmeticTypes[Left],
8346                               ArithmeticTypes[Right] };
8347         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8348       }
8349     }
8350   }
8351 
8352   // C++ [over.built]p20:
8353   //
8354   //   For every pair (T, VQ), where T is an enumeration or
8355   //   pointer to member type and VQ is either volatile or
8356   //   empty, there exist candidate operator functions of the form
8357   //
8358   //        VQ T&      operator=(VQ T&, T);
8359   void addAssignmentMemberPointerOrEnumeralOverloads() {
8360     /// Set of (canonical) types that we've already handled.
8361     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8362 
8363     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8364       for (BuiltinCandidateTypeSet::iterator
8365                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8366              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8367            Enum != EnumEnd; ++Enum) {
8368         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8369           continue;
8370 
8371         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8372       }
8373 
8374       for (BuiltinCandidateTypeSet::iterator
8375                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8376              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8377            MemPtr != MemPtrEnd; ++MemPtr) {
8378         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8379           continue;
8380 
8381         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8382       }
8383     }
8384   }
8385 
8386   // C++ [over.built]p19:
8387   //
8388   //   For every pair (T, VQ), where T is any type and VQ is either
8389   //   volatile or empty, there exist candidate operator functions
8390   //   of the form
8391   //
8392   //        T*VQ&      operator=(T*VQ&, T*);
8393   //
8394   // C++ [over.built]p21:
8395   //
8396   //   For every pair (T, VQ), where T is a cv-qualified or
8397   //   cv-unqualified object type and VQ is either volatile or
8398   //   empty, there exist candidate operator functions of the form
8399   //
8400   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8401   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8402   void addAssignmentPointerOverloads(bool isEqualOp) {
8403     /// Set of (canonical) types that we've already handled.
8404     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8405 
8406     for (BuiltinCandidateTypeSet::iterator
8407               Ptr = CandidateTypes[0].pointer_begin(),
8408            PtrEnd = CandidateTypes[0].pointer_end();
8409          Ptr != PtrEnd; ++Ptr) {
8410       // If this is operator=, keep track of the builtin candidates we added.
8411       if (isEqualOp)
8412         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8413       else if (!(*Ptr)->getPointeeType()->isObjectType())
8414         continue;
8415 
8416       // non-volatile version
8417       QualType ParamTypes[2] = {
8418         S.Context.getLValueReferenceType(*Ptr),
8419         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8420       };
8421       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8422                             /*IsAssignmentOperator=*/ isEqualOp);
8423 
8424       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8425                           VisibleTypeConversionsQuals.hasVolatile();
8426       if (NeedVolatile) {
8427         // volatile version
8428         ParamTypes[0] =
8429           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8430         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8431                               /*IsAssignmentOperator=*/isEqualOp);
8432       }
8433 
8434       if (!(*Ptr).isRestrictQualified() &&
8435           VisibleTypeConversionsQuals.hasRestrict()) {
8436         // restrict version
8437         ParamTypes[0]
8438           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8439         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8440                               /*IsAssignmentOperator=*/isEqualOp);
8441 
8442         if (NeedVolatile) {
8443           // volatile restrict version
8444           ParamTypes[0]
8445             = S.Context.getLValueReferenceType(
8446                 S.Context.getCVRQualifiedType(*Ptr,
8447                                               (Qualifiers::Volatile |
8448                                                Qualifiers::Restrict)));
8449           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8450                                 /*IsAssignmentOperator=*/isEqualOp);
8451         }
8452       }
8453     }
8454 
8455     if (isEqualOp) {
8456       for (BuiltinCandidateTypeSet::iterator
8457                 Ptr = CandidateTypes[1].pointer_begin(),
8458              PtrEnd = CandidateTypes[1].pointer_end();
8459            Ptr != PtrEnd; ++Ptr) {
8460         // Make sure we don't add the same candidate twice.
8461         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8462           continue;
8463 
8464         QualType ParamTypes[2] = {
8465           S.Context.getLValueReferenceType(*Ptr),
8466           *Ptr,
8467         };
8468 
8469         // non-volatile version
8470         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8471                               /*IsAssignmentOperator=*/true);
8472 
8473         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8474                            VisibleTypeConversionsQuals.hasVolatile();
8475         if (NeedVolatile) {
8476           // volatile version
8477           ParamTypes[0] =
8478             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8479           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8480                                 /*IsAssignmentOperator=*/true);
8481         }
8482 
8483         if (!(*Ptr).isRestrictQualified() &&
8484             VisibleTypeConversionsQuals.hasRestrict()) {
8485           // restrict version
8486           ParamTypes[0]
8487             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8488           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8489                                 /*IsAssignmentOperator=*/true);
8490 
8491           if (NeedVolatile) {
8492             // volatile restrict version
8493             ParamTypes[0]
8494               = S.Context.getLValueReferenceType(
8495                   S.Context.getCVRQualifiedType(*Ptr,
8496                                                 (Qualifiers::Volatile |
8497                                                  Qualifiers::Restrict)));
8498             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8499                                   /*IsAssignmentOperator=*/true);
8500           }
8501         }
8502       }
8503     }
8504   }
8505 
8506   // C++ [over.built]p18:
8507   //
8508   //   For every triple (L, VQ, R), where L is an arithmetic type,
8509   //   VQ is either volatile or empty, and R is a promoted
8510   //   arithmetic type, there exist candidate operator functions of
8511   //   the form
8512   //
8513   //        VQ L&      operator=(VQ L&, R);
8514   //        VQ L&      operator*=(VQ L&, R);
8515   //        VQ L&      operator/=(VQ L&, R);
8516   //        VQ L&      operator+=(VQ L&, R);
8517   //        VQ L&      operator-=(VQ L&, R);
8518   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8519     if (!HasArithmeticOrEnumeralCandidateType)
8520       return;
8521 
8522     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8523       for (unsigned Right = FirstPromotedArithmeticType;
8524            Right < LastPromotedArithmeticType; ++Right) {
8525         QualType ParamTypes[2];
8526         ParamTypes[1] = ArithmeticTypes[Right];
8527         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8528             S, ArithmeticTypes[Left], Args[0]);
8529         // Add this built-in operator as a candidate (VQ is empty).
8530         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8531         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8532                               /*IsAssignmentOperator=*/isEqualOp);
8533 
8534         // Add this built-in operator as a candidate (VQ is 'volatile').
8535         if (VisibleTypeConversionsQuals.hasVolatile()) {
8536           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8537           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8538           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8539                                 /*IsAssignmentOperator=*/isEqualOp);
8540         }
8541       }
8542     }
8543 
8544     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8545     for (BuiltinCandidateTypeSet::iterator
8546               Vec1 = CandidateTypes[0].vector_begin(),
8547            Vec1End = CandidateTypes[0].vector_end();
8548          Vec1 != Vec1End; ++Vec1) {
8549       for (BuiltinCandidateTypeSet::iterator
8550                 Vec2 = CandidateTypes[1].vector_begin(),
8551              Vec2End = CandidateTypes[1].vector_end();
8552            Vec2 != Vec2End; ++Vec2) {
8553         QualType ParamTypes[2];
8554         ParamTypes[1] = *Vec2;
8555         // Add this built-in operator as a candidate (VQ is empty).
8556         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8557         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8558                               /*IsAssignmentOperator=*/isEqualOp);
8559 
8560         // Add this built-in operator as a candidate (VQ is 'volatile').
8561         if (VisibleTypeConversionsQuals.hasVolatile()) {
8562           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8563           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8564           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8565                                 /*IsAssignmentOperator=*/isEqualOp);
8566         }
8567       }
8568     }
8569   }
8570 
8571   // C++ [over.built]p22:
8572   //
8573   //   For every triple (L, VQ, R), where L is an integral type, VQ
8574   //   is either volatile or empty, and R is a promoted integral
8575   //   type, there exist candidate operator functions of the form
8576   //
8577   //        VQ L&       operator%=(VQ L&, R);
8578   //        VQ L&       operator<<=(VQ L&, R);
8579   //        VQ L&       operator>>=(VQ L&, R);
8580   //        VQ L&       operator&=(VQ L&, R);
8581   //        VQ L&       operator^=(VQ L&, R);
8582   //        VQ L&       operator|=(VQ L&, R);
8583   void addAssignmentIntegralOverloads() {
8584     if (!HasArithmeticOrEnumeralCandidateType)
8585       return;
8586 
8587     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8588       for (unsigned Right = FirstPromotedIntegralType;
8589            Right < LastPromotedIntegralType; ++Right) {
8590         QualType ParamTypes[2];
8591         ParamTypes[1] = ArithmeticTypes[Right];
8592         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8593             S, ArithmeticTypes[Left], Args[0]);
8594         // Add this built-in operator as a candidate (VQ is empty).
8595         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8596         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8597         if (VisibleTypeConversionsQuals.hasVolatile()) {
8598           // Add this built-in operator as a candidate (VQ is 'volatile').
8599           ParamTypes[0] = LeftBaseTy;
8600           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8601           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8602           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8603         }
8604       }
8605     }
8606   }
8607 
8608   // C++ [over.operator]p23:
8609   //
8610   //   There also exist candidate operator functions of the form
8611   //
8612   //        bool        operator!(bool);
8613   //        bool        operator&&(bool, bool);
8614   //        bool        operator||(bool, bool);
8615   void addExclaimOverload() {
8616     QualType ParamTy = S.Context.BoolTy;
8617     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8618                           /*IsAssignmentOperator=*/false,
8619                           /*NumContextualBoolArguments=*/1);
8620   }
8621   void addAmpAmpOrPipePipeOverload() {
8622     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8623     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8624                           /*IsAssignmentOperator=*/false,
8625                           /*NumContextualBoolArguments=*/2);
8626   }
8627 
8628   // C++ [over.built]p13:
8629   //
8630   //   For every cv-qualified or cv-unqualified object type T there
8631   //   exist candidate operator functions of the form
8632   //
8633   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8634   //        T&         operator[](T*, ptrdiff_t);
8635   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8636   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8637   //        T&         operator[](ptrdiff_t, T*);
8638   void addSubscriptOverloads() {
8639     for (BuiltinCandidateTypeSet::iterator
8640               Ptr = CandidateTypes[0].pointer_begin(),
8641            PtrEnd = CandidateTypes[0].pointer_end();
8642          Ptr != PtrEnd; ++Ptr) {
8643       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8644       QualType PointeeType = (*Ptr)->getPointeeType();
8645       if (!PointeeType->isObjectType())
8646         continue;
8647 
8648       // T& operator[](T*, ptrdiff_t)
8649       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8650     }
8651 
8652     for (BuiltinCandidateTypeSet::iterator
8653               Ptr = CandidateTypes[1].pointer_begin(),
8654            PtrEnd = CandidateTypes[1].pointer_end();
8655          Ptr != PtrEnd; ++Ptr) {
8656       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8657       QualType PointeeType = (*Ptr)->getPointeeType();
8658       if (!PointeeType->isObjectType())
8659         continue;
8660 
8661       // T& operator[](ptrdiff_t, T*)
8662       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8663     }
8664   }
8665 
8666   // C++ [over.built]p11:
8667   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8668   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8669   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8670   //    there exist candidate operator functions of the form
8671   //
8672   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8673   //
8674   //    where CV12 is the union of CV1 and CV2.
8675   void addArrowStarOverloads() {
8676     for (BuiltinCandidateTypeSet::iterator
8677              Ptr = CandidateTypes[0].pointer_begin(),
8678            PtrEnd = CandidateTypes[0].pointer_end();
8679          Ptr != PtrEnd; ++Ptr) {
8680       QualType C1Ty = (*Ptr);
8681       QualType C1;
8682       QualifierCollector Q1;
8683       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8684       if (!isa<RecordType>(C1))
8685         continue;
8686       // heuristic to reduce number of builtin candidates in the set.
8687       // Add volatile/restrict version only if there are conversions to a
8688       // volatile/restrict type.
8689       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8690         continue;
8691       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8692         continue;
8693       for (BuiltinCandidateTypeSet::iterator
8694                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8695              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8696            MemPtr != MemPtrEnd; ++MemPtr) {
8697         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8698         QualType C2 = QualType(mptr->getClass(), 0);
8699         C2 = C2.getUnqualifiedType();
8700         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8701           break;
8702         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8703         // build CV12 T&
8704         QualType T = mptr->getPointeeType();
8705         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8706             T.isVolatileQualified())
8707           continue;
8708         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8709             T.isRestrictQualified())
8710           continue;
8711         T = Q1.apply(S.Context, T);
8712         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8713       }
8714     }
8715   }
8716 
8717   // Note that we don't consider the first argument, since it has been
8718   // contextually converted to bool long ago. The candidates below are
8719   // therefore added as binary.
8720   //
8721   // C++ [over.built]p25:
8722   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8723   //   enumeration type, there exist candidate operator functions of the form
8724   //
8725   //        T        operator?(bool, T, T);
8726   //
8727   void addConditionalOperatorOverloads() {
8728     /// Set of (canonical) types that we've already handled.
8729     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8730 
8731     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8732       for (BuiltinCandidateTypeSet::iterator
8733                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8734              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8735            Ptr != PtrEnd; ++Ptr) {
8736         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8737           continue;
8738 
8739         QualType ParamTypes[2] = { *Ptr, *Ptr };
8740         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8741       }
8742 
8743       for (BuiltinCandidateTypeSet::iterator
8744                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8745              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8746            MemPtr != MemPtrEnd; ++MemPtr) {
8747         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8748           continue;
8749 
8750         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8751         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8752       }
8753 
8754       if (S.getLangOpts().CPlusPlus11) {
8755         for (BuiltinCandidateTypeSet::iterator
8756                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8757                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8758              Enum != EnumEnd; ++Enum) {
8759           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8760             continue;
8761 
8762           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8763             continue;
8764 
8765           QualType ParamTypes[2] = { *Enum, *Enum };
8766           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8767         }
8768       }
8769     }
8770   }
8771 };
8772 
8773 } // end anonymous namespace
8774 
8775 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8776 /// operator overloads to the candidate set (C++ [over.built]), based
8777 /// on the operator @p Op and the arguments given. For example, if the
8778 /// operator is a binary '+', this routine might add "int
8779 /// operator+(int, int)" to cover integer addition.
8780 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8781                                         SourceLocation OpLoc,
8782                                         ArrayRef<Expr *> Args,
8783                                         OverloadCandidateSet &CandidateSet) {
8784   // Find all of the types that the arguments can convert to, but only
8785   // if the operator we're looking at has built-in operator candidates
8786   // that make use of these types. Also record whether we encounter non-record
8787   // candidate types or either arithmetic or enumeral candidate types.
8788   Qualifiers VisibleTypeConversionsQuals;
8789   VisibleTypeConversionsQuals.addConst();
8790   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8791     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8792 
8793   bool HasNonRecordCandidateType = false;
8794   bool HasArithmeticOrEnumeralCandidateType = false;
8795   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8796   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8797     CandidateTypes.emplace_back(*this);
8798     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8799                                                  OpLoc,
8800                                                  true,
8801                                                  (Op == OO_Exclaim ||
8802                                                   Op == OO_AmpAmp ||
8803                                                   Op == OO_PipePipe),
8804                                                  VisibleTypeConversionsQuals);
8805     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8806         CandidateTypes[ArgIdx].hasNonRecordTypes();
8807     HasArithmeticOrEnumeralCandidateType =
8808         HasArithmeticOrEnumeralCandidateType ||
8809         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8810   }
8811 
8812   // Exit early when no non-record types have been added to the candidate set
8813   // for any of the arguments to the operator.
8814   //
8815   // We can't exit early for !, ||, or &&, since there we have always have
8816   // 'bool' overloads.
8817   if (!HasNonRecordCandidateType &&
8818       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8819     return;
8820 
8821   // Setup an object to manage the common state for building overloads.
8822   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8823                                            VisibleTypeConversionsQuals,
8824                                            HasArithmeticOrEnumeralCandidateType,
8825                                            CandidateTypes, CandidateSet);
8826 
8827   // Dispatch over the operation to add in only those overloads which apply.
8828   switch (Op) {
8829   case OO_None:
8830   case NUM_OVERLOADED_OPERATORS:
8831     llvm_unreachable("Expected an overloaded operator");
8832 
8833   case OO_New:
8834   case OO_Delete:
8835   case OO_Array_New:
8836   case OO_Array_Delete:
8837   case OO_Call:
8838     llvm_unreachable(
8839                     "Special operators don't use AddBuiltinOperatorCandidates");
8840 
8841   case OO_Comma:
8842   case OO_Arrow:
8843   case OO_Coawait:
8844     // C++ [over.match.oper]p3:
8845     //   -- For the operator ',', the unary operator '&', the
8846     //      operator '->', or the operator 'co_await', the
8847     //      built-in candidates set is empty.
8848     break;
8849 
8850   case OO_Plus: // '+' is either unary or binary
8851     if (Args.size() == 1)
8852       OpBuilder.addUnaryPlusPointerOverloads();
8853     LLVM_FALLTHROUGH;
8854 
8855   case OO_Minus: // '-' is either unary or binary
8856     if (Args.size() == 1) {
8857       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8858     } else {
8859       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8860       OpBuilder.addGenericBinaryArithmeticOverloads();
8861     }
8862     break;
8863 
8864   case OO_Star: // '*' is either unary or binary
8865     if (Args.size() == 1)
8866       OpBuilder.addUnaryStarPointerOverloads();
8867     else
8868       OpBuilder.addGenericBinaryArithmeticOverloads();
8869     break;
8870 
8871   case OO_Slash:
8872     OpBuilder.addGenericBinaryArithmeticOverloads();
8873     break;
8874 
8875   case OO_PlusPlus:
8876   case OO_MinusMinus:
8877     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8878     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8879     break;
8880 
8881   case OO_EqualEqual:
8882   case OO_ExclaimEqual:
8883     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8884     LLVM_FALLTHROUGH;
8885 
8886   case OO_Less:
8887   case OO_Greater:
8888   case OO_LessEqual:
8889   case OO_GreaterEqual:
8890     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8891     OpBuilder.addGenericBinaryArithmeticOverloads();
8892     break;
8893 
8894   case OO_Spaceship:
8895     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8896     OpBuilder.addThreeWayArithmeticOverloads();
8897     break;
8898 
8899   case OO_Percent:
8900   case OO_Caret:
8901   case OO_Pipe:
8902   case OO_LessLess:
8903   case OO_GreaterGreater:
8904     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8905     break;
8906 
8907   case OO_Amp: // '&' is either unary or binary
8908     if (Args.size() == 1)
8909       // C++ [over.match.oper]p3:
8910       //   -- For the operator ',', the unary operator '&', or the
8911       //      operator '->', the built-in candidates set is empty.
8912       break;
8913 
8914     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8915     break;
8916 
8917   case OO_Tilde:
8918     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8919     break;
8920 
8921   case OO_Equal:
8922     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8923     LLVM_FALLTHROUGH;
8924 
8925   case OO_PlusEqual:
8926   case OO_MinusEqual:
8927     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8928     LLVM_FALLTHROUGH;
8929 
8930   case OO_StarEqual:
8931   case OO_SlashEqual:
8932     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8933     break;
8934 
8935   case OO_PercentEqual:
8936   case OO_LessLessEqual:
8937   case OO_GreaterGreaterEqual:
8938   case OO_AmpEqual:
8939   case OO_CaretEqual:
8940   case OO_PipeEqual:
8941     OpBuilder.addAssignmentIntegralOverloads();
8942     break;
8943 
8944   case OO_Exclaim:
8945     OpBuilder.addExclaimOverload();
8946     break;
8947 
8948   case OO_AmpAmp:
8949   case OO_PipePipe:
8950     OpBuilder.addAmpAmpOrPipePipeOverload();
8951     break;
8952 
8953   case OO_Subscript:
8954     OpBuilder.addSubscriptOverloads();
8955     break;
8956 
8957   case OO_ArrowStar:
8958     OpBuilder.addArrowStarOverloads();
8959     break;
8960 
8961   case OO_Conditional:
8962     OpBuilder.addConditionalOperatorOverloads();
8963     OpBuilder.addGenericBinaryArithmeticOverloads();
8964     break;
8965   }
8966 }
8967 
8968 /// Add function candidates found via argument-dependent lookup
8969 /// to the set of overloading candidates.
8970 ///
8971 /// This routine performs argument-dependent name lookup based on the
8972 /// given function name (which may also be an operator name) and adds
8973 /// all of the overload candidates found by ADL to the overload
8974 /// candidate set (C++ [basic.lookup.argdep]).
8975 void
8976 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8977                                            SourceLocation Loc,
8978                                            ArrayRef<Expr *> Args,
8979                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8980                                            OverloadCandidateSet& CandidateSet,
8981                                            bool PartialOverloading) {
8982   ADLResult Fns;
8983 
8984   // FIXME: This approach for uniquing ADL results (and removing
8985   // redundant candidates from the set) relies on pointer-equality,
8986   // which means we need to key off the canonical decl.  However,
8987   // always going back to the canonical decl might not get us the
8988   // right set of default arguments.  What default arguments are
8989   // we supposed to consider on ADL candidates, anyway?
8990 
8991   // FIXME: Pass in the explicit template arguments?
8992   ArgumentDependentLookup(Name, Loc, Args, Fns);
8993 
8994   // Erase all of the candidates we already knew about.
8995   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8996                                    CandEnd = CandidateSet.end();
8997        Cand != CandEnd; ++Cand)
8998     if (Cand->Function) {
8999       Fns.erase(Cand->Function);
9000       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9001         Fns.erase(FunTmpl);
9002     }
9003 
9004   // For each of the ADL candidates we found, add it to the overload
9005   // set.
9006   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9007     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9008 
9009     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9010       if (ExplicitTemplateArgs)
9011         continue;
9012 
9013       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
9014                            /*SuppressUserConversions=*/false, PartialOverloading,
9015                            /*AllowExplicit*/ true,
9016                            /*AllowExplicitConversions*/ false,
9017                            ADLCallKind::UsesADL);
9018     } else {
9019       AddTemplateOverloadCandidate(
9020           cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
9021           CandidateSet,
9022           /*SuppressUserConversions=*/false, PartialOverloading,
9023           /*AllowExplicit*/true, ADLCallKind::UsesADL);
9024     }
9025   }
9026 }
9027 
9028 namespace {
9029 enum class Comparison { Equal, Better, Worse };
9030 }
9031 
9032 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9033 /// overload resolution.
9034 ///
9035 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9036 /// Cand1's first N enable_if attributes have precisely the same conditions as
9037 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9038 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9039 ///
9040 /// Note that you can have a pair of candidates such that Cand1's enable_if
9041 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9042 /// worse than Cand1's.
9043 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9044                                        const FunctionDecl *Cand2) {
9045   // Common case: One (or both) decls don't have enable_if attrs.
9046   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9047   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9048   if (!Cand1Attr || !Cand2Attr) {
9049     if (Cand1Attr == Cand2Attr)
9050       return Comparison::Equal;
9051     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9052   }
9053 
9054   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9055   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9056 
9057   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9058   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9059     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9060     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9061 
9062     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9063     // has fewer enable_if attributes than Cand2, and vice versa.
9064     if (!Cand1A)
9065       return Comparison::Worse;
9066     if (!Cand2A)
9067       return Comparison::Better;
9068 
9069     Cand1ID.clear();
9070     Cand2ID.clear();
9071 
9072     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9073     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9074     if (Cand1ID != Cand2ID)
9075       return Comparison::Worse;
9076   }
9077 
9078   return Comparison::Equal;
9079 }
9080 
9081 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9082                                           const OverloadCandidate &Cand2) {
9083   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9084       !Cand2.Function->isMultiVersion())
9085     return false;
9086 
9087   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9088   // is obviously better.
9089   if (Cand1.Function->isInvalidDecl()) return false;
9090   if (Cand2.Function->isInvalidDecl()) return true;
9091 
9092   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9093   // cpu_dispatch, else arbitrarily based on the identifiers.
9094   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9095   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9096   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9097   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9098 
9099   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9100     return false;
9101 
9102   if (Cand1CPUDisp && !Cand2CPUDisp)
9103     return true;
9104   if (Cand2CPUDisp && !Cand1CPUDisp)
9105     return false;
9106 
9107   if (Cand1CPUSpec && Cand2CPUSpec) {
9108     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9109       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9110 
9111     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9112         FirstDiff = std::mismatch(
9113             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9114             Cand2CPUSpec->cpus_begin(),
9115             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9116               return LHS->getName() == RHS->getName();
9117             });
9118 
9119     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9120            "Two different cpu-specific versions should not have the same "
9121            "identifier list, otherwise they'd be the same decl!");
9122     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9123   }
9124   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9125 }
9126 
9127 /// isBetterOverloadCandidate - Determines whether the first overload
9128 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9129 bool clang::isBetterOverloadCandidate(
9130     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9131     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9132   // Define viable functions to be better candidates than non-viable
9133   // functions.
9134   if (!Cand2.Viable)
9135     return Cand1.Viable;
9136   else if (!Cand1.Viable)
9137     return false;
9138 
9139   // C++ [over.match.best]p1:
9140   //
9141   //   -- if F is a static member function, ICS1(F) is defined such
9142   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9143   //      any function G, and, symmetrically, ICS1(G) is neither
9144   //      better nor worse than ICS1(F).
9145   unsigned StartArg = 0;
9146   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9147     StartArg = 1;
9148 
9149   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9150     // We don't allow incompatible pointer conversions in C++.
9151     if (!S.getLangOpts().CPlusPlus)
9152       return ICS.isStandard() &&
9153              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9154 
9155     // The only ill-formed conversion we allow in C++ is the string literal to
9156     // char* conversion, which is only considered ill-formed after C++11.
9157     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9158            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9159   };
9160 
9161   // Define functions that don't require ill-formed conversions for a given
9162   // argument to be better candidates than functions that do.
9163   unsigned NumArgs = Cand1.Conversions.size();
9164   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9165   bool HasBetterConversion = false;
9166   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9167     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9168     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9169     if (Cand1Bad != Cand2Bad) {
9170       if (Cand1Bad)
9171         return false;
9172       HasBetterConversion = true;
9173     }
9174   }
9175 
9176   if (HasBetterConversion)
9177     return true;
9178 
9179   // C++ [over.match.best]p1:
9180   //   A viable function F1 is defined to be a better function than another
9181   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9182   //   conversion sequence than ICSi(F2), and then...
9183   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9184     switch (CompareImplicitConversionSequences(S, Loc,
9185                                                Cand1.Conversions[ArgIdx],
9186                                                Cand2.Conversions[ArgIdx])) {
9187     case ImplicitConversionSequence::Better:
9188       // Cand1 has a better conversion sequence.
9189       HasBetterConversion = true;
9190       break;
9191 
9192     case ImplicitConversionSequence::Worse:
9193       // Cand1 can't be better than Cand2.
9194       return false;
9195 
9196     case ImplicitConversionSequence::Indistinguishable:
9197       // Do nothing.
9198       break;
9199     }
9200   }
9201 
9202   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9203   //       ICSj(F2), or, if not that,
9204   if (HasBetterConversion)
9205     return true;
9206 
9207   //   -- the context is an initialization by user-defined conversion
9208   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9209   //      from the return type of F1 to the destination type (i.e.,
9210   //      the type of the entity being initialized) is a better
9211   //      conversion sequence than the standard conversion sequence
9212   //      from the return type of F2 to the destination type.
9213   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9214       Cand1.Function && Cand2.Function &&
9215       isa<CXXConversionDecl>(Cand1.Function) &&
9216       isa<CXXConversionDecl>(Cand2.Function)) {
9217     // First check whether we prefer one of the conversion functions over the
9218     // other. This only distinguishes the results in non-standard, extension
9219     // cases such as the conversion from a lambda closure type to a function
9220     // pointer or block.
9221     ImplicitConversionSequence::CompareKind Result =
9222         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9223     if (Result == ImplicitConversionSequence::Indistinguishable)
9224       Result = CompareStandardConversionSequences(S, Loc,
9225                                                   Cand1.FinalConversion,
9226                                                   Cand2.FinalConversion);
9227 
9228     if (Result != ImplicitConversionSequence::Indistinguishable)
9229       return Result == ImplicitConversionSequence::Better;
9230 
9231     // FIXME: Compare kind of reference binding if conversion functions
9232     // convert to a reference type used in direct reference binding, per
9233     // C++14 [over.match.best]p1 section 2 bullet 3.
9234   }
9235 
9236   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9237   // as combined with the resolution to CWG issue 243.
9238   //
9239   // When the context is initialization by constructor ([over.match.ctor] or
9240   // either phase of [over.match.list]), a constructor is preferred over
9241   // a conversion function.
9242   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9243       Cand1.Function && Cand2.Function &&
9244       isa<CXXConstructorDecl>(Cand1.Function) !=
9245           isa<CXXConstructorDecl>(Cand2.Function))
9246     return isa<CXXConstructorDecl>(Cand1.Function);
9247 
9248   //    -- F1 is a non-template function and F2 is a function template
9249   //       specialization, or, if not that,
9250   bool Cand1IsSpecialization = Cand1.Function &&
9251                                Cand1.Function->getPrimaryTemplate();
9252   bool Cand2IsSpecialization = Cand2.Function &&
9253                                Cand2.Function->getPrimaryTemplate();
9254   if (Cand1IsSpecialization != Cand2IsSpecialization)
9255     return Cand2IsSpecialization;
9256 
9257   //   -- F1 and F2 are function template specializations, and the function
9258   //      template for F1 is more specialized than the template for F2
9259   //      according to the partial ordering rules described in 14.5.5.2, or,
9260   //      if not that,
9261   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9262     if (FunctionTemplateDecl *BetterTemplate
9263           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9264                                          Cand2.Function->getPrimaryTemplate(),
9265                                          Loc,
9266                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9267                                                              : TPOC_Call,
9268                                          Cand1.ExplicitCallArguments,
9269                                          Cand2.ExplicitCallArguments))
9270       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9271   }
9272 
9273   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9274   // A derived-class constructor beats an (inherited) base class constructor.
9275   bool Cand1IsInherited =
9276       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9277   bool Cand2IsInherited =
9278       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9279   if (Cand1IsInherited != Cand2IsInherited)
9280     return Cand2IsInherited;
9281   else if (Cand1IsInherited) {
9282     assert(Cand2IsInherited);
9283     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9284     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9285     if (Cand1Class->isDerivedFrom(Cand2Class))
9286       return true;
9287     if (Cand2Class->isDerivedFrom(Cand1Class))
9288       return false;
9289     // Inherited from sibling base classes: still ambiguous.
9290   }
9291 
9292   // Check C++17 tie-breakers for deduction guides.
9293   {
9294     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9295     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9296     if (Guide1 && Guide2) {
9297       //  -- F1 is generated from a deduction-guide and F2 is not
9298       if (Guide1->isImplicit() != Guide2->isImplicit())
9299         return Guide2->isImplicit();
9300 
9301       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9302       if (Guide1->isCopyDeductionCandidate())
9303         return true;
9304     }
9305   }
9306 
9307   // Check for enable_if value-based overload resolution.
9308   if (Cand1.Function && Cand2.Function) {
9309     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9310     if (Cmp != Comparison::Equal)
9311       return Cmp == Comparison::Better;
9312   }
9313 
9314   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9315     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9316     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9317            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9318   }
9319 
9320   bool HasPS1 = Cand1.Function != nullptr &&
9321                 functionHasPassObjectSizeParams(Cand1.Function);
9322   bool HasPS2 = Cand2.Function != nullptr &&
9323                 functionHasPassObjectSizeParams(Cand2.Function);
9324   if (HasPS1 != HasPS2 && HasPS1)
9325     return true;
9326 
9327   return isBetterMultiversionCandidate(Cand1, Cand2);
9328 }
9329 
9330 /// Determine whether two declarations are "equivalent" for the purposes of
9331 /// name lookup and overload resolution. This applies when the same internal/no
9332 /// linkage entity is defined by two modules (probably by textually including
9333 /// the same header). In such a case, we don't consider the declarations to
9334 /// declare the same entity, but we also don't want lookups with both
9335 /// declarations visible to be ambiguous in some cases (this happens when using
9336 /// a modularized libstdc++).
9337 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9338                                                   const NamedDecl *B) {
9339   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9340   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9341   if (!VA || !VB)
9342     return false;
9343 
9344   // The declarations must be declaring the same name as an internal linkage
9345   // entity in different modules.
9346   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9347           VB->getDeclContext()->getRedeclContext()) ||
9348       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9349           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9350       VA->isExternallyVisible() || VB->isExternallyVisible())
9351     return false;
9352 
9353   // Check that the declarations appear to be equivalent.
9354   //
9355   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9356   // For constants and functions, we should check the initializer or body is
9357   // the same. For non-constant variables, we shouldn't allow it at all.
9358   if (Context.hasSameType(VA->getType(), VB->getType()))
9359     return true;
9360 
9361   // Enum constants within unnamed enumerations will have different types, but
9362   // may still be similar enough to be interchangeable for our purposes.
9363   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9364     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9365       // Only handle anonymous enums. If the enumerations were named and
9366       // equivalent, they would have been merged to the same type.
9367       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9368       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9369       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9370           !Context.hasSameType(EnumA->getIntegerType(),
9371                                EnumB->getIntegerType()))
9372         return false;
9373       // Allow this only if the value is the same for both enumerators.
9374       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9375     }
9376   }
9377 
9378   // Nothing else is sufficiently similar.
9379   return false;
9380 }
9381 
9382 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9383     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9384   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9385 
9386   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9387   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9388       << !M << (M ? M->getFullModuleName() : "");
9389 
9390   for (auto *E : Equiv) {
9391     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9392     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9393         << !M << (M ? M->getFullModuleName() : "");
9394   }
9395 }
9396 
9397 /// Computes the best viable function (C++ 13.3.3)
9398 /// within an overload candidate set.
9399 ///
9400 /// \param Loc The location of the function name (or operator symbol) for
9401 /// which overload resolution occurs.
9402 ///
9403 /// \param Best If overload resolution was successful or found a deleted
9404 /// function, \p Best points to the candidate function found.
9405 ///
9406 /// \returns The result of overload resolution.
9407 OverloadingResult
9408 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9409                                          iterator &Best) {
9410   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9411   std::transform(begin(), end(), std::back_inserter(Candidates),
9412                  [](OverloadCandidate &Cand) { return &Cand; });
9413 
9414   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9415   // are accepted by both clang and NVCC. However, during a particular
9416   // compilation mode only one call variant is viable. We need to
9417   // exclude non-viable overload candidates from consideration based
9418   // only on their host/device attributes. Specifically, if one
9419   // candidate call is WrongSide and the other is SameSide, we ignore
9420   // the WrongSide candidate.
9421   if (S.getLangOpts().CUDA) {
9422     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9423     bool ContainsSameSideCandidate =
9424         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9425           return Cand->Function &&
9426                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9427                      Sema::CFP_SameSide;
9428         });
9429     if (ContainsSameSideCandidate) {
9430       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9431         return Cand->Function &&
9432                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9433                    Sema::CFP_WrongSide;
9434       };
9435       llvm::erase_if(Candidates, IsWrongSideCandidate);
9436     }
9437   }
9438 
9439   // Find the best viable function.
9440   Best = end();
9441   for (auto *Cand : Candidates)
9442     if (Cand->Viable)
9443       if (Best == end() ||
9444           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9445         Best = Cand;
9446 
9447   // If we didn't find any viable functions, abort.
9448   if (Best == end())
9449     return OR_No_Viable_Function;
9450 
9451   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9452 
9453   // Make sure that this function is better than every other viable
9454   // function. If not, we have an ambiguity.
9455   for (auto *Cand : Candidates) {
9456     if (Cand->Viable && Cand != Best &&
9457         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9458       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9459                                                    Cand->Function)) {
9460         EquivalentCands.push_back(Cand->Function);
9461         continue;
9462       }
9463 
9464       Best = end();
9465       return OR_Ambiguous;
9466     }
9467   }
9468 
9469   // Best is the best viable function.
9470   if (Best->Function && Best->Function->isDeleted())
9471     return OR_Deleted;
9472 
9473   if (!EquivalentCands.empty())
9474     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9475                                                     EquivalentCands);
9476 
9477   return OR_Success;
9478 }
9479 
9480 namespace {
9481 
9482 enum OverloadCandidateKind {
9483   oc_function,
9484   oc_method,
9485   oc_constructor,
9486   oc_implicit_default_constructor,
9487   oc_implicit_copy_constructor,
9488   oc_implicit_move_constructor,
9489   oc_implicit_copy_assignment,
9490   oc_implicit_move_assignment,
9491   oc_inherited_constructor
9492 };
9493 
9494 enum OverloadCandidateSelect {
9495   ocs_non_template,
9496   ocs_template,
9497   ocs_described_template,
9498 };
9499 
9500 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9501 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9502                           std::string &Description) {
9503 
9504   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9505   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9506     isTemplate = true;
9507     Description = S.getTemplateArgumentBindingsText(
9508         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9509   }
9510 
9511   OverloadCandidateSelect Select = [&]() {
9512     if (!Description.empty())
9513       return ocs_described_template;
9514     return isTemplate ? ocs_template : ocs_non_template;
9515   }();
9516 
9517   OverloadCandidateKind Kind = [&]() {
9518     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9519       if (!Ctor->isImplicit()) {
9520         if (isa<ConstructorUsingShadowDecl>(Found))
9521           return oc_inherited_constructor;
9522         else
9523           return oc_constructor;
9524       }
9525 
9526       if (Ctor->isDefaultConstructor())
9527         return oc_implicit_default_constructor;
9528 
9529       if (Ctor->isMoveConstructor())
9530         return oc_implicit_move_constructor;
9531 
9532       assert(Ctor->isCopyConstructor() &&
9533              "unexpected sort of implicit constructor");
9534       return oc_implicit_copy_constructor;
9535     }
9536 
9537     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9538       // This actually gets spelled 'candidate function' for now, but
9539       // it doesn't hurt to split it out.
9540       if (!Meth->isImplicit())
9541         return oc_method;
9542 
9543       if (Meth->isMoveAssignmentOperator())
9544         return oc_implicit_move_assignment;
9545 
9546       if (Meth->isCopyAssignmentOperator())
9547         return oc_implicit_copy_assignment;
9548 
9549       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9550       return oc_method;
9551     }
9552 
9553     return oc_function;
9554   }();
9555 
9556   return std::make_pair(Kind, Select);
9557 }
9558 
9559 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9560   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9561   // set.
9562   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9563     S.Diag(FoundDecl->getLocation(),
9564            diag::note_ovl_candidate_inherited_constructor)
9565       << Shadow->getNominatedBaseClass();
9566 }
9567 
9568 } // end anonymous namespace
9569 
9570 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9571                                     const FunctionDecl *FD) {
9572   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9573     bool AlwaysTrue;
9574     if (EnableIf->getCond()->isValueDependent() ||
9575         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9576       return false;
9577     if (!AlwaysTrue)
9578       return false;
9579   }
9580   return true;
9581 }
9582 
9583 /// Returns true if we can take the address of the function.
9584 ///
9585 /// \param Complain - If true, we'll emit a diagnostic
9586 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9587 ///   we in overload resolution?
9588 /// \param Loc - The location of the statement we're complaining about. Ignored
9589 ///   if we're not complaining, or if we're in overload resolution.
9590 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9591                                               bool Complain,
9592                                               bool InOverloadResolution,
9593                                               SourceLocation Loc) {
9594   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9595     if (Complain) {
9596       if (InOverloadResolution)
9597         S.Diag(FD->getBeginLoc(),
9598                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9599       else
9600         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9601     }
9602     return false;
9603   }
9604 
9605   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9606     return P->hasAttr<PassObjectSizeAttr>();
9607   });
9608   if (I == FD->param_end())
9609     return true;
9610 
9611   if (Complain) {
9612     // Add one to ParamNo because it's user-facing
9613     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9614     if (InOverloadResolution)
9615       S.Diag(FD->getLocation(),
9616              diag::note_ovl_candidate_has_pass_object_size_params)
9617           << ParamNo;
9618     else
9619       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9620           << FD << ParamNo;
9621   }
9622   return false;
9623 }
9624 
9625 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9626                                                const FunctionDecl *FD) {
9627   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9628                                            /*InOverloadResolution=*/true,
9629                                            /*Loc=*/SourceLocation());
9630 }
9631 
9632 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9633                                              bool Complain,
9634                                              SourceLocation Loc) {
9635   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9636                                              /*InOverloadResolution=*/false,
9637                                              Loc);
9638 }
9639 
9640 // Notes the location of an overload candidate.
9641 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9642                                  QualType DestType, bool TakingAddress) {
9643   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9644     return;
9645   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9646       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9647     return;
9648 
9649   std::string FnDesc;
9650   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9651       ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9652   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9653                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9654                          << Fn << FnDesc;
9655 
9656   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9657   Diag(Fn->getLocation(), PD);
9658   MaybeEmitInheritedConstructorNote(*this, Found);
9659 }
9660 
9661 // Notes the location of all overload candidates designated through
9662 // OverloadedExpr
9663 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9664                                      bool TakingAddress) {
9665   assert(OverloadedExpr->getType() == Context.OverloadTy);
9666 
9667   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9668   OverloadExpr *OvlExpr = Ovl.Expression;
9669 
9670   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9671                             IEnd = OvlExpr->decls_end();
9672        I != IEnd; ++I) {
9673     if (FunctionTemplateDecl *FunTmpl =
9674                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9675       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9676                             TakingAddress);
9677     } else if (FunctionDecl *Fun
9678                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9679       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9680     }
9681   }
9682 }
9683 
9684 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9685 /// "lead" diagnostic; it will be given two arguments, the source and
9686 /// target types of the conversion.
9687 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9688                                  Sema &S,
9689                                  SourceLocation CaretLoc,
9690                                  const PartialDiagnostic &PDiag) const {
9691   S.Diag(CaretLoc, PDiag)
9692     << Ambiguous.getFromType() << Ambiguous.getToType();
9693   // FIXME: The note limiting machinery is borrowed from
9694   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9695   // refactoring here.
9696   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9697   unsigned CandsShown = 0;
9698   AmbiguousConversionSequence::const_iterator I, E;
9699   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9700     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9701       break;
9702     ++CandsShown;
9703     S.NoteOverloadCandidate(I->first, I->second);
9704   }
9705   if (I != E)
9706     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9707 }
9708 
9709 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9710                                   unsigned I, bool TakingCandidateAddress) {
9711   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9712   assert(Conv.isBad());
9713   assert(Cand->Function && "for now, candidate must be a function");
9714   FunctionDecl *Fn = Cand->Function;
9715 
9716   // There's a conversion slot for the object argument if this is a
9717   // non-constructor method.  Note that 'I' corresponds the
9718   // conversion-slot index.
9719   bool isObjectArgument = false;
9720   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9721     if (I == 0)
9722       isObjectArgument = true;
9723     else
9724       I--;
9725   }
9726 
9727   std::string FnDesc;
9728   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9729       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9730 
9731   Expr *FromExpr = Conv.Bad.FromExpr;
9732   QualType FromTy = Conv.Bad.getFromType();
9733   QualType ToTy = Conv.Bad.getToType();
9734 
9735   if (FromTy == S.Context.OverloadTy) {
9736     assert(FromExpr && "overload set argument came from implicit argument?");
9737     Expr *E = FromExpr->IgnoreParens();
9738     if (isa<UnaryOperator>(E))
9739       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9740     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9741 
9742     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9743         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9744         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9745         << Name << I + 1;
9746     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9747     return;
9748   }
9749 
9750   // Do some hand-waving analysis to see if the non-viability is due
9751   // to a qualifier mismatch.
9752   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9753   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9754   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9755     CToTy = RT->getPointeeType();
9756   else {
9757     // TODO: detect and diagnose the full richness of const mismatches.
9758     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9759       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9760         CFromTy = FromPT->getPointeeType();
9761         CToTy = ToPT->getPointeeType();
9762       }
9763   }
9764 
9765   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9766       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9767     Qualifiers FromQs = CFromTy.getQualifiers();
9768     Qualifiers ToQs = CToTy.getQualifiers();
9769 
9770     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9771       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9772           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9773           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9774           << ToTy << (unsigned)isObjectArgument << I + 1;
9775       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9776       return;
9777     }
9778 
9779     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9780       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9781           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9782           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9783           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9784           << (unsigned)isObjectArgument << I + 1;
9785       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9786       return;
9787     }
9788 
9789     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9790       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9791           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9792           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9793           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9794           << (unsigned)isObjectArgument << I + 1;
9795       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9796       return;
9797     }
9798 
9799     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9800       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9801           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9802           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9803           << FromQs.hasUnaligned() << I + 1;
9804       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9805       return;
9806     }
9807 
9808     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9809     assert(CVR && "unexpected qualifiers mismatch");
9810 
9811     if (isObjectArgument) {
9812       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9813           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9814           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9815           << (CVR - 1);
9816     } else {
9817       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9818           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9819           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9820           << (CVR - 1) << I + 1;
9821     }
9822     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9823     return;
9824   }
9825 
9826   // Special diagnostic for failure to convert an initializer list, since
9827   // telling the user that it has type void is not useful.
9828   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9829     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9830         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9831         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9832         << ToTy << (unsigned)isObjectArgument << I + 1;
9833     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9834     return;
9835   }
9836 
9837   // Diagnose references or pointers to incomplete types differently,
9838   // since it's far from impossible that the incompleteness triggered
9839   // the failure.
9840   QualType TempFromTy = FromTy.getNonReferenceType();
9841   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9842     TempFromTy = PTy->getPointeeType();
9843   if (TempFromTy->isIncompleteType()) {
9844     // Emit the generic diagnostic and, optionally, add the hints to it.
9845     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9846         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9847         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9848         << ToTy << (unsigned)isObjectArgument << I + 1
9849         << (unsigned)(Cand->Fix.Kind);
9850 
9851     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9852     return;
9853   }
9854 
9855   // Diagnose base -> derived pointer conversions.
9856   unsigned BaseToDerivedConversion = 0;
9857   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9858     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9859       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9860                                                FromPtrTy->getPointeeType()) &&
9861           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9862           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9863           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9864                           FromPtrTy->getPointeeType()))
9865         BaseToDerivedConversion = 1;
9866     }
9867   } else if (const ObjCObjectPointerType *FromPtrTy
9868                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9869     if (const ObjCObjectPointerType *ToPtrTy
9870                                         = ToTy->getAs<ObjCObjectPointerType>())
9871       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9872         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9873           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9874                                                 FromPtrTy->getPointeeType()) &&
9875               FromIface->isSuperClassOf(ToIface))
9876             BaseToDerivedConversion = 2;
9877   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9878     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9879         !FromTy->isIncompleteType() &&
9880         !ToRefTy->getPointeeType()->isIncompleteType() &&
9881         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9882       BaseToDerivedConversion = 3;
9883     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9884                ToTy.getNonReferenceType().getCanonicalType() ==
9885                FromTy.getNonReferenceType().getCanonicalType()) {
9886       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9887           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9888           << (unsigned)isObjectArgument << I + 1
9889           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9890       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9891       return;
9892     }
9893   }
9894 
9895   if (BaseToDerivedConversion) {
9896     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9897         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9898         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9899         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9900     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9901     return;
9902   }
9903 
9904   if (isa<ObjCObjectPointerType>(CFromTy) &&
9905       isa<PointerType>(CToTy)) {
9906       Qualifiers FromQs = CFromTy.getQualifiers();
9907       Qualifiers ToQs = CToTy.getQualifiers();
9908       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9909         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9910             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9911             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9912             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9913         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9914         return;
9915       }
9916   }
9917 
9918   if (TakingCandidateAddress &&
9919       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9920     return;
9921 
9922   // Emit the generic diagnostic and, optionally, add the hints to it.
9923   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9924   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9925         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9926         << ToTy << (unsigned)isObjectArgument << I + 1
9927         << (unsigned)(Cand->Fix.Kind);
9928 
9929   // If we can fix the conversion, suggest the FixIts.
9930   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9931        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9932     FDiag << *HI;
9933   S.Diag(Fn->getLocation(), FDiag);
9934 
9935   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9936 }
9937 
9938 /// Additional arity mismatch diagnosis specific to a function overload
9939 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9940 /// over a candidate in any candidate set.
9941 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9942                                unsigned NumArgs) {
9943   FunctionDecl *Fn = Cand->Function;
9944   unsigned MinParams = Fn->getMinRequiredArguments();
9945 
9946   // With invalid overloaded operators, it's possible that we think we
9947   // have an arity mismatch when in fact it looks like we have the
9948   // right number of arguments, because only overloaded operators have
9949   // the weird behavior of overloading member and non-member functions.
9950   // Just don't report anything.
9951   if (Fn->isInvalidDecl() &&
9952       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9953     return true;
9954 
9955   if (NumArgs < MinParams) {
9956     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9957            (Cand->FailureKind == ovl_fail_bad_deduction &&
9958             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9959   } else {
9960     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9961            (Cand->FailureKind == ovl_fail_bad_deduction &&
9962             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9963   }
9964 
9965   return false;
9966 }
9967 
9968 /// General arity mismatch diagnosis over a candidate in a candidate set.
9969 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9970                                   unsigned NumFormalArgs) {
9971   assert(isa<FunctionDecl>(D) &&
9972       "The templated declaration should at least be a function"
9973       " when diagnosing bad template argument deduction due to too many"
9974       " or too few arguments");
9975 
9976   FunctionDecl *Fn = cast<FunctionDecl>(D);
9977 
9978   // TODO: treat calls to a missing default constructor as a special case
9979   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9980   unsigned MinParams = Fn->getMinRequiredArguments();
9981 
9982   // at least / at most / exactly
9983   unsigned mode, modeCount;
9984   if (NumFormalArgs < MinParams) {
9985     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9986         FnTy->isTemplateVariadic())
9987       mode = 0; // "at least"
9988     else
9989       mode = 2; // "exactly"
9990     modeCount = MinParams;
9991   } else {
9992     if (MinParams != FnTy->getNumParams())
9993       mode = 1; // "at most"
9994     else
9995       mode = 2; // "exactly"
9996     modeCount = FnTy->getNumParams();
9997   }
9998 
9999   std::string Description;
10000   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10001       ClassifyOverloadCandidate(S, Found, Fn, Description);
10002 
10003   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10004     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10005         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10006         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10007   else
10008     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10009         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10010         << Description << mode << modeCount << NumFormalArgs;
10011 
10012   MaybeEmitInheritedConstructorNote(S, Found);
10013 }
10014 
10015 /// Arity mismatch diagnosis specific to a function overload candidate.
10016 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10017                                   unsigned NumFormalArgs) {
10018   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10019     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10020 }
10021 
10022 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10023   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10024     return TD;
10025   llvm_unreachable("Unsupported: Getting the described template declaration"
10026                    " for bad deduction diagnosis");
10027 }
10028 
10029 /// Diagnose a failed template-argument deduction.
10030 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10031                                  DeductionFailureInfo &DeductionFailure,
10032                                  unsigned NumArgs,
10033                                  bool TakingCandidateAddress) {
10034   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10035   NamedDecl *ParamD;
10036   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10037   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10038   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10039   switch (DeductionFailure.Result) {
10040   case Sema::TDK_Success:
10041     llvm_unreachable("TDK_success while diagnosing bad deduction");
10042 
10043   case Sema::TDK_Incomplete: {
10044     assert(ParamD && "no parameter found for incomplete deduction result");
10045     S.Diag(Templated->getLocation(),
10046            diag::note_ovl_candidate_incomplete_deduction)
10047         << ParamD->getDeclName();
10048     MaybeEmitInheritedConstructorNote(S, Found);
10049     return;
10050   }
10051 
10052   case Sema::TDK_IncompletePack: {
10053     assert(ParamD && "no parameter found for incomplete deduction result");
10054     S.Diag(Templated->getLocation(),
10055            diag::note_ovl_candidate_incomplete_deduction_pack)
10056         << ParamD->getDeclName()
10057         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10058         << *DeductionFailure.getFirstArg();
10059     MaybeEmitInheritedConstructorNote(S, Found);
10060     return;
10061   }
10062 
10063   case Sema::TDK_Underqualified: {
10064     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10065     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10066 
10067     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10068 
10069     // Param will have been canonicalized, but it should just be a
10070     // qualified version of ParamD, so move the qualifiers to that.
10071     QualifierCollector Qs;
10072     Qs.strip(Param);
10073     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10074     assert(S.Context.hasSameType(Param, NonCanonParam));
10075 
10076     // Arg has also been canonicalized, but there's nothing we can do
10077     // about that.  It also doesn't matter as much, because it won't
10078     // have any template parameters in it (because deduction isn't
10079     // done on dependent types).
10080     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10081 
10082     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10083         << ParamD->getDeclName() << Arg << NonCanonParam;
10084     MaybeEmitInheritedConstructorNote(S, Found);
10085     return;
10086   }
10087 
10088   case Sema::TDK_Inconsistent: {
10089     assert(ParamD && "no parameter found for inconsistent deduction result");
10090     int which = 0;
10091     if (isa<TemplateTypeParmDecl>(ParamD))
10092       which = 0;
10093     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10094       // Deduction might have failed because we deduced arguments of two
10095       // different types for a non-type template parameter.
10096       // FIXME: Use a different TDK value for this.
10097       QualType T1 =
10098           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10099       QualType T2 =
10100           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10101       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10102         S.Diag(Templated->getLocation(),
10103                diag::note_ovl_candidate_inconsistent_deduction_types)
10104           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10105           << *DeductionFailure.getSecondArg() << T2;
10106         MaybeEmitInheritedConstructorNote(S, Found);
10107         return;
10108       }
10109 
10110       which = 1;
10111     } else {
10112       which = 2;
10113     }
10114 
10115     S.Diag(Templated->getLocation(),
10116            diag::note_ovl_candidate_inconsistent_deduction)
10117         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10118         << *DeductionFailure.getSecondArg();
10119     MaybeEmitInheritedConstructorNote(S, Found);
10120     return;
10121   }
10122 
10123   case Sema::TDK_InvalidExplicitArguments:
10124     assert(ParamD && "no parameter found for invalid explicit arguments");
10125     if (ParamD->getDeclName())
10126       S.Diag(Templated->getLocation(),
10127              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10128           << ParamD->getDeclName();
10129     else {
10130       int index = 0;
10131       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10132         index = TTP->getIndex();
10133       else if (NonTypeTemplateParmDecl *NTTP
10134                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10135         index = NTTP->getIndex();
10136       else
10137         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10138       S.Diag(Templated->getLocation(),
10139              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10140           << (index + 1);
10141     }
10142     MaybeEmitInheritedConstructorNote(S, Found);
10143     return;
10144 
10145   case Sema::TDK_TooManyArguments:
10146   case Sema::TDK_TooFewArguments:
10147     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10148     return;
10149 
10150   case Sema::TDK_InstantiationDepth:
10151     S.Diag(Templated->getLocation(),
10152            diag::note_ovl_candidate_instantiation_depth);
10153     MaybeEmitInheritedConstructorNote(S, Found);
10154     return;
10155 
10156   case Sema::TDK_SubstitutionFailure: {
10157     // Format the template argument list into the argument string.
10158     SmallString<128> TemplateArgString;
10159     if (TemplateArgumentList *Args =
10160             DeductionFailure.getTemplateArgumentList()) {
10161       TemplateArgString = " ";
10162       TemplateArgString += S.getTemplateArgumentBindingsText(
10163           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10164     }
10165 
10166     // If this candidate was disabled by enable_if, say so.
10167     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10168     if (PDiag && PDiag->second.getDiagID() ==
10169           diag::err_typename_nested_not_found_enable_if) {
10170       // FIXME: Use the source range of the condition, and the fully-qualified
10171       //        name of the enable_if template. These are both present in PDiag.
10172       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10173         << "'enable_if'" << TemplateArgString;
10174       return;
10175     }
10176 
10177     // We found a specific requirement that disabled the enable_if.
10178     if (PDiag && PDiag->second.getDiagID() ==
10179         diag::err_typename_nested_not_found_requirement) {
10180       S.Diag(Templated->getLocation(),
10181              diag::note_ovl_candidate_disabled_by_requirement)
10182         << PDiag->second.getStringArg(0) << TemplateArgString;
10183       return;
10184     }
10185 
10186     // Format the SFINAE diagnostic into the argument string.
10187     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10188     //        formatted message in another diagnostic.
10189     SmallString<128> SFINAEArgString;
10190     SourceRange R;
10191     if (PDiag) {
10192       SFINAEArgString = ": ";
10193       R = SourceRange(PDiag->first, PDiag->first);
10194       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10195     }
10196 
10197     S.Diag(Templated->getLocation(),
10198            diag::note_ovl_candidate_substitution_failure)
10199         << TemplateArgString << SFINAEArgString << R;
10200     MaybeEmitInheritedConstructorNote(S, Found);
10201     return;
10202   }
10203 
10204   case Sema::TDK_DeducedMismatch:
10205   case Sema::TDK_DeducedMismatchNested: {
10206     // Format the template argument list into the argument string.
10207     SmallString<128> TemplateArgString;
10208     if (TemplateArgumentList *Args =
10209             DeductionFailure.getTemplateArgumentList()) {
10210       TemplateArgString = " ";
10211       TemplateArgString += S.getTemplateArgumentBindingsText(
10212           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10213     }
10214 
10215     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10216         << (*DeductionFailure.getCallArgIndex() + 1)
10217         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10218         << TemplateArgString
10219         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10220     break;
10221   }
10222 
10223   case Sema::TDK_NonDeducedMismatch: {
10224     // FIXME: Provide a source location to indicate what we couldn't match.
10225     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10226     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10227     if (FirstTA.getKind() == TemplateArgument::Template &&
10228         SecondTA.getKind() == TemplateArgument::Template) {
10229       TemplateName FirstTN = FirstTA.getAsTemplate();
10230       TemplateName SecondTN = SecondTA.getAsTemplate();
10231       if (FirstTN.getKind() == TemplateName::Template &&
10232           SecondTN.getKind() == TemplateName::Template) {
10233         if (FirstTN.getAsTemplateDecl()->getName() ==
10234             SecondTN.getAsTemplateDecl()->getName()) {
10235           // FIXME: This fixes a bad diagnostic where both templates are named
10236           // the same.  This particular case is a bit difficult since:
10237           // 1) It is passed as a string to the diagnostic printer.
10238           // 2) The diagnostic printer only attempts to find a better
10239           //    name for types, not decls.
10240           // Ideally, this should folded into the diagnostic printer.
10241           S.Diag(Templated->getLocation(),
10242                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10243               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10244           return;
10245         }
10246       }
10247     }
10248 
10249     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10250         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10251       return;
10252 
10253     // FIXME: For generic lambda parameters, check if the function is a lambda
10254     // call operator, and if so, emit a prettier and more informative
10255     // diagnostic that mentions 'auto' and lambda in addition to
10256     // (or instead of?) the canonical template type parameters.
10257     S.Diag(Templated->getLocation(),
10258            diag::note_ovl_candidate_non_deduced_mismatch)
10259         << FirstTA << SecondTA;
10260     return;
10261   }
10262   // TODO: diagnose these individually, then kill off
10263   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10264   case Sema::TDK_MiscellaneousDeductionFailure:
10265     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10266     MaybeEmitInheritedConstructorNote(S, Found);
10267     return;
10268   case Sema::TDK_CUDATargetMismatch:
10269     S.Diag(Templated->getLocation(),
10270            diag::note_cuda_ovl_candidate_target_mismatch);
10271     return;
10272   }
10273 }
10274 
10275 /// Diagnose a failed template-argument deduction, for function calls.
10276 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10277                                  unsigned NumArgs,
10278                                  bool TakingCandidateAddress) {
10279   unsigned TDK = Cand->DeductionFailure.Result;
10280   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10281     if (CheckArityMismatch(S, Cand, NumArgs))
10282       return;
10283   }
10284   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10285                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10286 }
10287 
10288 /// CUDA: diagnose an invalid call across targets.
10289 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10290   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10291   FunctionDecl *Callee = Cand->Function;
10292 
10293   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10294                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10295 
10296   std::string FnDesc;
10297   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10298       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10299 
10300   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10301       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10302       << FnDesc /* Ignored */
10303       << CalleeTarget << CallerTarget;
10304 
10305   // This could be an implicit constructor for which we could not infer the
10306   // target due to a collsion. Diagnose that case.
10307   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10308   if (Meth != nullptr && Meth->isImplicit()) {
10309     CXXRecordDecl *ParentClass = Meth->getParent();
10310     Sema::CXXSpecialMember CSM;
10311 
10312     switch (FnKindPair.first) {
10313     default:
10314       return;
10315     case oc_implicit_default_constructor:
10316       CSM = Sema::CXXDefaultConstructor;
10317       break;
10318     case oc_implicit_copy_constructor:
10319       CSM = Sema::CXXCopyConstructor;
10320       break;
10321     case oc_implicit_move_constructor:
10322       CSM = Sema::CXXMoveConstructor;
10323       break;
10324     case oc_implicit_copy_assignment:
10325       CSM = Sema::CXXCopyAssignment;
10326       break;
10327     case oc_implicit_move_assignment:
10328       CSM = Sema::CXXMoveAssignment;
10329       break;
10330     };
10331 
10332     bool ConstRHS = false;
10333     if (Meth->getNumParams()) {
10334       if (const ReferenceType *RT =
10335               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10336         ConstRHS = RT->getPointeeType().isConstQualified();
10337       }
10338     }
10339 
10340     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10341                                               /* ConstRHS */ ConstRHS,
10342                                               /* Diagnose */ true);
10343   }
10344 }
10345 
10346 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10347   FunctionDecl *Callee = Cand->Function;
10348   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10349 
10350   S.Diag(Callee->getLocation(),
10351          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10352       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10353 }
10354 
10355 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10356   ExplicitSpecifier ES;
10357   const char *DeclName;
10358   switch (Cand->Function->getDeclKind()) {
10359   case Decl::Kind::CXXConstructor:
10360     ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
10361     DeclName = "constructor";
10362     break;
10363   case Decl::Kind::CXXConversion:
10364     ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
10365     DeclName = "conversion operator";
10366     break;
10367   case Decl::Kind::CXXDeductionGuide:
10368     ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
10369     DeclName = "deductiong guide";
10370     break;
10371   default:
10372     llvm_unreachable("invalid Decl");
10373   }
10374   assert(ES.getExpr() && "null expression should be handled before");
10375   S.Diag(Cand->Function->getLocation(),
10376          diag::note_ovl_candidate_explicit_forbidden)
10377       << DeclName;
10378   S.Diag(ES.getExpr()->getBeginLoc(),
10379          diag::note_explicit_bool_resolved_to_true);
10380 }
10381 
10382 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10383   FunctionDecl *Callee = Cand->Function;
10384 
10385   S.Diag(Callee->getLocation(),
10386          diag::note_ovl_candidate_disabled_by_extension)
10387     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10388 }
10389 
10390 /// Generates a 'note' diagnostic for an overload candidate.  We've
10391 /// already generated a primary error at the call site.
10392 ///
10393 /// It really does need to be a single diagnostic with its caret
10394 /// pointed at the candidate declaration.  Yes, this creates some
10395 /// major challenges of technical writing.  Yes, this makes pointing
10396 /// out problems with specific arguments quite awkward.  It's still
10397 /// better than generating twenty screens of text for every failed
10398 /// overload.
10399 ///
10400 /// It would be great to be able to express per-candidate problems
10401 /// more richly for those diagnostic clients that cared, but we'd
10402 /// still have to be just as careful with the default diagnostics.
10403 /// \param CtorDestAS Addr space of object being constructed (for ctor
10404 /// candidates only).
10405 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10406                                   unsigned NumArgs,
10407                                   bool TakingCandidateAddress,
10408                                   LangAS CtorDestAS = LangAS::Default) {
10409   FunctionDecl *Fn = Cand->Function;
10410 
10411   // Note deleted candidates, but only if they're viable.
10412   if (Cand->Viable) {
10413     if (Fn->isDeleted()) {
10414       std::string FnDesc;
10415       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10416           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10417 
10418       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10419           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10420           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10421       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10422       return;
10423     }
10424 
10425     // We don't really have anything else to say about viable candidates.
10426     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10427     return;
10428   }
10429 
10430   switch (Cand->FailureKind) {
10431   case ovl_fail_too_many_arguments:
10432   case ovl_fail_too_few_arguments:
10433     return DiagnoseArityMismatch(S, Cand, NumArgs);
10434 
10435   case ovl_fail_bad_deduction:
10436     return DiagnoseBadDeduction(S, Cand, NumArgs,
10437                                 TakingCandidateAddress);
10438 
10439   case ovl_fail_illegal_constructor: {
10440     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10441       << (Fn->getPrimaryTemplate() ? 1 : 0);
10442     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10443     return;
10444   }
10445 
10446   case ovl_fail_object_addrspace_mismatch: {
10447     Qualifiers QualsForPrinting;
10448     QualsForPrinting.setAddressSpace(CtorDestAS);
10449     S.Diag(Fn->getLocation(),
10450            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10451         << QualsForPrinting;
10452     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10453     return;
10454   }
10455 
10456   case ovl_fail_trivial_conversion:
10457   case ovl_fail_bad_final_conversion:
10458   case ovl_fail_final_conversion_not_exact:
10459     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10460 
10461   case ovl_fail_bad_conversion: {
10462     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10463     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10464       if (Cand->Conversions[I].isBad())
10465         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10466 
10467     // FIXME: this currently happens when we're called from SemaInit
10468     // when user-conversion overload fails.  Figure out how to handle
10469     // those conditions and diagnose them well.
10470     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10471   }
10472 
10473   case ovl_fail_bad_target:
10474     return DiagnoseBadTarget(S, Cand);
10475 
10476   case ovl_fail_enable_if:
10477     return DiagnoseFailedEnableIfAttr(S, Cand);
10478 
10479   case ovl_fail_explicit_resolved:
10480     return DiagnoseFailedExplicitSpec(S, Cand);
10481 
10482   case ovl_fail_ext_disabled:
10483     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10484 
10485   case ovl_fail_inhctor_slice:
10486     // It's generally not interesting to note copy/move constructors here.
10487     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10488       return;
10489     S.Diag(Fn->getLocation(),
10490            diag::note_ovl_candidate_inherited_constructor_slice)
10491       << (Fn->getPrimaryTemplate() ? 1 : 0)
10492       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10493     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10494     return;
10495 
10496   case ovl_fail_addr_not_available: {
10497     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10498     (void)Available;
10499     assert(!Available);
10500     break;
10501   }
10502   case ovl_non_default_multiversion_function:
10503     // Do nothing, these should simply be ignored.
10504     break;
10505   }
10506 }
10507 
10508 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10509   // Desugar the type of the surrogate down to a function type,
10510   // retaining as many typedefs as possible while still showing
10511   // the function type (and, therefore, its parameter types).
10512   QualType FnType = Cand->Surrogate->getConversionType();
10513   bool isLValueReference = false;
10514   bool isRValueReference = false;
10515   bool isPointer = false;
10516   if (const LValueReferenceType *FnTypeRef =
10517         FnType->getAs<LValueReferenceType>()) {
10518     FnType = FnTypeRef->getPointeeType();
10519     isLValueReference = true;
10520   } else if (const RValueReferenceType *FnTypeRef =
10521                FnType->getAs<RValueReferenceType>()) {
10522     FnType = FnTypeRef->getPointeeType();
10523     isRValueReference = true;
10524   }
10525   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10526     FnType = FnTypePtr->getPointeeType();
10527     isPointer = true;
10528   }
10529   // Desugar down to a function type.
10530   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10531   // Reconstruct the pointer/reference as appropriate.
10532   if (isPointer) FnType = S.Context.getPointerType(FnType);
10533   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10534   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10535 
10536   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10537     << FnType;
10538 }
10539 
10540 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10541                                          SourceLocation OpLoc,
10542                                          OverloadCandidate *Cand) {
10543   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10544   std::string TypeStr("operator");
10545   TypeStr += Opc;
10546   TypeStr += "(";
10547   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10548   if (Cand->Conversions.size() == 1) {
10549     TypeStr += ")";
10550     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10551   } else {
10552     TypeStr += ", ";
10553     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10554     TypeStr += ")";
10555     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10556   }
10557 }
10558 
10559 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10560                                          OverloadCandidate *Cand) {
10561   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10562     if (ICS.isBad()) break; // all meaningless after first invalid
10563     if (!ICS.isAmbiguous()) continue;
10564 
10565     ICS.DiagnoseAmbiguousConversion(
10566         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10567   }
10568 }
10569 
10570 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10571   if (Cand->Function)
10572     return Cand->Function->getLocation();
10573   if (Cand->IsSurrogate)
10574     return Cand->Surrogate->getLocation();
10575   return SourceLocation();
10576 }
10577 
10578 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10579   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10580   case Sema::TDK_Success:
10581   case Sema::TDK_NonDependentConversionFailure:
10582     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10583 
10584   case Sema::TDK_Invalid:
10585   case Sema::TDK_Incomplete:
10586   case Sema::TDK_IncompletePack:
10587     return 1;
10588 
10589   case Sema::TDK_Underqualified:
10590   case Sema::TDK_Inconsistent:
10591     return 2;
10592 
10593   case Sema::TDK_SubstitutionFailure:
10594   case Sema::TDK_DeducedMismatch:
10595   case Sema::TDK_DeducedMismatchNested:
10596   case Sema::TDK_NonDeducedMismatch:
10597   case Sema::TDK_MiscellaneousDeductionFailure:
10598   case Sema::TDK_CUDATargetMismatch:
10599     return 3;
10600 
10601   case Sema::TDK_InstantiationDepth:
10602     return 4;
10603 
10604   case Sema::TDK_InvalidExplicitArguments:
10605     return 5;
10606 
10607   case Sema::TDK_TooManyArguments:
10608   case Sema::TDK_TooFewArguments:
10609     return 6;
10610   }
10611   llvm_unreachable("Unhandled deduction result");
10612 }
10613 
10614 namespace {
10615 struct CompareOverloadCandidatesForDisplay {
10616   Sema &S;
10617   SourceLocation Loc;
10618   size_t NumArgs;
10619   OverloadCandidateSet::CandidateSetKind CSK;
10620 
10621   CompareOverloadCandidatesForDisplay(
10622       Sema &S, SourceLocation Loc, size_t NArgs,
10623       OverloadCandidateSet::CandidateSetKind CSK)
10624       : S(S), NumArgs(NArgs), CSK(CSK) {}
10625 
10626   bool operator()(const OverloadCandidate *L,
10627                   const OverloadCandidate *R) {
10628     // Fast-path this check.
10629     if (L == R) return false;
10630 
10631     // Order first by viability.
10632     if (L->Viable) {
10633       if (!R->Viable) return true;
10634 
10635       // TODO: introduce a tri-valued comparison for overload
10636       // candidates.  Would be more worthwhile if we had a sort
10637       // that could exploit it.
10638       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10639         return true;
10640       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10641         return false;
10642     } else if (R->Viable)
10643       return false;
10644 
10645     assert(L->Viable == R->Viable);
10646 
10647     // Criteria by which we can sort non-viable candidates:
10648     if (!L->Viable) {
10649       // 1. Arity mismatches come after other candidates.
10650       if (L->FailureKind == ovl_fail_too_many_arguments ||
10651           L->FailureKind == ovl_fail_too_few_arguments) {
10652         if (R->FailureKind == ovl_fail_too_many_arguments ||
10653             R->FailureKind == ovl_fail_too_few_arguments) {
10654           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10655           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10656           if (LDist == RDist) {
10657             if (L->FailureKind == R->FailureKind)
10658               // Sort non-surrogates before surrogates.
10659               return !L->IsSurrogate && R->IsSurrogate;
10660             // Sort candidates requiring fewer parameters than there were
10661             // arguments given after candidates requiring more parameters
10662             // than there were arguments given.
10663             return L->FailureKind == ovl_fail_too_many_arguments;
10664           }
10665           return LDist < RDist;
10666         }
10667         return false;
10668       }
10669       if (R->FailureKind == ovl_fail_too_many_arguments ||
10670           R->FailureKind == ovl_fail_too_few_arguments)
10671         return true;
10672 
10673       // 2. Bad conversions come first and are ordered by the number
10674       // of bad conversions and quality of good conversions.
10675       if (L->FailureKind == ovl_fail_bad_conversion) {
10676         if (R->FailureKind != ovl_fail_bad_conversion)
10677           return true;
10678 
10679         // The conversion that can be fixed with a smaller number of changes,
10680         // comes first.
10681         unsigned numLFixes = L->Fix.NumConversionsFixed;
10682         unsigned numRFixes = R->Fix.NumConversionsFixed;
10683         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10684         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10685         if (numLFixes != numRFixes) {
10686           return numLFixes < numRFixes;
10687         }
10688 
10689         // If there's any ordering between the defined conversions...
10690         // FIXME: this might not be transitive.
10691         assert(L->Conversions.size() == R->Conversions.size());
10692 
10693         int leftBetter = 0;
10694         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10695         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10696           switch (CompareImplicitConversionSequences(S, Loc,
10697                                                      L->Conversions[I],
10698                                                      R->Conversions[I])) {
10699           case ImplicitConversionSequence::Better:
10700             leftBetter++;
10701             break;
10702 
10703           case ImplicitConversionSequence::Worse:
10704             leftBetter--;
10705             break;
10706 
10707           case ImplicitConversionSequence::Indistinguishable:
10708             break;
10709           }
10710         }
10711         if (leftBetter > 0) return true;
10712         if (leftBetter < 0) return false;
10713 
10714       } else if (R->FailureKind == ovl_fail_bad_conversion)
10715         return false;
10716 
10717       if (L->FailureKind == ovl_fail_bad_deduction) {
10718         if (R->FailureKind != ovl_fail_bad_deduction)
10719           return true;
10720 
10721         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10722           return RankDeductionFailure(L->DeductionFailure)
10723                < RankDeductionFailure(R->DeductionFailure);
10724       } else if (R->FailureKind == ovl_fail_bad_deduction)
10725         return false;
10726 
10727       // TODO: others?
10728     }
10729 
10730     // Sort everything else by location.
10731     SourceLocation LLoc = GetLocationForCandidate(L);
10732     SourceLocation RLoc = GetLocationForCandidate(R);
10733 
10734     // Put candidates without locations (e.g. builtins) at the end.
10735     if (LLoc.isInvalid()) return false;
10736     if (RLoc.isInvalid()) return true;
10737 
10738     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10739   }
10740 };
10741 }
10742 
10743 /// CompleteNonViableCandidate - Normally, overload resolution only
10744 /// computes up to the first bad conversion. Produces the FixIt set if
10745 /// possible.
10746 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10747                                        ArrayRef<Expr *> Args) {
10748   assert(!Cand->Viable);
10749 
10750   // Don't do anything on failures other than bad conversion.
10751   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10752 
10753   // We only want the FixIts if all the arguments can be corrected.
10754   bool Unfixable = false;
10755   // Use a implicit copy initialization to check conversion fixes.
10756   Cand->Fix.setConversionChecker(TryCopyInitialization);
10757 
10758   // Attempt to fix the bad conversion.
10759   unsigned ConvCount = Cand->Conversions.size();
10760   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10761        ++ConvIdx) {
10762     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10763     if (Cand->Conversions[ConvIdx].isInitialized() &&
10764         Cand->Conversions[ConvIdx].isBad()) {
10765       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10766       break;
10767     }
10768   }
10769 
10770   // FIXME: this should probably be preserved from the overload
10771   // operation somehow.
10772   bool SuppressUserConversions = false;
10773 
10774   unsigned ConvIdx = 0;
10775   ArrayRef<QualType> ParamTypes;
10776 
10777   if (Cand->IsSurrogate) {
10778     QualType ConvType
10779       = Cand->Surrogate->getConversionType().getNonReferenceType();
10780     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10781       ConvType = ConvPtrType->getPointeeType();
10782     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10783     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10784     ConvIdx = 1;
10785   } else if (Cand->Function) {
10786     ParamTypes =
10787         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10788     if (isa<CXXMethodDecl>(Cand->Function) &&
10789         !isa<CXXConstructorDecl>(Cand->Function)) {
10790       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10791       ConvIdx = 1;
10792     }
10793   } else {
10794     // Builtin operator.
10795     assert(ConvCount <= 3);
10796     ParamTypes = Cand->BuiltinParamTypes;
10797   }
10798 
10799   // Fill in the rest of the conversions.
10800   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10801     if (Cand->Conversions[ConvIdx].isInitialized()) {
10802       // We've already checked this conversion.
10803     } else if (ArgIdx < ParamTypes.size()) {
10804       if (ParamTypes[ArgIdx]->isDependentType())
10805         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10806             Args[ArgIdx]->getType());
10807       else {
10808         Cand->Conversions[ConvIdx] =
10809             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10810                                   SuppressUserConversions,
10811                                   /*InOverloadResolution=*/true,
10812                                   /*AllowObjCWritebackConversion=*/
10813                                   S.getLangOpts().ObjCAutoRefCount);
10814         // Store the FixIt in the candidate if it exists.
10815         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10816           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10817       }
10818     } else
10819       Cand->Conversions[ConvIdx].setEllipsis();
10820   }
10821 }
10822 
10823 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
10824     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10825     SourceLocation OpLoc,
10826     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10827   // Sort the candidates by viability and position.  Sorting directly would
10828   // be prohibitive, so we make a set of pointers and sort those.
10829   SmallVector<OverloadCandidate*, 32> Cands;
10830   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10831   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10832     if (!Filter(*Cand))
10833       continue;
10834     if (Cand->Viable)
10835       Cands.push_back(Cand);
10836     else if (OCD == OCD_AllCandidates) {
10837       CompleteNonViableCandidate(S, Cand, Args);
10838       if (Cand->Function || Cand->IsSurrogate)
10839         Cands.push_back(Cand);
10840       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10841       // want to list every possible builtin candidate.
10842     }
10843   }
10844 
10845   llvm::stable_sort(
10846       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10847 
10848   return Cands;
10849 }
10850 
10851 /// When overload resolution fails, prints diagnostic messages containing the
10852 /// candidates in the candidate set.
10853 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
10854     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10855     StringRef Opc, SourceLocation OpLoc,
10856     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10857 
10858   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
10859 
10860   S.Diag(PD.first, PD.second);
10861 
10862   NoteCandidates(S, Args, Cands, Opc, OpLoc);
10863 }
10864 
10865 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
10866                                           ArrayRef<OverloadCandidate *> Cands,
10867                                           StringRef Opc, SourceLocation OpLoc) {
10868   bool ReportedAmbiguousConversions = false;
10869 
10870   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10871   unsigned CandsShown = 0;
10872   auto I = Cands.begin(), E = Cands.end();
10873   for (; I != E; ++I) {
10874     OverloadCandidate *Cand = *I;
10875 
10876     // Set an arbitrary limit on the number of candidate functions we'll spam
10877     // the user with.  FIXME: This limit should depend on details of the
10878     // candidate list.
10879     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10880       break;
10881     }
10882     ++CandsShown;
10883 
10884     if (Cand->Function)
10885       NoteFunctionCandidate(S, Cand, Args.size(),
10886                             /*TakingCandidateAddress=*/false, DestAS);
10887     else if (Cand->IsSurrogate)
10888       NoteSurrogateCandidate(S, Cand);
10889     else {
10890       assert(Cand->Viable &&
10891              "Non-viable built-in candidates are not added to Cands.");
10892       // Generally we only see ambiguities including viable builtin
10893       // operators if overload resolution got screwed up by an
10894       // ambiguous user-defined conversion.
10895       //
10896       // FIXME: It's quite possible for different conversions to see
10897       // different ambiguities, though.
10898       if (!ReportedAmbiguousConversions) {
10899         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10900         ReportedAmbiguousConversions = true;
10901       }
10902 
10903       // If this is a viable builtin, print it.
10904       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10905     }
10906   }
10907 
10908   if (I != E)
10909     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10910 }
10911 
10912 static SourceLocation
10913 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10914   return Cand->Specialization ? Cand->Specialization->getLocation()
10915                               : SourceLocation();
10916 }
10917 
10918 namespace {
10919 struct CompareTemplateSpecCandidatesForDisplay {
10920   Sema &S;
10921   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10922 
10923   bool operator()(const TemplateSpecCandidate *L,
10924                   const TemplateSpecCandidate *R) {
10925     // Fast-path this check.
10926     if (L == R)
10927       return false;
10928 
10929     // Assuming that both candidates are not matches...
10930 
10931     // Sort by the ranking of deduction failures.
10932     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10933       return RankDeductionFailure(L->DeductionFailure) <
10934              RankDeductionFailure(R->DeductionFailure);
10935 
10936     // Sort everything else by location.
10937     SourceLocation LLoc = GetLocationForCandidate(L);
10938     SourceLocation RLoc = GetLocationForCandidate(R);
10939 
10940     // Put candidates without locations (e.g. builtins) at the end.
10941     if (LLoc.isInvalid())
10942       return false;
10943     if (RLoc.isInvalid())
10944       return true;
10945 
10946     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10947   }
10948 };
10949 }
10950 
10951 /// Diagnose a template argument deduction failure.
10952 /// We are treating these failures as overload failures due to bad
10953 /// deductions.
10954 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10955                                                  bool ForTakingAddress) {
10956   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10957                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10958 }
10959 
10960 void TemplateSpecCandidateSet::destroyCandidates() {
10961   for (iterator i = begin(), e = end(); i != e; ++i) {
10962     i->DeductionFailure.Destroy();
10963   }
10964 }
10965 
10966 void TemplateSpecCandidateSet::clear() {
10967   destroyCandidates();
10968   Candidates.clear();
10969 }
10970 
10971 /// NoteCandidates - When no template specialization match is found, prints
10972 /// diagnostic messages containing the non-matching specializations that form
10973 /// the candidate set.
10974 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10975 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10976 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10977   // Sort the candidates by position (assuming no candidate is a match).
10978   // Sorting directly would be prohibitive, so we make a set of pointers
10979   // and sort those.
10980   SmallVector<TemplateSpecCandidate *, 32> Cands;
10981   Cands.reserve(size());
10982   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10983     if (Cand->Specialization)
10984       Cands.push_back(Cand);
10985     // Otherwise, this is a non-matching builtin candidate.  We do not,
10986     // in general, want to list every possible builtin candidate.
10987   }
10988 
10989   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
10990 
10991   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10992   // for generalization purposes (?).
10993   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10994 
10995   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10996   unsigned CandsShown = 0;
10997   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10998     TemplateSpecCandidate *Cand = *I;
10999 
11000     // Set an arbitrary limit on the number of candidates we'll spam
11001     // the user with.  FIXME: This limit should depend on details of the
11002     // candidate list.
11003     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11004       break;
11005     ++CandsShown;
11006 
11007     assert(Cand->Specialization &&
11008            "Non-matching built-in candidates are not added to Cands.");
11009     Cand->NoteDeductionFailure(S, ForTakingAddress);
11010   }
11011 
11012   if (I != E)
11013     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11014 }
11015 
11016 // [PossiblyAFunctionType]  -->   [Return]
11017 // NonFunctionType --> NonFunctionType
11018 // R (A) --> R(A)
11019 // R (*)(A) --> R (A)
11020 // R (&)(A) --> R (A)
11021 // R (S::*)(A) --> R (A)
11022 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11023   QualType Ret = PossiblyAFunctionType;
11024   if (const PointerType *ToTypePtr =
11025     PossiblyAFunctionType->getAs<PointerType>())
11026     Ret = ToTypePtr->getPointeeType();
11027   else if (const ReferenceType *ToTypeRef =
11028     PossiblyAFunctionType->getAs<ReferenceType>())
11029     Ret = ToTypeRef->getPointeeType();
11030   else if (const MemberPointerType *MemTypePtr =
11031     PossiblyAFunctionType->getAs<MemberPointerType>())
11032     Ret = MemTypePtr->getPointeeType();
11033   Ret =
11034     Context.getCanonicalType(Ret).getUnqualifiedType();
11035   return Ret;
11036 }
11037 
11038 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11039                                  bool Complain = true) {
11040   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11041       S.DeduceReturnType(FD, Loc, Complain))
11042     return true;
11043 
11044   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11045   if (S.getLangOpts().CPlusPlus17 &&
11046       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11047       !S.ResolveExceptionSpec(Loc, FPT))
11048     return true;
11049 
11050   return false;
11051 }
11052 
11053 namespace {
11054 // A helper class to help with address of function resolution
11055 // - allows us to avoid passing around all those ugly parameters
11056 class AddressOfFunctionResolver {
11057   Sema& S;
11058   Expr* SourceExpr;
11059   const QualType& TargetType;
11060   QualType TargetFunctionType; // Extracted function type from target type
11061 
11062   bool Complain;
11063   //DeclAccessPair& ResultFunctionAccessPair;
11064   ASTContext& Context;
11065 
11066   bool TargetTypeIsNonStaticMemberFunction;
11067   bool FoundNonTemplateFunction;
11068   bool StaticMemberFunctionFromBoundPointer;
11069   bool HasComplained;
11070 
11071   OverloadExpr::FindResult OvlExprInfo;
11072   OverloadExpr *OvlExpr;
11073   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11074   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11075   TemplateSpecCandidateSet FailedCandidates;
11076 
11077 public:
11078   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11079                             const QualType &TargetType, bool Complain)
11080       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11081         Complain(Complain), Context(S.getASTContext()),
11082         TargetTypeIsNonStaticMemberFunction(
11083             !!TargetType->getAs<MemberPointerType>()),
11084         FoundNonTemplateFunction(false),
11085         StaticMemberFunctionFromBoundPointer(false),
11086         HasComplained(false),
11087         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11088         OvlExpr(OvlExprInfo.Expression),
11089         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11090     ExtractUnqualifiedFunctionTypeFromTargetType();
11091 
11092     if (TargetFunctionType->isFunctionType()) {
11093       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11094         if (!UME->isImplicitAccess() &&
11095             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11096           StaticMemberFunctionFromBoundPointer = true;
11097     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11098       DeclAccessPair dap;
11099       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11100               OvlExpr, false, &dap)) {
11101         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11102           if (!Method->isStatic()) {
11103             // If the target type is a non-function type and the function found
11104             // is a non-static member function, pretend as if that was the
11105             // target, it's the only possible type to end up with.
11106             TargetTypeIsNonStaticMemberFunction = true;
11107 
11108             // And skip adding the function if its not in the proper form.
11109             // We'll diagnose this due to an empty set of functions.
11110             if (!OvlExprInfo.HasFormOfMemberPointer)
11111               return;
11112           }
11113 
11114         Matches.push_back(std::make_pair(dap, Fn));
11115       }
11116       return;
11117     }
11118 
11119     if (OvlExpr->hasExplicitTemplateArgs())
11120       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11121 
11122     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11123       // C++ [over.over]p4:
11124       //   If more than one function is selected, [...]
11125       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11126         if (FoundNonTemplateFunction)
11127           EliminateAllTemplateMatches();
11128         else
11129           EliminateAllExceptMostSpecializedTemplate();
11130       }
11131     }
11132 
11133     if (S.getLangOpts().CUDA && Matches.size() > 1)
11134       EliminateSuboptimalCudaMatches();
11135   }
11136 
11137   bool hasComplained() const { return HasComplained; }
11138 
11139 private:
11140   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11141     QualType Discard;
11142     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11143            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11144   }
11145 
11146   /// \return true if A is considered a better overload candidate for the
11147   /// desired type than B.
11148   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11149     // If A doesn't have exactly the correct type, we don't want to classify it
11150     // as "better" than anything else. This way, the user is required to
11151     // disambiguate for us if there are multiple candidates and no exact match.
11152     return candidateHasExactlyCorrectType(A) &&
11153            (!candidateHasExactlyCorrectType(B) ||
11154             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11155   }
11156 
11157   /// \return true if we were able to eliminate all but one overload candidate,
11158   /// false otherwise.
11159   bool eliminiateSuboptimalOverloadCandidates() {
11160     // Same algorithm as overload resolution -- one pass to pick the "best",
11161     // another pass to be sure that nothing is better than the best.
11162     auto Best = Matches.begin();
11163     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11164       if (isBetterCandidate(I->second, Best->second))
11165         Best = I;
11166 
11167     const FunctionDecl *BestFn = Best->second;
11168     auto IsBestOrInferiorToBest = [this, BestFn](
11169         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11170       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11171     };
11172 
11173     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11174     // option, so we can potentially give the user a better error
11175     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11176       return false;
11177     Matches[0] = *Best;
11178     Matches.resize(1);
11179     return true;
11180   }
11181 
11182   bool isTargetTypeAFunction() const {
11183     return TargetFunctionType->isFunctionType();
11184   }
11185 
11186   // [ToType]     [Return]
11187 
11188   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11189   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11190   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11191   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11192     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11193   }
11194 
11195   // return true if any matching specializations were found
11196   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11197                                    const DeclAccessPair& CurAccessFunPair) {
11198     if (CXXMethodDecl *Method
11199               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11200       // Skip non-static function templates when converting to pointer, and
11201       // static when converting to member pointer.
11202       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11203         return false;
11204     }
11205     else if (TargetTypeIsNonStaticMemberFunction)
11206       return false;
11207 
11208     // C++ [over.over]p2:
11209     //   If the name is a function template, template argument deduction is
11210     //   done (14.8.2.2), and if the argument deduction succeeds, the
11211     //   resulting template argument list is used to generate a single
11212     //   function template specialization, which is added to the set of
11213     //   overloaded functions considered.
11214     FunctionDecl *Specialization = nullptr;
11215     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11216     if (Sema::TemplateDeductionResult Result
11217           = S.DeduceTemplateArguments(FunctionTemplate,
11218                                       &OvlExplicitTemplateArgs,
11219                                       TargetFunctionType, Specialization,
11220                                       Info, /*IsAddressOfFunction*/true)) {
11221       // Make a note of the failed deduction for diagnostics.
11222       FailedCandidates.addCandidate()
11223           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11224                MakeDeductionFailureInfo(Context, Result, Info));
11225       return false;
11226     }
11227 
11228     // Template argument deduction ensures that we have an exact match or
11229     // compatible pointer-to-function arguments that would be adjusted by ICS.
11230     // This function template specicalization works.
11231     assert(S.isSameOrCompatibleFunctionType(
11232               Context.getCanonicalType(Specialization->getType()),
11233               Context.getCanonicalType(TargetFunctionType)));
11234 
11235     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11236       return false;
11237 
11238     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11239     return true;
11240   }
11241 
11242   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11243                                       const DeclAccessPair& CurAccessFunPair) {
11244     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11245       // Skip non-static functions when converting to pointer, and static
11246       // when converting to member pointer.
11247       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11248         return false;
11249     }
11250     else if (TargetTypeIsNonStaticMemberFunction)
11251       return false;
11252 
11253     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11254       if (S.getLangOpts().CUDA)
11255         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11256           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11257             return false;
11258       if (FunDecl->isMultiVersion()) {
11259         const auto *TA = FunDecl->getAttr<TargetAttr>();
11260         if (TA && !TA->isDefaultVersion())
11261           return false;
11262       }
11263 
11264       // If any candidate has a placeholder return type, trigger its deduction
11265       // now.
11266       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11267                                Complain)) {
11268         HasComplained |= Complain;
11269         return false;
11270       }
11271 
11272       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11273         return false;
11274 
11275       // If we're in C, we need to support types that aren't exactly identical.
11276       if (!S.getLangOpts().CPlusPlus ||
11277           candidateHasExactlyCorrectType(FunDecl)) {
11278         Matches.push_back(std::make_pair(
11279             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11280         FoundNonTemplateFunction = true;
11281         return true;
11282       }
11283     }
11284 
11285     return false;
11286   }
11287 
11288   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11289     bool Ret = false;
11290 
11291     // If the overload expression doesn't have the form of a pointer to
11292     // member, don't try to convert it to a pointer-to-member type.
11293     if (IsInvalidFormOfPointerToMemberFunction())
11294       return false;
11295 
11296     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11297                                E = OvlExpr->decls_end();
11298          I != E; ++I) {
11299       // Look through any using declarations to find the underlying function.
11300       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11301 
11302       // C++ [over.over]p3:
11303       //   Non-member functions and static member functions match
11304       //   targets of type "pointer-to-function" or "reference-to-function."
11305       //   Nonstatic member functions match targets of
11306       //   type "pointer-to-member-function."
11307       // Note that according to DR 247, the containing class does not matter.
11308       if (FunctionTemplateDecl *FunctionTemplate
11309                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11310         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11311           Ret = true;
11312       }
11313       // If we have explicit template arguments supplied, skip non-templates.
11314       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11315                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11316         Ret = true;
11317     }
11318     assert(Ret || Matches.empty());
11319     return Ret;
11320   }
11321 
11322   void EliminateAllExceptMostSpecializedTemplate() {
11323     //   [...] and any given function template specialization F1 is
11324     //   eliminated if the set contains a second function template
11325     //   specialization whose function template is more specialized
11326     //   than the function template of F1 according to the partial
11327     //   ordering rules of 14.5.5.2.
11328 
11329     // The algorithm specified above is quadratic. We instead use a
11330     // two-pass algorithm (similar to the one used to identify the
11331     // best viable function in an overload set) that identifies the
11332     // best function template (if it exists).
11333 
11334     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11335     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11336       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11337 
11338     // TODO: It looks like FailedCandidates does not serve much purpose
11339     // here, since the no_viable diagnostic has index 0.
11340     UnresolvedSetIterator Result = S.getMostSpecialized(
11341         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11342         SourceExpr->getBeginLoc(), S.PDiag(),
11343         S.PDiag(diag::err_addr_ovl_ambiguous)
11344             << Matches[0].second->getDeclName(),
11345         S.PDiag(diag::note_ovl_candidate)
11346             << (unsigned)oc_function << (unsigned)ocs_described_template,
11347         Complain, TargetFunctionType);
11348 
11349     if (Result != MatchesCopy.end()) {
11350       // Make it the first and only element
11351       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11352       Matches[0].second = cast<FunctionDecl>(*Result);
11353       Matches.resize(1);
11354     } else
11355       HasComplained |= Complain;
11356   }
11357 
11358   void EliminateAllTemplateMatches() {
11359     //   [...] any function template specializations in the set are
11360     //   eliminated if the set also contains a non-template function, [...]
11361     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11362       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11363         ++I;
11364       else {
11365         Matches[I] = Matches[--N];
11366         Matches.resize(N);
11367       }
11368     }
11369   }
11370 
11371   void EliminateSuboptimalCudaMatches() {
11372     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11373   }
11374 
11375 public:
11376   void ComplainNoMatchesFound() const {
11377     assert(Matches.empty());
11378     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11379         << OvlExpr->getName() << TargetFunctionType
11380         << OvlExpr->getSourceRange();
11381     if (FailedCandidates.empty())
11382       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11383                                   /*TakingAddress=*/true);
11384     else {
11385       // We have some deduction failure messages. Use them to diagnose
11386       // the function templates, and diagnose the non-template candidates
11387       // normally.
11388       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11389                                  IEnd = OvlExpr->decls_end();
11390            I != IEnd; ++I)
11391         if (FunctionDecl *Fun =
11392                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11393           if (!functionHasPassObjectSizeParams(Fun))
11394             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11395                                     /*TakingAddress=*/true);
11396       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11397     }
11398   }
11399 
11400   bool IsInvalidFormOfPointerToMemberFunction() const {
11401     return TargetTypeIsNonStaticMemberFunction &&
11402       !OvlExprInfo.HasFormOfMemberPointer;
11403   }
11404 
11405   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11406       // TODO: Should we condition this on whether any functions might
11407       // have matched, or is it more appropriate to do that in callers?
11408       // TODO: a fixit wouldn't hurt.
11409       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11410         << TargetType << OvlExpr->getSourceRange();
11411   }
11412 
11413   bool IsStaticMemberFunctionFromBoundPointer() const {
11414     return StaticMemberFunctionFromBoundPointer;
11415   }
11416 
11417   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11418     S.Diag(OvlExpr->getBeginLoc(),
11419            diag::err_invalid_form_pointer_member_function)
11420         << OvlExpr->getSourceRange();
11421   }
11422 
11423   void ComplainOfInvalidConversion() const {
11424     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11425         << OvlExpr->getName() << TargetType;
11426   }
11427 
11428   void ComplainMultipleMatchesFound() const {
11429     assert(Matches.size() > 1);
11430     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11431         << OvlExpr->getName() << OvlExpr->getSourceRange();
11432     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11433                                 /*TakingAddress=*/true);
11434   }
11435 
11436   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11437 
11438   int getNumMatches() const { return Matches.size(); }
11439 
11440   FunctionDecl* getMatchingFunctionDecl() const {
11441     if (Matches.size() != 1) return nullptr;
11442     return Matches[0].second;
11443   }
11444 
11445   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11446     if (Matches.size() != 1) return nullptr;
11447     return &Matches[0].first;
11448   }
11449 };
11450 }
11451 
11452 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11453 /// an overloaded function (C++ [over.over]), where @p From is an
11454 /// expression with overloaded function type and @p ToType is the type
11455 /// we're trying to resolve to. For example:
11456 ///
11457 /// @code
11458 /// int f(double);
11459 /// int f(int);
11460 ///
11461 /// int (*pfd)(double) = f; // selects f(double)
11462 /// @endcode
11463 ///
11464 /// This routine returns the resulting FunctionDecl if it could be
11465 /// resolved, and NULL otherwise. When @p Complain is true, this
11466 /// routine will emit diagnostics if there is an error.
11467 FunctionDecl *
11468 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11469                                          QualType TargetType,
11470                                          bool Complain,
11471                                          DeclAccessPair &FoundResult,
11472                                          bool *pHadMultipleCandidates) {
11473   assert(AddressOfExpr->getType() == Context.OverloadTy);
11474 
11475   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11476                                      Complain);
11477   int NumMatches = Resolver.getNumMatches();
11478   FunctionDecl *Fn = nullptr;
11479   bool ShouldComplain = Complain && !Resolver.hasComplained();
11480   if (NumMatches == 0 && ShouldComplain) {
11481     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11482       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11483     else
11484       Resolver.ComplainNoMatchesFound();
11485   }
11486   else if (NumMatches > 1 && ShouldComplain)
11487     Resolver.ComplainMultipleMatchesFound();
11488   else if (NumMatches == 1) {
11489     Fn = Resolver.getMatchingFunctionDecl();
11490     assert(Fn);
11491     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11492       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11493     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11494     if (Complain) {
11495       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11496         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11497       else
11498         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11499     }
11500   }
11501 
11502   if (pHadMultipleCandidates)
11503     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11504   return Fn;
11505 }
11506 
11507 /// Given an expression that refers to an overloaded function, try to
11508 /// resolve that function to a single function that can have its address taken.
11509 /// This will modify `Pair` iff it returns non-null.
11510 ///
11511 /// This routine can only realistically succeed if all but one candidates in the
11512 /// overload set for SrcExpr cannot have their addresses taken.
11513 FunctionDecl *
11514 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11515                                                   DeclAccessPair &Pair) {
11516   OverloadExpr::FindResult R = OverloadExpr::find(E);
11517   OverloadExpr *Ovl = R.Expression;
11518   FunctionDecl *Result = nullptr;
11519   DeclAccessPair DAP;
11520   // Don't use the AddressOfResolver because we're specifically looking for
11521   // cases where we have one overload candidate that lacks
11522   // enable_if/pass_object_size/...
11523   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11524     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11525     if (!FD)
11526       return nullptr;
11527 
11528     if (!checkAddressOfFunctionIsAvailable(FD))
11529       continue;
11530 
11531     // We have more than one result; quit.
11532     if (Result)
11533       return nullptr;
11534     DAP = I.getPair();
11535     Result = FD;
11536   }
11537 
11538   if (Result)
11539     Pair = DAP;
11540   return Result;
11541 }
11542 
11543 /// Given an overloaded function, tries to turn it into a non-overloaded
11544 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11545 /// will perform access checks, diagnose the use of the resultant decl, and, if
11546 /// requested, potentially perform a function-to-pointer decay.
11547 ///
11548 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11549 /// Otherwise, returns true. This may emit diagnostics and return true.
11550 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11551     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11552   Expr *E = SrcExpr.get();
11553   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11554 
11555   DeclAccessPair DAP;
11556   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11557   if (!Found || Found->isCPUDispatchMultiVersion() ||
11558       Found->isCPUSpecificMultiVersion())
11559     return false;
11560 
11561   // Emitting multiple diagnostics for a function that is both inaccessible and
11562   // unavailable is consistent with our behavior elsewhere. So, always check
11563   // for both.
11564   DiagnoseUseOfDecl(Found, E->getExprLoc());
11565   CheckAddressOfMemberAccess(E, DAP);
11566   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11567   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11568     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11569   else
11570     SrcExpr = Fixed;
11571   return true;
11572 }
11573 
11574 /// Given an expression that refers to an overloaded function, try to
11575 /// resolve that overloaded function expression down to a single function.
11576 ///
11577 /// This routine can only resolve template-ids that refer to a single function
11578 /// template, where that template-id refers to a single template whose template
11579 /// arguments are either provided by the template-id or have defaults,
11580 /// as described in C++0x [temp.arg.explicit]p3.
11581 ///
11582 /// If no template-ids are found, no diagnostics are emitted and NULL is
11583 /// returned.
11584 FunctionDecl *
11585 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11586                                                   bool Complain,
11587                                                   DeclAccessPair *FoundResult) {
11588   // C++ [over.over]p1:
11589   //   [...] [Note: any redundant set of parentheses surrounding the
11590   //   overloaded function name is ignored (5.1). ]
11591   // C++ [over.over]p1:
11592   //   [...] The overloaded function name can be preceded by the &
11593   //   operator.
11594 
11595   // If we didn't actually find any template-ids, we're done.
11596   if (!ovl->hasExplicitTemplateArgs())
11597     return nullptr;
11598 
11599   TemplateArgumentListInfo ExplicitTemplateArgs;
11600   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11601   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11602 
11603   // Look through all of the overloaded functions, searching for one
11604   // whose type matches exactly.
11605   FunctionDecl *Matched = nullptr;
11606   for (UnresolvedSetIterator I = ovl->decls_begin(),
11607          E = ovl->decls_end(); I != E; ++I) {
11608     // C++0x [temp.arg.explicit]p3:
11609     //   [...] In contexts where deduction is done and fails, or in contexts
11610     //   where deduction is not done, if a template argument list is
11611     //   specified and it, along with any default template arguments,
11612     //   identifies a single function template specialization, then the
11613     //   template-id is an lvalue for the function template specialization.
11614     FunctionTemplateDecl *FunctionTemplate
11615       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11616 
11617     // C++ [over.over]p2:
11618     //   If the name is a function template, template argument deduction is
11619     //   done (14.8.2.2), and if the argument deduction succeeds, the
11620     //   resulting template argument list is used to generate a single
11621     //   function template specialization, which is added to the set of
11622     //   overloaded functions considered.
11623     FunctionDecl *Specialization = nullptr;
11624     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11625     if (TemplateDeductionResult Result
11626           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11627                                     Specialization, Info,
11628                                     /*IsAddressOfFunction*/true)) {
11629       // Make a note of the failed deduction for diagnostics.
11630       // TODO: Actually use the failed-deduction info?
11631       FailedCandidates.addCandidate()
11632           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11633                MakeDeductionFailureInfo(Context, Result, Info));
11634       continue;
11635     }
11636 
11637     assert(Specialization && "no specialization and no error?");
11638 
11639     // Multiple matches; we can't resolve to a single declaration.
11640     if (Matched) {
11641       if (Complain) {
11642         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11643           << ovl->getName();
11644         NoteAllOverloadCandidates(ovl);
11645       }
11646       return nullptr;
11647     }
11648 
11649     Matched = Specialization;
11650     if (FoundResult) *FoundResult = I.getPair();
11651   }
11652 
11653   if (Matched &&
11654       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11655     return nullptr;
11656 
11657   return Matched;
11658 }
11659 
11660 // Resolve and fix an overloaded expression that can be resolved
11661 // because it identifies a single function template specialization.
11662 //
11663 // Last three arguments should only be supplied if Complain = true
11664 //
11665 // Return true if it was logically possible to so resolve the
11666 // expression, regardless of whether or not it succeeded.  Always
11667 // returns true if 'complain' is set.
11668 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11669                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11670                       bool complain, SourceRange OpRangeForComplaining,
11671                                            QualType DestTypeForComplaining,
11672                                             unsigned DiagIDForComplaining) {
11673   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11674 
11675   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11676 
11677   DeclAccessPair found;
11678   ExprResult SingleFunctionExpression;
11679   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11680                            ovl.Expression, /*complain*/ false, &found)) {
11681     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11682       SrcExpr = ExprError();
11683       return true;
11684     }
11685 
11686     // It is only correct to resolve to an instance method if we're
11687     // resolving a form that's permitted to be a pointer to member.
11688     // Otherwise we'll end up making a bound member expression, which
11689     // is illegal in all the contexts we resolve like this.
11690     if (!ovl.HasFormOfMemberPointer &&
11691         isa<CXXMethodDecl>(fn) &&
11692         cast<CXXMethodDecl>(fn)->isInstance()) {
11693       if (!complain) return false;
11694 
11695       Diag(ovl.Expression->getExprLoc(),
11696            diag::err_bound_member_function)
11697         << 0 << ovl.Expression->getSourceRange();
11698 
11699       // TODO: I believe we only end up here if there's a mix of
11700       // static and non-static candidates (otherwise the expression
11701       // would have 'bound member' type, not 'overload' type).
11702       // Ideally we would note which candidate was chosen and why
11703       // the static candidates were rejected.
11704       SrcExpr = ExprError();
11705       return true;
11706     }
11707 
11708     // Fix the expression to refer to 'fn'.
11709     SingleFunctionExpression =
11710         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11711 
11712     // If desired, do function-to-pointer decay.
11713     if (doFunctionPointerConverion) {
11714       SingleFunctionExpression =
11715         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11716       if (SingleFunctionExpression.isInvalid()) {
11717         SrcExpr = ExprError();
11718         return true;
11719       }
11720     }
11721   }
11722 
11723   if (!SingleFunctionExpression.isUsable()) {
11724     if (complain) {
11725       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11726         << ovl.Expression->getName()
11727         << DestTypeForComplaining
11728         << OpRangeForComplaining
11729         << ovl.Expression->getQualifierLoc().getSourceRange();
11730       NoteAllOverloadCandidates(SrcExpr.get());
11731 
11732       SrcExpr = ExprError();
11733       return true;
11734     }
11735 
11736     return false;
11737   }
11738 
11739   SrcExpr = SingleFunctionExpression;
11740   return true;
11741 }
11742 
11743 /// Add a single candidate to the overload set.
11744 static void AddOverloadedCallCandidate(Sema &S,
11745                                        DeclAccessPair FoundDecl,
11746                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11747                                        ArrayRef<Expr *> Args,
11748                                        OverloadCandidateSet &CandidateSet,
11749                                        bool PartialOverloading,
11750                                        bool KnownValid) {
11751   NamedDecl *Callee = FoundDecl.getDecl();
11752   if (isa<UsingShadowDecl>(Callee))
11753     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11754 
11755   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11756     if (ExplicitTemplateArgs) {
11757       assert(!KnownValid && "Explicit template arguments?");
11758       return;
11759     }
11760     // Prevent ill-formed function decls to be added as overload candidates.
11761     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11762       return;
11763 
11764     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11765                            /*SuppressUserConversions=*/false,
11766                            PartialOverloading);
11767     return;
11768   }
11769 
11770   if (FunctionTemplateDecl *FuncTemplate
11771       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11772     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11773                                    ExplicitTemplateArgs, Args, CandidateSet,
11774                                    /*SuppressUserConversions=*/false,
11775                                    PartialOverloading);
11776     return;
11777   }
11778 
11779   assert(!KnownValid && "unhandled case in overloaded call candidate");
11780 }
11781 
11782 /// Add the overload candidates named by callee and/or found by argument
11783 /// dependent lookup to the given overload set.
11784 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11785                                        ArrayRef<Expr *> Args,
11786                                        OverloadCandidateSet &CandidateSet,
11787                                        bool PartialOverloading) {
11788 
11789 #ifndef NDEBUG
11790   // Verify that ArgumentDependentLookup is consistent with the rules
11791   // in C++0x [basic.lookup.argdep]p3:
11792   //
11793   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11794   //   and let Y be the lookup set produced by argument dependent
11795   //   lookup (defined as follows). If X contains
11796   //
11797   //     -- a declaration of a class member, or
11798   //
11799   //     -- a block-scope function declaration that is not a
11800   //        using-declaration, or
11801   //
11802   //     -- a declaration that is neither a function or a function
11803   //        template
11804   //
11805   //   then Y is empty.
11806 
11807   if (ULE->requiresADL()) {
11808     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11809            E = ULE->decls_end(); I != E; ++I) {
11810       assert(!(*I)->getDeclContext()->isRecord());
11811       assert(isa<UsingShadowDecl>(*I) ||
11812              !(*I)->getDeclContext()->isFunctionOrMethod());
11813       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11814     }
11815   }
11816 #endif
11817 
11818   // It would be nice to avoid this copy.
11819   TemplateArgumentListInfo TABuffer;
11820   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11821   if (ULE->hasExplicitTemplateArgs()) {
11822     ULE->copyTemplateArgumentsInto(TABuffer);
11823     ExplicitTemplateArgs = &TABuffer;
11824   }
11825 
11826   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11827          E = ULE->decls_end(); I != E; ++I)
11828     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11829                                CandidateSet, PartialOverloading,
11830                                /*KnownValid*/ true);
11831 
11832   if (ULE->requiresADL())
11833     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11834                                          Args, ExplicitTemplateArgs,
11835                                          CandidateSet, PartialOverloading);
11836 }
11837 
11838 /// Determine whether a declaration with the specified name could be moved into
11839 /// a different namespace.
11840 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11841   switch (Name.getCXXOverloadedOperator()) {
11842   case OO_New: case OO_Array_New:
11843   case OO_Delete: case OO_Array_Delete:
11844     return false;
11845 
11846   default:
11847     return true;
11848   }
11849 }
11850 
11851 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11852 /// template, where the non-dependent name was declared after the template
11853 /// was defined. This is common in code written for a compilers which do not
11854 /// correctly implement two-stage name lookup.
11855 ///
11856 /// Returns true if a viable candidate was found and a diagnostic was issued.
11857 static bool
11858 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11859                        const CXXScopeSpec &SS, LookupResult &R,
11860                        OverloadCandidateSet::CandidateSetKind CSK,
11861                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11862                        ArrayRef<Expr *> Args,
11863                        bool *DoDiagnoseEmptyLookup = nullptr) {
11864   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11865     return false;
11866 
11867   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11868     if (DC->isTransparentContext())
11869       continue;
11870 
11871     SemaRef.LookupQualifiedName(R, DC);
11872 
11873     if (!R.empty()) {
11874       R.suppressDiagnostics();
11875 
11876       if (isa<CXXRecordDecl>(DC)) {
11877         // Don't diagnose names we find in classes; we get much better
11878         // diagnostics for these from DiagnoseEmptyLookup.
11879         R.clear();
11880         if (DoDiagnoseEmptyLookup)
11881           *DoDiagnoseEmptyLookup = true;
11882         return false;
11883       }
11884 
11885       OverloadCandidateSet Candidates(FnLoc, CSK);
11886       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11887         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11888                                    ExplicitTemplateArgs, Args,
11889                                    Candidates, false, /*KnownValid*/ false);
11890 
11891       OverloadCandidateSet::iterator Best;
11892       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11893         // No viable functions. Don't bother the user with notes for functions
11894         // which don't work and shouldn't be found anyway.
11895         R.clear();
11896         return false;
11897       }
11898 
11899       // Find the namespaces where ADL would have looked, and suggest
11900       // declaring the function there instead.
11901       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11902       Sema::AssociatedClassSet AssociatedClasses;
11903       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11904                                                  AssociatedNamespaces,
11905                                                  AssociatedClasses);
11906       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11907       if (canBeDeclaredInNamespace(R.getLookupName())) {
11908         DeclContext *Std = SemaRef.getStdNamespace();
11909         for (Sema::AssociatedNamespaceSet::iterator
11910                it = AssociatedNamespaces.begin(),
11911                end = AssociatedNamespaces.end(); it != end; ++it) {
11912           // Never suggest declaring a function within namespace 'std'.
11913           if (Std && Std->Encloses(*it))
11914             continue;
11915 
11916           // Never suggest declaring a function within a namespace with a
11917           // reserved name, like __gnu_cxx.
11918           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11919           if (NS &&
11920               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11921             continue;
11922 
11923           SuggestedNamespaces.insert(*it);
11924         }
11925       }
11926 
11927       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11928         << R.getLookupName();
11929       if (SuggestedNamespaces.empty()) {
11930         SemaRef.Diag(Best->Function->getLocation(),
11931                      diag::note_not_found_by_two_phase_lookup)
11932           << R.getLookupName() << 0;
11933       } else if (SuggestedNamespaces.size() == 1) {
11934         SemaRef.Diag(Best->Function->getLocation(),
11935                      diag::note_not_found_by_two_phase_lookup)
11936           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11937       } else {
11938         // FIXME: It would be useful to list the associated namespaces here,
11939         // but the diagnostics infrastructure doesn't provide a way to produce
11940         // a localized representation of a list of items.
11941         SemaRef.Diag(Best->Function->getLocation(),
11942                      diag::note_not_found_by_two_phase_lookup)
11943           << R.getLookupName() << 2;
11944       }
11945 
11946       // Try to recover by calling this function.
11947       return true;
11948     }
11949 
11950     R.clear();
11951   }
11952 
11953   return false;
11954 }
11955 
11956 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11957 /// template, where the non-dependent operator was declared after the template
11958 /// was defined.
11959 ///
11960 /// Returns true if a viable candidate was found and a diagnostic was issued.
11961 static bool
11962 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11963                                SourceLocation OpLoc,
11964                                ArrayRef<Expr *> Args) {
11965   DeclarationName OpName =
11966     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11967   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11968   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11969                                 OverloadCandidateSet::CSK_Operator,
11970                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11971 }
11972 
11973 namespace {
11974 class BuildRecoveryCallExprRAII {
11975   Sema &SemaRef;
11976 public:
11977   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11978     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11979     SemaRef.IsBuildingRecoveryCallExpr = true;
11980   }
11981 
11982   ~BuildRecoveryCallExprRAII() {
11983     SemaRef.IsBuildingRecoveryCallExpr = false;
11984   }
11985 };
11986 
11987 }
11988 
11989 /// Attempts to recover from a call where no functions were found.
11990 ///
11991 /// Returns true if new candidates were found.
11992 static ExprResult
11993 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11994                       UnresolvedLookupExpr *ULE,
11995                       SourceLocation LParenLoc,
11996                       MutableArrayRef<Expr *> Args,
11997                       SourceLocation RParenLoc,
11998                       bool EmptyLookup, bool AllowTypoCorrection) {
11999   // Do not try to recover if it is already building a recovery call.
12000   // This stops infinite loops for template instantiations like
12001   //
12002   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12003   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12004   //
12005   if (SemaRef.IsBuildingRecoveryCallExpr)
12006     return ExprError();
12007   BuildRecoveryCallExprRAII RCE(SemaRef);
12008 
12009   CXXScopeSpec SS;
12010   SS.Adopt(ULE->getQualifierLoc());
12011   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12012 
12013   TemplateArgumentListInfo TABuffer;
12014   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12015   if (ULE->hasExplicitTemplateArgs()) {
12016     ULE->copyTemplateArgumentsInto(TABuffer);
12017     ExplicitTemplateArgs = &TABuffer;
12018   }
12019 
12020   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12021                  Sema::LookupOrdinaryName);
12022   bool DoDiagnoseEmptyLookup = EmptyLookup;
12023   if (!DiagnoseTwoPhaseLookup(
12024           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12025           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12026     NoTypoCorrectionCCC NoTypoValidator{};
12027     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12028                                                 ExplicitTemplateArgs != nullptr,
12029                                                 dyn_cast<MemberExpr>(Fn));
12030     CorrectionCandidateCallback &Validator =
12031         AllowTypoCorrection
12032             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12033             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12034     if (!DoDiagnoseEmptyLookup ||
12035         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12036                                     Args))
12037       return ExprError();
12038   }
12039 
12040   assert(!R.empty() && "lookup results empty despite recovery");
12041 
12042   // If recovery created an ambiguity, just bail out.
12043   if (R.isAmbiguous()) {
12044     R.suppressDiagnostics();
12045     return ExprError();
12046   }
12047 
12048   // Build an implicit member call if appropriate.  Just drop the
12049   // casts and such from the call, we don't really care.
12050   ExprResult NewFn = ExprError();
12051   if ((*R.begin())->isCXXClassMember())
12052     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12053                                                     ExplicitTemplateArgs, S);
12054   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12055     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12056                                         ExplicitTemplateArgs);
12057   else
12058     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12059 
12060   if (NewFn.isInvalid())
12061     return ExprError();
12062 
12063   // This shouldn't cause an infinite loop because we're giving it
12064   // an expression with viable lookup results, which should never
12065   // end up here.
12066   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12067                                MultiExprArg(Args.data(), Args.size()),
12068                                RParenLoc);
12069 }
12070 
12071 /// Constructs and populates an OverloadedCandidateSet from
12072 /// the given function.
12073 /// \returns true when an the ExprResult output parameter has been set.
12074 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12075                                   UnresolvedLookupExpr *ULE,
12076                                   MultiExprArg Args,
12077                                   SourceLocation RParenLoc,
12078                                   OverloadCandidateSet *CandidateSet,
12079                                   ExprResult *Result) {
12080 #ifndef NDEBUG
12081   if (ULE->requiresADL()) {
12082     // To do ADL, we must have found an unqualified name.
12083     assert(!ULE->getQualifier() && "qualified name with ADL");
12084 
12085     // We don't perform ADL for implicit declarations of builtins.
12086     // Verify that this was correctly set up.
12087     FunctionDecl *F;
12088     if (ULE->decls_begin() != ULE->decls_end() &&
12089         ULE->decls_begin() + 1 == ULE->decls_end() &&
12090         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12091         F->getBuiltinID() && F->isImplicit())
12092       llvm_unreachable("performing ADL for builtin");
12093 
12094     // We don't perform ADL in C.
12095     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12096   }
12097 #endif
12098 
12099   UnbridgedCastsSet UnbridgedCasts;
12100   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12101     *Result = ExprError();
12102     return true;
12103   }
12104 
12105   // Add the functions denoted by the callee to the set of candidate
12106   // functions, including those from argument-dependent lookup.
12107   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12108 
12109   if (getLangOpts().MSVCCompat &&
12110       CurContext->isDependentContext() && !isSFINAEContext() &&
12111       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12112 
12113     OverloadCandidateSet::iterator Best;
12114     if (CandidateSet->empty() ||
12115         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12116             OR_No_Viable_Function) {
12117       // In Microsoft mode, if we are inside a template class member function
12118       // then create a type dependent CallExpr. The goal is to postpone name
12119       // lookup to instantiation time to be able to search into type dependent
12120       // base classes.
12121       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12122                                       VK_RValue, RParenLoc);
12123       CE->setTypeDependent(true);
12124       CE->setValueDependent(true);
12125       CE->setInstantiationDependent(true);
12126       *Result = CE;
12127       return true;
12128     }
12129   }
12130 
12131   if (CandidateSet->empty())
12132     return false;
12133 
12134   UnbridgedCasts.restore();
12135   return false;
12136 }
12137 
12138 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12139 /// the completed call expression. If overload resolution fails, emits
12140 /// diagnostics and returns ExprError()
12141 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12142                                            UnresolvedLookupExpr *ULE,
12143                                            SourceLocation LParenLoc,
12144                                            MultiExprArg Args,
12145                                            SourceLocation RParenLoc,
12146                                            Expr *ExecConfig,
12147                                            OverloadCandidateSet *CandidateSet,
12148                                            OverloadCandidateSet::iterator *Best,
12149                                            OverloadingResult OverloadResult,
12150                                            bool AllowTypoCorrection) {
12151   if (CandidateSet->empty())
12152     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12153                                  RParenLoc, /*EmptyLookup=*/true,
12154                                  AllowTypoCorrection);
12155 
12156   switch (OverloadResult) {
12157   case OR_Success: {
12158     FunctionDecl *FDecl = (*Best)->Function;
12159     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12160     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12161       return ExprError();
12162     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12163     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12164                                          ExecConfig, /*IsExecConfig=*/false,
12165                                          (*Best)->IsADLCandidate);
12166   }
12167 
12168   case OR_No_Viable_Function: {
12169     // Try to recover by looking for viable functions which the user might
12170     // have meant to call.
12171     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12172                                                 Args, RParenLoc,
12173                                                 /*EmptyLookup=*/false,
12174                                                 AllowTypoCorrection);
12175     if (!Recovery.isInvalid())
12176       return Recovery;
12177 
12178     // If the user passes in a function that we can't take the address of, we
12179     // generally end up emitting really bad error messages. Here, we attempt to
12180     // emit better ones.
12181     for (const Expr *Arg : Args) {
12182       if (!Arg->getType()->isFunctionType())
12183         continue;
12184       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12185         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12186         if (FD &&
12187             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12188                                                        Arg->getExprLoc()))
12189           return ExprError();
12190       }
12191     }
12192 
12193     CandidateSet->NoteCandidates(
12194         PartialDiagnosticAt(
12195             Fn->getBeginLoc(),
12196             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12197                 << ULE->getName() << Fn->getSourceRange()),
12198         SemaRef, OCD_AllCandidates, Args);
12199     break;
12200   }
12201 
12202   case OR_Ambiguous:
12203     CandidateSet->NoteCandidates(
12204         PartialDiagnosticAt(Fn->getBeginLoc(),
12205                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12206                                 << ULE->getName() << Fn->getSourceRange()),
12207         SemaRef, OCD_ViableCandidates, Args);
12208     break;
12209 
12210   case OR_Deleted: {
12211     CandidateSet->NoteCandidates(
12212         PartialDiagnosticAt(Fn->getBeginLoc(),
12213                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12214                                 << ULE->getName() << Fn->getSourceRange()),
12215         SemaRef, OCD_AllCandidates, Args);
12216 
12217     // We emitted an error for the unavailable/deleted function call but keep
12218     // the call in the AST.
12219     FunctionDecl *FDecl = (*Best)->Function;
12220     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12221     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12222                                          ExecConfig, /*IsExecConfig=*/false,
12223                                          (*Best)->IsADLCandidate);
12224   }
12225   }
12226 
12227   // Overload resolution failed.
12228   return ExprError();
12229 }
12230 
12231 static void markUnaddressableCandidatesUnviable(Sema &S,
12232                                                 OverloadCandidateSet &CS) {
12233   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12234     if (I->Viable &&
12235         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12236       I->Viable = false;
12237       I->FailureKind = ovl_fail_addr_not_available;
12238     }
12239   }
12240 }
12241 
12242 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12243 /// (which eventually refers to the declaration Func) and the call
12244 /// arguments Args/NumArgs, attempt to resolve the function call down
12245 /// to a specific function. If overload resolution succeeds, returns
12246 /// the call expression produced by overload resolution.
12247 /// Otherwise, emits diagnostics and returns ExprError.
12248 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12249                                          UnresolvedLookupExpr *ULE,
12250                                          SourceLocation LParenLoc,
12251                                          MultiExprArg Args,
12252                                          SourceLocation RParenLoc,
12253                                          Expr *ExecConfig,
12254                                          bool AllowTypoCorrection,
12255                                          bool CalleesAddressIsTaken) {
12256   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12257                                     OverloadCandidateSet::CSK_Normal);
12258   ExprResult result;
12259 
12260   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12261                              &result))
12262     return result;
12263 
12264   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12265   // functions that aren't addressible are considered unviable.
12266   if (CalleesAddressIsTaken)
12267     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12268 
12269   OverloadCandidateSet::iterator Best;
12270   OverloadingResult OverloadResult =
12271       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12272 
12273   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12274                                   ExecConfig, &CandidateSet, &Best,
12275                                   OverloadResult, AllowTypoCorrection);
12276 }
12277 
12278 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12279   return Functions.size() > 1 ||
12280     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12281 }
12282 
12283 /// Create a unary operation that may resolve to an overloaded
12284 /// operator.
12285 ///
12286 /// \param OpLoc The location of the operator itself (e.g., '*').
12287 ///
12288 /// \param Opc The UnaryOperatorKind that describes this operator.
12289 ///
12290 /// \param Fns The set of non-member functions that will be
12291 /// considered by overload resolution. The caller needs to build this
12292 /// set based on the context using, e.g.,
12293 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12294 /// set should not contain any member functions; those will be added
12295 /// by CreateOverloadedUnaryOp().
12296 ///
12297 /// \param Input The input argument.
12298 ExprResult
12299 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12300                               const UnresolvedSetImpl &Fns,
12301                               Expr *Input, bool PerformADL) {
12302   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12303   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12304   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12305   // TODO: provide better source location info.
12306   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12307 
12308   if (checkPlaceholderForOverload(*this, Input))
12309     return ExprError();
12310 
12311   Expr *Args[2] = { Input, nullptr };
12312   unsigned NumArgs = 1;
12313 
12314   // For post-increment and post-decrement, add the implicit '0' as
12315   // the second argument, so that we know this is a post-increment or
12316   // post-decrement.
12317   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12318     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12319     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12320                                      SourceLocation());
12321     NumArgs = 2;
12322   }
12323 
12324   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12325 
12326   if (Input->isTypeDependent()) {
12327     if (Fns.empty())
12328       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12329                                          VK_RValue, OK_Ordinary, OpLoc, false);
12330 
12331     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12332     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12333         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12334         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12335     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12336                                        Context.DependentTy, VK_RValue, OpLoc,
12337                                        FPOptions());
12338   }
12339 
12340   // Build an empty overload set.
12341   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12342 
12343   // Add the candidates from the given function set.
12344   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12345 
12346   // Add operator candidates that are member functions.
12347   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12348 
12349   // Add candidates from ADL.
12350   if (PerformADL) {
12351     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12352                                          /*ExplicitTemplateArgs*/nullptr,
12353                                          CandidateSet);
12354   }
12355 
12356   // Add builtin operator candidates.
12357   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12358 
12359   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12360 
12361   // Perform overload resolution.
12362   OverloadCandidateSet::iterator Best;
12363   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12364   case OR_Success: {
12365     // We found a built-in operator or an overloaded operator.
12366     FunctionDecl *FnDecl = Best->Function;
12367 
12368     if (FnDecl) {
12369       Expr *Base = nullptr;
12370       // We matched an overloaded operator. Build a call to that
12371       // operator.
12372 
12373       // Convert the arguments.
12374       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12375         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12376 
12377         ExprResult InputRes =
12378           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12379                                               Best->FoundDecl, Method);
12380         if (InputRes.isInvalid())
12381           return ExprError();
12382         Base = Input = InputRes.get();
12383       } else {
12384         // Convert the arguments.
12385         ExprResult InputInit
12386           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12387                                                       Context,
12388                                                       FnDecl->getParamDecl(0)),
12389                                       SourceLocation(),
12390                                       Input);
12391         if (InputInit.isInvalid())
12392           return ExprError();
12393         Input = InputInit.get();
12394       }
12395 
12396       // Build the actual expression node.
12397       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12398                                                 Base, HadMultipleCandidates,
12399                                                 OpLoc);
12400       if (FnExpr.isInvalid())
12401         return ExprError();
12402 
12403       // Determine the result type.
12404       QualType ResultTy = FnDecl->getReturnType();
12405       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12406       ResultTy = ResultTy.getNonLValueExprType(Context);
12407 
12408       Args[0] = Input;
12409       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12410           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12411           FPOptions(), Best->IsADLCandidate);
12412 
12413       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12414         return ExprError();
12415 
12416       if (CheckFunctionCall(FnDecl, TheCall,
12417                             FnDecl->getType()->castAs<FunctionProtoType>()))
12418         return ExprError();
12419 
12420       return MaybeBindToTemporary(TheCall);
12421     } else {
12422       // We matched a built-in operator. Convert the arguments, then
12423       // break out so that we will build the appropriate built-in
12424       // operator node.
12425       ExprResult InputRes = PerformImplicitConversion(
12426           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12427           CCK_ForBuiltinOverloadedOp);
12428       if (InputRes.isInvalid())
12429         return ExprError();
12430       Input = InputRes.get();
12431       break;
12432     }
12433   }
12434 
12435   case OR_No_Viable_Function:
12436     // This is an erroneous use of an operator which can be overloaded by
12437     // a non-member function. Check for non-member operators which were
12438     // defined too late to be candidates.
12439     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12440       // FIXME: Recover by calling the found function.
12441       return ExprError();
12442 
12443     // No viable function; fall through to handling this as a
12444     // built-in operator, which will produce an error message for us.
12445     break;
12446 
12447   case OR_Ambiguous:
12448     CandidateSet.NoteCandidates(
12449         PartialDiagnosticAt(OpLoc,
12450                             PDiag(diag::err_ovl_ambiguous_oper_unary)
12451                                 << UnaryOperator::getOpcodeStr(Opc)
12452                                 << Input->getType() << Input->getSourceRange()),
12453         *this, OCD_ViableCandidates, ArgsArray,
12454         UnaryOperator::getOpcodeStr(Opc), OpLoc);
12455     return ExprError();
12456 
12457   case OR_Deleted:
12458     CandidateSet.NoteCandidates(
12459         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12460                                        << UnaryOperator::getOpcodeStr(Opc)
12461                                        << Input->getSourceRange()),
12462         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
12463         OpLoc);
12464     return ExprError();
12465   }
12466 
12467   // Either we found no viable overloaded operator or we matched a
12468   // built-in operator. In either case, fall through to trying to
12469   // build a built-in operation.
12470   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12471 }
12472 
12473 /// Create a binary operation that may resolve to an overloaded
12474 /// operator.
12475 ///
12476 /// \param OpLoc The location of the operator itself (e.g., '+').
12477 ///
12478 /// \param Opc The BinaryOperatorKind that describes this operator.
12479 ///
12480 /// \param Fns The set of non-member functions that will be
12481 /// considered by overload resolution. The caller needs to build this
12482 /// set based on the context using, e.g.,
12483 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12484 /// set should not contain any member functions; those will be added
12485 /// by CreateOverloadedBinOp().
12486 ///
12487 /// \param LHS Left-hand argument.
12488 /// \param RHS Right-hand argument.
12489 ExprResult
12490 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12491                             BinaryOperatorKind Opc,
12492                             const UnresolvedSetImpl &Fns,
12493                             Expr *LHS, Expr *RHS, bool PerformADL) {
12494   Expr *Args[2] = { LHS, RHS };
12495   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12496 
12497   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12498   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12499 
12500   // If either side is type-dependent, create an appropriate dependent
12501   // expression.
12502   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12503     if (Fns.empty()) {
12504       // If there are no functions to store, just build a dependent
12505       // BinaryOperator or CompoundAssignment.
12506       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12507         return new (Context) BinaryOperator(
12508             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12509             OpLoc, FPFeatures);
12510 
12511       return new (Context) CompoundAssignOperator(
12512           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12513           Context.DependentTy, Context.DependentTy, OpLoc,
12514           FPFeatures);
12515     }
12516 
12517     // FIXME: save results of ADL from here?
12518     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12519     // TODO: provide better source location info in DNLoc component.
12520     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12521     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12522         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12523         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12524     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12525                                        Context.DependentTy, VK_RValue, OpLoc,
12526                                        FPFeatures);
12527   }
12528 
12529   // Always do placeholder-like conversions on the RHS.
12530   if (checkPlaceholderForOverload(*this, Args[1]))
12531     return ExprError();
12532 
12533   // Do placeholder-like conversion on the LHS; note that we should
12534   // not get here with a PseudoObject LHS.
12535   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12536   if (checkPlaceholderForOverload(*this, Args[0]))
12537     return ExprError();
12538 
12539   // If this is the assignment operator, we only perform overload resolution
12540   // if the left-hand side is a class or enumeration type. This is actually
12541   // a hack. The standard requires that we do overload resolution between the
12542   // various built-in candidates, but as DR507 points out, this can lead to
12543   // problems. So we do it this way, which pretty much follows what GCC does.
12544   // Note that we go the traditional code path for compound assignment forms.
12545   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12546     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12547 
12548   // If this is the .* operator, which is not overloadable, just
12549   // create a built-in binary operator.
12550   if (Opc == BO_PtrMemD)
12551     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12552 
12553   // Build an empty overload set.
12554   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12555 
12556   // Add the candidates from the given function set.
12557   AddFunctionCandidates(Fns, Args, CandidateSet);
12558 
12559   // Add operator candidates that are member functions.
12560   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12561 
12562   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12563   // performed for an assignment operator (nor for operator[] nor operator->,
12564   // which don't get here).
12565   if (Opc != BO_Assign && PerformADL)
12566     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12567                                          /*ExplicitTemplateArgs*/ nullptr,
12568                                          CandidateSet);
12569 
12570   // Add builtin operator candidates.
12571   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12572 
12573   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12574 
12575   // Perform overload resolution.
12576   OverloadCandidateSet::iterator Best;
12577   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12578     case OR_Success: {
12579       // We found a built-in operator or an overloaded operator.
12580       FunctionDecl *FnDecl = Best->Function;
12581 
12582       if (FnDecl) {
12583         Expr *Base = nullptr;
12584         // We matched an overloaded operator. Build a call to that
12585         // operator.
12586 
12587         // Convert the arguments.
12588         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12589           // Best->Access is only meaningful for class members.
12590           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12591 
12592           ExprResult Arg1 =
12593             PerformCopyInitialization(
12594               InitializedEntity::InitializeParameter(Context,
12595                                                      FnDecl->getParamDecl(0)),
12596               SourceLocation(), Args[1]);
12597           if (Arg1.isInvalid())
12598             return ExprError();
12599 
12600           ExprResult Arg0 =
12601             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12602                                                 Best->FoundDecl, Method);
12603           if (Arg0.isInvalid())
12604             return ExprError();
12605           Base = Args[0] = Arg0.getAs<Expr>();
12606           Args[1] = RHS = Arg1.getAs<Expr>();
12607         } else {
12608           // Convert the arguments.
12609           ExprResult Arg0 = PerformCopyInitialization(
12610             InitializedEntity::InitializeParameter(Context,
12611                                                    FnDecl->getParamDecl(0)),
12612             SourceLocation(), Args[0]);
12613           if (Arg0.isInvalid())
12614             return ExprError();
12615 
12616           ExprResult Arg1 =
12617             PerformCopyInitialization(
12618               InitializedEntity::InitializeParameter(Context,
12619                                                      FnDecl->getParamDecl(1)),
12620               SourceLocation(), Args[1]);
12621           if (Arg1.isInvalid())
12622             return ExprError();
12623           Args[0] = LHS = Arg0.getAs<Expr>();
12624           Args[1] = RHS = Arg1.getAs<Expr>();
12625         }
12626 
12627         // Build the actual expression node.
12628         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12629                                                   Best->FoundDecl, Base,
12630                                                   HadMultipleCandidates, OpLoc);
12631         if (FnExpr.isInvalid())
12632           return ExprError();
12633 
12634         // Determine the result type.
12635         QualType ResultTy = FnDecl->getReturnType();
12636         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12637         ResultTy = ResultTy.getNonLValueExprType(Context);
12638 
12639         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
12640             Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
12641             Best->IsADLCandidate);
12642 
12643         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12644                                 FnDecl))
12645           return ExprError();
12646 
12647         ArrayRef<const Expr *> ArgsArray(Args, 2);
12648         const Expr *ImplicitThis = nullptr;
12649         // Cut off the implicit 'this'.
12650         if (isa<CXXMethodDecl>(FnDecl)) {
12651           ImplicitThis = ArgsArray[0];
12652           ArgsArray = ArgsArray.slice(1);
12653         }
12654 
12655         // Check for a self move.
12656         if (Op == OO_Equal)
12657           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12658 
12659         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12660                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12661                   VariadicDoesNotApply);
12662 
12663         return MaybeBindToTemporary(TheCall);
12664       } else {
12665         // We matched a built-in operator. Convert the arguments, then
12666         // break out so that we will build the appropriate built-in
12667         // operator node.
12668         ExprResult ArgsRes0 = PerformImplicitConversion(
12669             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12670             AA_Passing, CCK_ForBuiltinOverloadedOp);
12671         if (ArgsRes0.isInvalid())
12672           return ExprError();
12673         Args[0] = ArgsRes0.get();
12674 
12675         ExprResult ArgsRes1 = PerformImplicitConversion(
12676             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12677             AA_Passing, CCK_ForBuiltinOverloadedOp);
12678         if (ArgsRes1.isInvalid())
12679           return ExprError();
12680         Args[1] = ArgsRes1.get();
12681         break;
12682       }
12683     }
12684 
12685     case OR_No_Viable_Function: {
12686       // C++ [over.match.oper]p9:
12687       //   If the operator is the operator , [...] and there are no
12688       //   viable functions, then the operator is assumed to be the
12689       //   built-in operator and interpreted according to clause 5.
12690       if (Opc == BO_Comma)
12691         break;
12692 
12693       // For class as left operand for assignment or compound assignment
12694       // operator do not fall through to handling in built-in, but report that
12695       // no overloaded assignment operator found
12696       ExprResult Result = ExprError();
12697       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
12698       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
12699                                                    Args, OpLoc);
12700       if (Args[0]->getType()->isRecordType() &&
12701           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12702         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12703              << BinaryOperator::getOpcodeStr(Opc)
12704              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12705         if (Args[0]->getType()->isIncompleteType()) {
12706           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12707             << Args[0]->getType()
12708             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12709         }
12710       } else {
12711         // This is an erroneous use of an operator which can be overloaded by
12712         // a non-member function. Check for non-member operators which were
12713         // defined too late to be candidates.
12714         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12715           // FIXME: Recover by calling the found function.
12716           return ExprError();
12717 
12718         // No viable function; try to create a built-in operation, which will
12719         // produce an error. Then, show the non-viable candidates.
12720         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12721       }
12722       assert(Result.isInvalid() &&
12723              "C++ binary operator overloading is missing candidates!");
12724       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
12725       return Result;
12726     }
12727 
12728     case OR_Ambiguous:
12729       CandidateSet.NoteCandidates(
12730           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
12731                                          << BinaryOperator::getOpcodeStr(Opc)
12732                                          << Args[0]->getType()
12733                                          << Args[1]->getType()
12734                                          << Args[0]->getSourceRange()
12735                                          << Args[1]->getSourceRange()),
12736           *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
12737           OpLoc);
12738       return ExprError();
12739 
12740     case OR_Deleted:
12741       if (isImplicitlyDeleted(Best->Function)) {
12742         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12743         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12744           << Context.getRecordType(Method->getParent())
12745           << getSpecialMember(Method);
12746 
12747         // The user probably meant to call this special member. Just
12748         // explain why it's deleted.
12749         NoteDeletedFunction(Method);
12750         return ExprError();
12751       }
12752       CandidateSet.NoteCandidates(
12753           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12754                                          << BinaryOperator::getOpcodeStr(Opc)
12755                                          << Args[0]->getSourceRange()
12756                                          << Args[1]->getSourceRange()),
12757           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
12758           OpLoc);
12759       return ExprError();
12760   }
12761 
12762   // We matched a built-in operator; build it.
12763   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12764 }
12765 
12766 ExprResult
12767 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12768                                          SourceLocation RLoc,
12769                                          Expr *Base, Expr *Idx) {
12770   Expr *Args[2] = { Base, Idx };
12771   DeclarationName OpName =
12772       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12773 
12774   // If either side is type-dependent, create an appropriate dependent
12775   // expression.
12776   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12777 
12778     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12779     // CHECKME: no 'operator' keyword?
12780     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12781     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12782     UnresolvedLookupExpr *Fn
12783       = UnresolvedLookupExpr::Create(Context, NamingClass,
12784                                      NestedNameSpecifierLoc(), OpNameInfo,
12785                                      /*ADL*/ true, /*Overloaded*/ false,
12786                                      UnresolvedSetIterator(),
12787                                      UnresolvedSetIterator());
12788     // Can't add any actual overloads yet
12789 
12790     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
12791                                        Context.DependentTy, VK_RValue, RLoc,
12792                                        FPOptions());
12793   }
12794 
12795   // Handle placeholders on both operands.
12796   if (checkPlaceholderForOverload(*this, Args[0]))
12797     return ExprError();
12798   if (checkPlaceholderForOverload(*this, Args[1]))
12799     return ExprError();
12800 
12801   // Build an empty overload set.
12802   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12803 
12804   // Subscript can only be overloaded as a member function.
12805 
12806   // Add operator candidates that are member functions.
12807   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12808 
12809   // Add builtin operator candidates.
12810   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12811 
12812   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12813 
12814   // Perform overload resolution.
12815   OverloadCandidateSet::iterator Best;
12816   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12817     case OR_Success: {
12818       // We found a built-in operator or an overloaded operator.
12819       FunctionDecl *FnDecl = Best->Function;
12820 
12821       if (FnDecl) {
12822         // We matched an overloaded operator. Build a call to that
12823         // operator.
12824 
12825         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12826 
12827         // Convert the arguments.
12828         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12829         ExprResult Arg0 =
12830           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12831                                               Best->FoundDecl, Method);
12832         if (Arg0.isInvalid())
12833           return ExprError();
12834         Args[0] = Arg0.get();
12835 
12836         // Convert the arguments.
12837         ExprResult InputInit
12838           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12839                                                       Context,
12840                                                       FnDecl->getParamDecl(0)),
12841                                       SourceLocation(),
12842                                       Args[1]);
12843         if (InputInit.isInvalid())
12844           return ExprError();
12845 
12846         Args[1] = InputInit.getAs<Expr>();
12847 
12848         // Build the actual expression node.
12849         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12850         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12851         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12852                                                   Best->FoundDecl,
12853                                                   Base,
12854                                                   HadMultipleCandidates,
12855                                                   OpLocInfo.getLoc(),
12856                                                   OpLocInfo.getInfo());
12857         if (FnExpr.isInvalid())
12858           return ExprError();
12859 
12860         // Determine the result type
12861         QualType ResultTy = FnDecl->getReturnType();
12862         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12863         ResultTy = ResultTy.getNonLValueExprType(Context);
12864 
12865         CXXOperatorCallExpr *TheCall =
12866             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
12867                                         Args, ResultTy, VK, RLoc, FPOptions());
12868 
12869         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12870           return ExprError();
12871 
12872         if (CheckFunctionCall(Method, TheCall,
12873                               Method->getType()->castAs<FunctionProtoType>()))
12874           return ExprError();
12875 
12876         return MaybeBindToTemporary(TheCall);
12877       } else {
12878         // We matched a built-in operator. Convert the arguments, then
12879         // break out so that we will build the appropriate built-in
12880         // operator node.
12881         ExprResult ArgsRes0 = PerformImplicitConversion(
12882             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12883             AA_Passing, CCK_ForBuiltinOverloadedOp);
12884         if (ArgsRes0.isInvalid())
12885           return ExprError();
12886         Args[0] = ArgsRes0.get();
12887 
12888         ExprResult ArgsRes1 = PerformImplicitConversion(
12889             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12890             AA_Passing, CCK_ForBuiltinOverloadedOp);
12891         if (ArgsRes1.isInvalid())
12892           return ExprError();
12893         Args[1] = ArgsRes1.get();
12894 
12895         break;
12896       }
12897     }
12898 
12899     case OR_No_Viable_Function: {
12900       PartialDiagnostic PD = CandidateSet.empty()
12901           ? (PDiag(diag::err_ovl_no_oper)
12902              << Args[0]->getType() << /*subscript*/ 0
12903              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
12904           : (PDiag(diag::err_ovl_no_viable_subscript)
12905              << Args[0]->getType() << Args[0]->getSourceRange()
12906              << Args[1]->getSourceRange());
12907       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
12908                                   OCD_AllCandidates, Args, "[]", LLoc);
12909       return ExprError();
12910     }
12911 
12912     case OR_Ambiguous:
12913       CandidateSet.NoteCandidates(
12914           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
12915                                         << "[]" << Args[0]->getType()
12916                                         << Args[1]->getType()
12917                                         << Args[0]->getSourceRange()
12918                                         << Args[1]->getSourceRange()),
12919           *this, OCD_ViableCandidates, Args, "[]", LLoc);
12920       return ExprError();
12921 
12922     case OR_Deleted:
12923       CandidateSet.NoteCandidates(
12924           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
12925                                         << "[]" << Args[0]->getSourceRange()
12926                                         << Args[1]->getSourceRange()),
12927           *this, OCD_AllCandidates, Args, "[]", LLoc);
12928       return ExprError();
12929     }
12930 
12931   // We matched a built-in operator; build it.
12932   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12933 }
12934 
12935 /// BuildCallToMemberFunction - Build a call to a member
12936 /// function. MemExpr is the expression that refers to the member
12937 /// function (and includes the object parameter), Args/NumArgs are the
12938 /// arguments to the function call (not including the object
12939 /// parameter). The caller needs to validate that the member
12940 /// expression refers to a non-static member function or an overloaded
12941 /// member function.
12942 ExprResult
12943 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12944                                 SourceLocation LParenLoc,
12945                                 MultiExprArg Args,
12946                                 SourceLocation RParenLoc) {
12947   assert(MemExprE->getType() == Context.BoundMemberTy ||
12948          MemExprE->getType() == Context.OverloadTy);
12949 
12950   // Dig out the member expression. This holds both the object
12951   // argument and the member function we're referring to.
12952   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12953 
12954   // Determine whether this is a call to a pointer-to-member function.
12955   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12956     assert(op->getType() == Context.BoundMemberTy);
12957     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12958 
12959     QualType fnType =
12960       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12961 
12962     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12963     QualType resultType = proto->getCallResultType(Context);
12964     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12965 
12966     // Check that the object type isn't more qualified than the
12967     // member function we're calling.
12968     Qualifiers funcQuals = proto->getMethodQuals();
12969 
12970     QualType objectType = op->getLHS()->getType();
12971     if (op->getOpcode() == BO_PtrMemI)
12972       objectType = objectType->castAs<PointerType>()->getPointeeType();
12973     Qualifiers objectQuals = objectType.getQualifiers();
12974 
12975     Qualifiers difference = objectQuals - funcQuals;
12976     difference.removeObjCGCAttr();
12977     difference.removeAddressSpace();
12978     if (difference) {
12979       std::string qualsString = difference.getAsString();
12980       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12981         << fnType.getUnqualifiedType()
12982         << qualsString
12983         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12984     }
12985 
12986     CXXMemberCallExpr *call =
12987         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
12988                                   valueKind, RParenLoc, proto->getNumParams());
12989 
12990     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
12991                             call, nullptr))
12992       return ExprError();
12993 
12994     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12995       return ExprError();
12996 
12997     if (CheckOtherCall(call, proto))
12998       return ExprError();
12999 
13000     return MaybeBindToTemporary(call);
13001   }
13002 
13003   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13004     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13005                             RParenLoc);
13006 
13007   UnbridgedCastsSet UnbridgedCasts;
13008   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13009     return ExprError();
13010 
13011   MemberExpr *MemExpr;
13012   CXXMethodDecl *Method = nullptr;
13013   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13014   NestedNameSpecifier *Qualifier = nullptr;
13015   if (isa<MemberExpr>(NakedMemExpr)) {
13016     MemExpr = cast<MemberExpr>(NakedMemExpr);
13017     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13018     FoundDecl = MemExpr->getFoundDecl();
13019     Qualifier = MemExpr->getQualifier();
13020     UnbridgedCasts.restore();
13021   } else {
13022     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13023     Qualifier = UnresExpr->getQualifier();
13024 
13025     QualType ObjectType = UnresExpr->getBaseType();
13026     Expr::Classification ObjectClassification
13027       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13028                             : UnresExpr->getBase()->Classify(Context);
13029 
13030     // Add overload candidates
13031     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13032                                       OverloadCandidateSet::CSK_Normal);
13033 
13034     // FIXME: avoid copy.
13035     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13036     if (UnresExpr->hasExplicitTemplateArgs()) {
13037       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13038       TemplateArgs = &TemplateArgsBuffer;
13039     }
13040 
13041     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13042            E = UnresExpr->decls_end(); I != E; ++I) {
13043 
13044       NamedDecl *Func = *I;
13045       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13046       if (isa<UsingShadowDecl>(Func))
13047         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13048 
13049 
13050       // Microsoft supports direct constructor calls.
13051       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13052         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13053                              CandidateSet,
13054                              /*SuppressUserConversions*/ false);
13055       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13056         // If explicit template arguments were provided, we can't call a
13057         // non-template member function.
13058         if (TemplateArgs)
13059           continue;
13060 
13061         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13062                            ObjectClassification, Args, CandidateSet,
13063                            /*SuppressUserConversions=*/false);
13064       } else {
13065         AddMethodTemplateCandidate(
13066             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13067             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13068             /*SuppressUserConversions=*/false);
13069       }
13070     }
13071 
13072     DeclarationName DeclName = UnresExpr->getMemberName();
13073 
13074     UnbridgedCasts.restore();
13075 
13076     OverloadCandidateSet::iterator Best;
13077     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13078                                             Best)) {
13079     case OR_Success:
13080       Method = cast<CXXMethodDecl>(Best->Function);
13081       FoundDecl = Best->FoundDecl;
13082       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13083       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13084         return ExprError();
13085       // If FoundDecl is different from Method (such as if one is a template
13086       // and the other a specialization), make sure DiagnoseUseOfDecl is
13087       // called on both.
13088       // FIXME: This would be more comprehensively addressed by modifying
13089       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13090       // being used.
13091       if (Method != FoundDecl.getDecl() &&
13092                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13093         return ExprError();
13094       break;
13095 
13096     case OR_No_Viable_Function:
13097       CandidateSet.NoteCandidates(
13098           PartialDiagnosticAt(
13099               UnresExpr->getMemberLoc(),
13100               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13101                   << DeclName << MemExprE->getSourceRange()),
13102           *this, OCD_AllCandidates, Args);
13103       // FIXME: Leaking incoming expressions!
13104       return ExprError();
13105 
13106     case OR_Ambiguous:
13107       CandidateSet.NoteCandidates(
13108           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13109                               PDiag(diag::err_ovl_ambiguous_member_call)
13110                                   << DeclName << MemExprE->getSourceRange()),
13111           *this, OCD_AllCandidates, Args);
13112       // FIXME: Leaking incoming expressions!
13113       return ExprError();
13114 
13115     case OR_Deleted:
13116       CandidateSet.NoteCandidates(
13117           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13118                               PDiag(diag::err_ovl_deleted_member_call)
13119                                   << DeclName << MemExprE->getSourceRange()),
13120           *this, OCD_AllCandidates, Args);
13121       // FIXME: Leaking incoming expressions!
13122       return ExprError();
13123     }
13124 
13125     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13126 
13127     // If overload resolution picked a static member, build a
13128     // non-member call based on that function.
13129     if (Method->isStatic()) {
13130       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13131                                    RParenLoc);
13132     }
13133 
13134     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13135   }
13136 
13137   QualType ResultType = Method->getReturnType();
13138   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13139   ResultType = ResultType.getNonLValueExprType(Context);
13140 
13141   assert(Method && "Member call to something that isn't a method?");
13142   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13143   CXXMemberCallExpr *TheCall =
13144       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13145                                 RParenLoc, Proto->getNumParams());
13146 
13147   // Check for a valid return type.
13148   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13149                           TheCall, Method))
13150     return ExprError();
13151 
13152   // Convert the object argument (for a non-static member function call).
13153   // We only need to do this if there was actually an overload; otherwise
13154   // it was done at lookup.
13155   if (!Method->isStatic()) {
13156     ExprResult ObjectArg =
13157       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13158                                           FoundDecl, Method);
13159     if (ObjectArg.isInvalid())
13160       return ExprError();
13161     MemExpr->setBase(ObjectArg.get());
13162   }
13163 
13164   // Convert the rest of the arguments
13165   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13166                               RParenLoc))
13167     return ExprError();
13168 
13169   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13170 
13171   if (CheckFunctionCall(Method, TheCall, Proto))
13172     return ExprError();
13173 
13174   // In the case the method to call was not selected by the overloading
13175   // resolution process, we still need to handle the enable_if attribute. Do
13176   // that here, so it will not hide previous -- and more relevant -- errors.
13177   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13178     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13179       Diag(MemE->getMemberLoc(),
13180            diag::err_ovl_no_viable_member_function_in_call)
13181           << Method << Method->getSourceRange();
13182       Diag(Method->getLocation(),
13183            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13184           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13185       return ExprError();
13186     }
13187   }
13188 
13189   if ((isa<CXXConstructorDecl>(CurContext) ||
13190        isa<CXXDestructorDecl>(CurContext)) &&
13191       TheCall->getMethodDecl()->isPure()) {
13192     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13193 
13194     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13195         MemExpr->performsVirtualDispatch(getLangOpts())) {
13196       Diag(MemExpr->getBeginLoc(),
13197            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13198           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13199           << MD->getParent()->getDeclName();
13200 
13201       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13202       if (getLangOpts().AppleKext)
13203         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13204             << MD->getParent()->getDeclName() << MD->getDeclName();
13205     }
13206   }
13207 
13208   if (CXXDestructorDecl *DD =
13209           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13210     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13211     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13212     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13213                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13214                          MemExpr->getMemberLoc());
13215   }
13216 
13217   return MaybeBindToTemporary(TheCall);
13218 }
13219 
13220 /// BuildCallToObjectOfClassType - Build a call to an object of class
13221 /// type (C++ [over.call.object]), which can end up invoking an
13222 /// overloaded function call operator (@c operator()) or performing a
13223 /// user-defined conversion on the object argument.
13224 ExprResult
13225 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13226                                    SourceLocation LParenLoc,
13227                                    MultiExprArg Args,
13228                                    SourceLocation RParenLoc) {
13229   if (checkPlaceholderForOverload(*this, Obj))
13230     return ExprError();
13231   ExprResult Object = Obj;
13232 
13233   UnbridgedCastsSet UnbridgedCasts;
13234   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13235     return ExprError();
13236 
13237   assert(Object.get()->getType()->isRecordType() &&
13238          "Requires object type argument");
13239   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13240 
13241   // C++ [over.call.object]p1:
13242   //  If the primary-expression E in the function call syntax
13243   //  evaluates to a class object of type "cv T", then the set of
13244   //  candidate functions includes at least the function call
13245   //  operators of T. The function call operators of T are obtained by
13246   //  ordinary lookup of the name operator() in the context of
13247   //  (E).operator().
13248   OverloadCandidateSet CandidateSet(LParenLoc,
13249                                     OverloadCandidateSet::CSK_Operator);
13250   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13251 
13252   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13253                           diag::err_incomplete_object_call, Object.get()))
13254     return true;
13255 
13256   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13257   LookupQualifiedName(R, Record->getDecl());
13258   R.suppressDiagnostics();
13259 
13260   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13261        Oper != OperEnd; ++Oper) {
13262     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13263                        Object.get()->Classify(Context), Args, CandidateSet,
13264                        /*SuppressUserConversion=*/false);
13265   }
13266 
13267   // C++ [over.call.object]p2:
13268   //   In addition, for each (non-explicit in C++0x) conversion function
13269   //   declared in T of the form
13270   //
13271   //        operator conversion-type-id () cv-qualifier;
13272   //
13273   //   where cv-qualifier is the same cv-qualification as, or a
13274   //   greater cv-qualification than, cv, and where conversion-type-id
13275   //   denotes the type "pointer to function of (P1,...,Pn) returning
13276   //   R", or the type "reference to pointer to function of
13277   //   (P1,...,Pn) returning R", or the type "reference to function
13278   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13279   //   is also considered as a candidate function. Similarly,
13280   //   surrogate call functions are added to the set of candidate
13281   //   functions for each conversion function declared in an
13282   //   accessible base class provided the function is not hidden
13283   //   within T by another intervening declaration.
13284   const auto &Conversions =
13285       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13286   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13287     NamedDecl *D = *I;
13288     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13289     if (isa<UsingShadowDecl>(D))
13290       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13291 
13292     // Skip over templated conversion functions; they aren't
13293     // surrogates.
13294     if (isa<FunctionTemplateDecl>(D))
13295       continue;
13296 
13297     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13298     if (!Conv->isExplicit()) {
13299       // Strip the reference type (if any) and then the pointer type (if
13300       // any) to get down to what might be a function type.
13301       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13302       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13303         ConvType = ConvPtrType->getPointeeType();
13304 
13305       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13306       {
13307         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13308                               Object.get(), Args, CandidateSet);
13309       }
13310     }
13311   }
13312 
13313   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13314 
13315   // Perform overload resolution.
13316   OverloadCandidateSet::iterator Best;
13317   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13318                                           Best)) {
13319   case OR_Success:
13320     // Overload resolution succeeded; we'll build the appropriate call
13321     // below.
13322     break;
13323 
13324   case OR_No_Viable_Function: {
13325     PartialDiagnostic PD =
13326         CandidateSet.empty()
13327             ? (PDiag(diag::err_ovl_no_oper)
13328                << Object.get()->getType() << /*call*/ 1
13329                << Object.get()->getSourceRange())
13330             : (PDiag(diag::err_ovl_no_viable_object_call)
13331                << Object.get()->getType() << Object.get()->getSourceRange());
13332     CandidateSet.NoteCandidates(
13333         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
13334         OCD_AllCandidates, Args);
13335     break;
13336   }
13337   case OR_Ambiguous:
13338     CandidateSet.NoteCandidates(
13339         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13340                             PDiag(diag::err_ovl_ambiguous_object_call)
13341                                 << Object.get()->getType()
13342                                 << Object.get()->getSourceRange()),
13343         *this, OCD_ViableCandidates, Args);
13344     break;
13345 
13346   case OR_Deleted:
13347     CandidateSet.NoteCandidates(
13348         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13349                             PDiag(diag::err_ovl_deleted_object_call)
13350                                 << Object.get()->getType()
13351                                 << Object.get()->getSourceRange()),
13352         *this, OCD_AllCandidates, Args);
13353     break;
13354   }
13355 
13356   if (Best == CandidateSet.end())
13357     return true;
13358 
13359   UnbridgedCasts.restore();
13360 
13361   if (Best->Function == nullptr) {
13362     // Since there is no function declaration, this is one of the
13363     // surrogate candidates. Dig out the conversion function.
13364     CXXConversionDecl *Conv
13365       = cast<CXXConversionDecl>(
13366                          Best->Conversions[0].UserDefined.ConversionFunction);
13367 
13368     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13369                               Best->FoundDecl);
13370     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13371       return ExprError();
13372     assert(Conv == Best->FoundDecl.getDecl() &&
13373              "Found Decl & conversion-to-functionptr should be same, right?!");
13374     // We selected one of the surrogate functions that converts the
13375     // object parameter to a function pointer. Perform the conversion
13376     // on the object argument, then let BuildCallExpr finish the job.
13377 
13378     // Create an implicit member expr to refer to the conversion operator.
13379     // and then call it.
13380     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13381                                              Conv, HadMultipleCandidates);
13382     if (Call.isInvalid())
13383       return ExprError();
13384     // Record usage of conversion in an implicit cast.
13385     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13386                                     CK_UserDefinedConversion, Call.get(),
13387                                     nullptr, VK_RValue);
13388 
13389     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13390   }
13391 
13392   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13393 
13394   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13395   // that calls this method, using Object for the implicit object
13396   // parameter and passing along the remaining arguments.
13397   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13398 
13399   // An error diagnostic has already been printed when parsing the declaration.
13400   if (Method->isInvalidDecl())
13401     return ExprError();
13402 
13403   const FunctionProtoType *Proto =
13404     Method->getType()->getAs<FunctionProtoType>();
13405 
13406   unsigned NumParams = Proto->getNumParams();
13407 
13408   DeclarationNameInfo OpLocInfo(
13409                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13410   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13411   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13412                                            Obj, HadMultipleCandidates,
13413                                            OpLocInfo.getLoc(),
13414                                            OpLocInfo.getInfo());
13415   if (NewFn.isInvalid())
13416     return true;
13417 
13418   // The number of argument slots to allocate in the call. If we have default
13419   // arguments we need to allocate space for them as well. We additionally
13420   // need one more slot for the object parameter.
13421   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13422 
13423   // Build the full argument list for the method call (the implicit object
13424   // parameter is placed at the beginning of the list).
13425   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13426 
13427   bool IsError = false;
13428 
13429   // Initialize the implicit object parameter.
13430   ExprResult ObjRes =
13431     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13432                                         Best->FoundDecl, Method);
13433   if (ObjRes.isInvalid())
13434     IsError = true;
13435   else
13436     Object = ObjRes;
13437   MethodArgs[0] = Object.get();
13438 
13439   // Check the argument types.
13440   for (unsigned i = 0; i != NumParams; i++) {
13441     Expr *Arg;
13442     if (i < Args.size()) {
13443       Arg = Args[i];
13444 
13445       // Pass the argument.
13446 
13447       ExprResult InputInit
13448         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13449                                                     Context,
13450                                                     Method->getParamDecl(i)),
13451                                     SourceLocation(), Arg);
13452 
13453       IsError |= InputInit.isInvalid();
13454       Arg = InputInit.getAs<Expr>();
13455     } else {
13456       ExprResult DefArg
13457         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13458       if (DefArg.isInvalid()) {
13459         IsError = true;
13460         break;
13461       }
13462 
13463       Arg = DefArg.getAs<Expr>();
13464     }
13465 
13466     MethodArgs[i + 1] = Arg;
13467   }
13468 
13469   // If this is a variadic call, handle args passed through "...".
13470   if (Proto->isVariadic()) {
13471     // Promote the arguments (C99 6.5.2.2p7).
13472     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13473       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13474                                                         nullptr);
13475       IsError |= Arg.isInvalid();
13476       MethodArgs[i + 1] = Arg.get();
13477     }
13478   }
13479 
13480   if (IsError)
13481     return true;
13482 
13483   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13484 
13485   // Once we've built TheCall, all of the expressions are properly owned.
13486   QualType ResultTy = Method->getReturnType();
13487   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13488   ResultTy = ResultTy.getNonLValueExprType(Context);
13489 
13490   CXXOperatorCallExpr *TheCall =
13491       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
13492                                   ResultTy, VK, RParenLoc, FPOptions());
13493 
13494   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13495     return true;
13496 
13497   if (CheckFunctionCall(Method, TheCall, Proto))
13498     return true;
13499 
13500   return MaybeBindToTemporary(TheCall);
13501 }
13502 
13503 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13504 ///  (if one exists), where @c Base is an expression of class type and
13505 /// @c Member is the name of the member we're trying to find.
13506 ExprResult
13507 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13508                                bool *NoArrowOperatorFound) {
13509   assert(Base->getType()->isRecordType() &&
13510          "left-hand side must have class type");
13511 
13512   if (checkPlaceholderForOverload(*this, Base))
13513     return ExprError();
13514 
13515   SourceLocation Loc = Base->getExprLoc();
13516 
13517   // C++ [over.ref]p1:
13518   //
13519   //   [...] An expression x->m is interpreted as (x.operator->())->m
13520   //   for a class object x of type T if T::operator->() exists and if
13521   //   the operator is selected as the best match function by the
13522   //   overload resolution mechanism (13.3).
13523   DeclarationName OpName =
13524     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13525   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13526   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13527 
13528   if (RequireCompleteType(Loc, Base->getType(),
13529                           diag::err_typecheck_incomplete_tag, Base))
13530     return ExprError();
13531 
13532   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13533   LookupQualifiedName(R, BaseRecord->getDecl());
13534   R.suppressDiagnostics();
13535 
13536   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13537        Oper != OperEnd; ++Oper) {
13538     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13539                        None, CandidateSet, /*SuppressUserConversion=*/false);
13540   }
13541 
13542   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13543 
13544   // Perform overload resolution.
13545   OverloadCandidateSet::iterator Best;
13546   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13547   case OR_Success:
13548     // Overload resolution succeeded; we'll build the call below.
13549     break;
13550 
13551   case OR_No_Viable_Function: {
13552     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
13553     if (CandidateSet.empty()) {
13554       QualType BaseType = Base->getType();
13555       if (NoArrowOperatorFound) {
13556         // Report this specific error to the caller instead of emitting a
13557         // diagnostic, as requested.
13558         *NoArrowOperatorFound = true;
13559         return ExprError();
13560       }
13561       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13562         << BaseType << Base->getSourceRange();
13563       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13564         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13565           << FixItHint::CreateReplacement(OpLoc, ".");
13566       }
13567     } else
13568       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13569         << "operator->" << Base->getSourceRange();
13570     CandidateSet.NoteCandidates(*this, Base, Cands);
13571     return ExprError();
13572   }
13573   case OR_Ambiguous:
13574     CandidateSet.NoteCandidates(
13575         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
13576                                        << "->" << Base->getType()
13577                                        << Base->getSourceRange()),
13578         *this, OCD_ViableCandidates, Base);
13579     return ExprError();
13580 
13581   case OR_Deleted:
13582     CandidateSet.NoteCandidates(
13583         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13584                                        << "->" << Base->getSourceRange()),
13585         *this, OCD_AllCandidates, Base);
13586     return ExprError();
13587   }
13588 
13589   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13590 
13591   // Convert the object parameter.
13592   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13593   ExprResult BaseResult =
13594     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13595                                         Best->FoundDecl, Method);
13596   if (BaseResult.isInvalid())
13597     return ExprError();
13598   Base = BaseResult.get();
13599 
13600   // Build the operator call.
13601   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13602                                             Base, HadMultipleCandidates, OpLoc);
13603   if (FnExpr.isInvalid())
13604     return ExprError();
13605 
13606   QualType ResultTy = Method->getReturnType();
13607   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13608   ResultTy = ResultTy.getNonLValueExprType(Context);
13609   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13610       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
13611 
13612   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13613     return ExprError();
13614 
13615   if (CheckFunctionCall(Method, TheCall,
13616                         Method->getType()->castAs<FunctionProtoType>()))
13617     return ExprError();
13618 
13619   return MaybeBindToTemporary(TheCall);
13620 }
13621 
13622 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13623 /// a literal operator described by the provided lookup results.
13624 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13625                                           DeclarationNameInfo &SuffixInfo,
13626                                           ArrayRef<Expr*> Args,
13627                                           SourceLocation LitEndLoc,
13628                                        TemplateArgumentListInfo *TemplateArgs) {
13629   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13630 
13631   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13632                                     OverloadCandidateSet::CSK_Normal);
13633   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13634                         /*SuppressUserConversions=*/true);
13635 
13636   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13637 
13638   // Perform overload resolution. This will usually be trivial, but might need
13639   // to perform substitutions for a literal operator template.
13640   OverloadCandidateSet::iterator Best;
13641   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13642   case OR_Success:
13643   case OR_Deleted:
13644     break;
13645 
13646   case OR_No_Viable_Function:
13647     CandidateSet.NoteCandidates(
13648         PartialDiagnosticAt(UDSuffixLoc,
13649                             PDiag(diag::err_ovl_no_viable_function_in_call)
13650                                 << R.getLookupName()),
13651         *this, OCD_AllCandidates, Args);
13652     return ExprError();
13653 
13654   case OR_Ambiguous:
13655     CandidateSet.NoteCandidates(
13656         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
13657                                                 << R.getLookupName()),
13658         *this, OCD_ViableCandidates, Args);
13659     return ExprError();
13660   }
13661 
13662   FunctionDecl *FD = Best->Function;
13663   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13664                                         nullptr, HadMultipleCandidates,
13665                                         SuffixInfo.getLoc(),
13666                                         SuffixInfo.getInfo());
13667   if (Fn.isInvalid())
13668     return true;
13669 
13670   // Check the argument types. This should almost always be a no-op, except
13671   // that array-to-pointer decay is applied to string literals.
13672   Expr *ConvArgs[2];
13673   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13674     ExprResult InputInit = PerformCopyInitialization(
13675       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13676       SourceLocation(), Args[ArgIdx]);
13677     if (InputInit.isInvalid())
13678       return true;
13679     ConvArgs[ArgIdx] = InputInit.get();
13680   }
13681 
13682   QualType ResultTy = FD->getReturnType();
13683   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13684   ResultTy = ResultTy.getNonLValueExprType(Context);
13685 
13686   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
13687       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
13688       VK, LitEndLoc, UDSuffixLoc);
13689 
13690   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13691     return ExprError();
13692 
13693   if (CheckFunctionCall(FD, UDL, nullptr))
13694     return ExprError();
13695 
13696   return MaybeBindToTemporary(UDL);
13697 }
13698 
13699 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13700 /// given LookupResult is non-empty, it is assumed to describe a member which
13701 /// will be invoked. Otherwise, the function will be found via argument
13702 /// dependent lookup.
13703 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13704 /// otherwise CallExpr is set to ExprError() and some non-success value
13705 /// is returned.
13706 Sema::ForRangeStatus
13707 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13708                                 SourceLocation RangeLoc,
13709                                 const DeclarationNameInfo &NameInfo,
13710                                 LookupResult &MemberLookup,
13711                                 OverloadCandidateSet *CandidateSet,
13712                                 Expr *Range, ExprResult *CallExpr) {
13713   Scope *S = nullptr;
13714 
13715   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13716   if (!MemberLookup.empty()) {
13717     ExprResult MemberRef =
13718         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13719                                  /*IsPtr=*/false, CXXScopeSpec(),
13720                                  /*TemplateKWLoc=*/SourceLocation(),
13721                                  /*FirstQualifierInScope=*/nullptr,
13722                                  MemberLookup,
13723                                  /*TemplateArgs=*/nullptr, S);
13724     if (MemberRef.isInvalid()) {
13725       *CallExpr = ExprError();
13726       return FRS_DiagnosticIssued;
13727     }
13728     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13729     if (CallExpr->isInvalid()) {
13730       *CallExpr = ExprError();
13731       return FRS_DiagnosticIssued;
13732     }
13733   } else {
13734     UnresolvedSet<0> FoundNames;
13735     UnresolvedLookupExpr *Fn =
13736       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13737                                    NestedNameSpecifierLoc(), NameInfo,
13738                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13739                                    FoundNames.begin(), FoundNames.end());
13740 
13741     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13742                                                     CandidateSet, CallExpr);
13743     if (CandidateSet->empty() || CandidateSetError) {
13744       *CallExpr = ExprError();
13745       return FRS_NoViableFunction;
13746     }
13747     OverloadCandidateSet::iterator Best;
13748     OverloadingResult OverloadResult =
13749         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13750 
13751     if (OverloadResult == OR_No_Viable_Function) {
13752       *CallExpr = ExprError();
13753       return FRS_NoViableFunction;
13754     }
13755     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13756                                          Loc, nullptr, CandidateSet, &Best,
13757                                          OverloadResult,
13758                                          /*AllowTypoCorrection=*/false);
13759     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13760       *CallExpr = ExprError();
13761       return FRS_DiagnosticIssued;
13762     }
13763   }
13764   return FRS_Success;
13765 }
13766 
13767 
13768 /// FixOverloadedFunctionReference - E is an expression that refers to
13769 /// a C++ overloaded function (possibly with some parentheses and
13770 /// perhaps a '&' around it). We have resolved the overloaded function
13771 /// to the function declaration Fn, so patch up the expression E to
13772 /// refer (possibly indirectly) to Fn. Returns the new expr.
13773 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13774                                            FunctionDecl *Fn) {
13775   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13776     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13777                                                    Found, Fn);
13778     if (SubExpr == PE->getSubExpr())
13779       return PE;
13780 
13781     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13782   }
13783 
13784   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13785     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13786                                                    Found, Fn);
13787     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13788                                SubExpr->getType()) &&
13789            "Implicit cast type cannot be determined from overload");
13790     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13791     if (SubExpr == ICE->getSubExpr())
13792       return ICE;
13793 
13794     return ImplicitCastExpr::Create(Context, ICE->getType(),
13795                                     ICE->getCastKind(),
13796                                     SubExpr, nullptr,
13797                                     ICE->getValueKind());
13798   }
13799 
13800   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13801     if (!GSE->isResultDependent()) {
13802       Expr *SubExpr =
13803           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13804       if (SubExpr == GSE->getResultExpr())
13805         return GSE;
13806 
13807       // Replace the resulting type information before rebuilding the generic
13808       // selection expression.
13809       ArrayRef<Expr *> A = GSE->getAssocExprs();
13810       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13811       unsigned ResultIdx = GSE->getResultIndex();
13812       AssocExprs[ResultIdx] = SubExpr;
13813 
13814       return GenericSelectionExpr::Create(
13815           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13816           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13817           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13818           ResultIdx);
13819     }
13820     // Rather than fall through to the unreachable, return the original generic
13821     // selection expression.
13822     return GSE;
13823   }
13824 
13825   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13826     assert(UnOp->getOpcode() == UO_AddrOf &&
13827            "Can only take the address of an overloaded function");
13828     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13829       if (Method->isStatic()) {
13830         // Do nothing: static member functions aren't any different
13831         // from non-member functions.
13832       } else {
13833         // Fix the subexpression, which really has to be an
13834         // UnresolvedLookupExpr holding an overloaded member function
13835         // or template.
13836         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13837                                                        Found, Fn);
13838         if (SubExpr == UnOp->getSubExpr())
13839           return UnOp;
13840 
13841         assert(isa<DeclRefExpr>(SubExpr)
13842                && "fixed to something other than a decl ref");
13843         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13844                && "fixed to a member ref with no nested name qualifier");
13845 
13846         // We have taken the address of a pointer to member
13847         // function. Perform the computation here so that we get the
13848         // appropriate pointer to member type.
13849         QualType ClassType
13850           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13851         QualType MemPtrType
13852           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13853         // Under the MS ABI, lock down the inheritance model now.
13854         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13855           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13856 
13857         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13858                                            VK_RValue, OK_Ordinary,
13859                                            UnOp->getOperatorLoc(), false);
13860       }
13861     }
13862     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13863                                                    Found, Fn);
13864     if (SubExpr == UnOp->getSubExpr())
13865       return UnOp;
13866 
13867     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13868                                      Context.getPointerType(SubExpr->getType()),
13869                                        VK_RValue, OK_Ordinary,
13870                                        UnOp->getOperatorLoc(), false);
13871   }
13872 
13873   // C++ [except.spec]p17:
13874   //   An exception-specification is considered to be needed when:
13875   //   - in an expression the function is the unique lookup result or the
13876   //     selected member of a set of overloaded functions
13877   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13878     ResolveExceptionSpec(E->getExprLoc(), FPT);
13879 
13880   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13881     // FIXME: avoid copy.
13882     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13883     if (ULE->hasExplicitTemplateArgs()) {
13884       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13885       TemplateArgs = &TemplateArgsBuffer;
13886     }
13887 
13888     DeclRefExpr *DRE =
13889         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
13890                          ULE->getQualifierLoc(), Found.getDecl(),
13891                          ULE->getTemplateKeywordLoc(), TemplateArgs);
13892     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13893     return DRE;
13894   }
13895 
13896   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13897     // FIXME: avoid copy.
13898     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13899     if (MemExpr->hasExplicitTemplateArgs()) {
13900       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13901       TemplateArgs = &TemplateArgsBuffer;
13902     }
13903 
13904     Expr *Base;
13905 
13906     // If we're filling in a static method where we used to have an
13907     // implicit member access, rewrite to a simple decl ref.
13908     if (MemExpr->isImplicitAccess()) {
13909       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13910         DeclRefExpr *DRE = BuildDeclRefExpr(
13911             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
13912             MemExpr->getQualifierLoc(), Found.getDecl(),
13913             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
13914         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13915         return DRE;
13916       } else {
13917         SourceLocation Loc = MemExpr->getMemberLoc();
13918         if (MemExpr->getQualifier())
13919           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13920         Base =
13921             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
13922       }
13923     } else
13924       Base = MemExpr->getBase();
13925 
13926     ExprValueKind valueKind;
13927     QualType type;
13928     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13929       valueKind = VK_LValue;
13930       type = Fn->getType();
13931     } else {
13932       valueKind = VK_RValue;
13933       type = Context.BoundMemberTy;
13934     }
13935 
13936     return BuildMemberExpr(
13937         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13938         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13939         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
13940         type, valueKind, OK_Ordinary, TemplateArgs);
13941   }
13942 
13943   llvm_unreachable("Invalid reference to overloaded function");
13944 }
13945 
13946 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13947                                                 DeclAccessPair Found,
13948                                                 FunctionDecl *Fn) {
13949   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13950 }
13951