1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include <algorithm>
37 #include <cstdlib>
38 
39 using namespace clang;
40 using namespace sema;
41 
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44     return P->hasAttr<PassObjectSizeAttr>();
45   });
46 }
47 
48 /// A convenience routine for creating a decayed reference to a function.
49 static ExprResult
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51                       const Expr *Base, bool HadMultipleCandidates,
52                       SourceLocation Loc = SourceLocation(),
53                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55     return ExprError();
56   // If FoundDecl is different from Fn (such as if one is a template
57   // and the other a specialization), make sure DiagnoseUseOfDecl is
58   // called on both.
59   // FIXME: This would be more comprehensively addressed by modifying
60   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61   // being used.
62   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63     return ExprError();
64   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65     S.ResolveExceptionSpec(Loc, FPT);
66   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67                                                  VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70 
71   S.MarkDeclRefReferenced(DRE, Base);
72   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73                              CK_FunctionToPointerDecay);
74 }
75 
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77                                  bool InOverloadResolution,
78                                  StandardConversionSequence &SCS,
79                                  bool CStyle,
80                                  bool AllowObjCWritebackConversion);
81 
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83                                                  QualType &ToType,
84                                                  bool InOverloadResolution,
85                                                  StandardConversionSequence &SCS,
86                                                  bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89                         UserDefinedConversionSequence& User,
90                         OverloadCandidateSet& Conversions,
91                         bool AllowExplicit,
92                         bool AllowObjCConversionOnExplicit);
93 
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97                                    const StandardConversionSequence& SCS1,
98                                    const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109 
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113   static const ImplicitConversionRank
114     Rank[(int)ICK_Num_Conversion_Kinds] = {
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Promotion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_OCL_Scalar_Widening,
135     ICR_Complex_Real_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Writeback_Conversion,
139     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140                      // it was omitted by the patch that added
141                      // ICK_Zero_Event_Conversion
142     ICR_C_Conversion,
143     ICR_C_Conversion_Extension
144   };
145   return Rank[(int)Kind];
146 }
147 
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152     "No conversion",
153     "Lvalue-to-rvalue",
154     "Array-to-pointer",
155     "Function-to-pointer",
156     "Function pointer conversion",
157     "Qualification",
158     "Integral promotion",
159     "Floating point promotion",
160     "Complex promotion",
161     "Integral conversion",
162     "Floating conversion",
163     "Complex conversion",
164     "Floating-integral conversion",
165     "Pointer conversion",
166     "Pointer-to-member conversion",
167     "Boolean conversion",
168     "Compatible-types conversion",
169     "Derived-to-base conversion",
170     "Vector conversion",
171     "Vector splat",
172     "Complex-real conversion",
173     "Block Pointer conversion",
174     "Transparent Union Conversion",
175     "Writeback conversion",
176     "OpenCL Zero Event Conversion",
177     "C specific type conversion",
178     "Incompatible pointer conversion"
179   };
180   return Name[Kind];
181 }
182 
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186   First = ICK_Identity;
187   Second = ICK_Identity;
188   Third = ICK_Identity;
189   DeprecatedStringLiteralToCharPtr = false;
190   QualificationIncludesObjCLifetime = false;
191   ReferenceBinding = false;
192   DirectBinding = false;
193   IsLvalueReference = true;
194   BindsToFunctionLvalue = false;
195   BindsToRvalue = false;
196   BindsImplicitObjectArgumentWithoutRefQualifier = false;
197   ObjCLifetimeConversionBinding = false;
198   CopyConstructor = nullptr;
199 }
200 
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205   ImplicitConversionRank Rank = ICR_Exact_Match;
206   if  (GetConversionRank(First) > Rank)
207     Rank = GetConversionRank(First);
208   if  (GetConversionRank(Second) > Rank)
209     Rank = GetConversionRank(Second);
210   if  (GetConversionRank(Third) > Rank)
211     Rank = GetConversionRank(Third);
212   return Rank;
213 }
214 
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220   // Note that FromType has not necessarily been transformed by the
221   // array-to-pointer or function-to-pointer implicit conversions, so
222   // check for their presence as well as checking whether FromType is
223   // a pointer.
224   if (getToType(1)->isBooleanType() &&
225       (getFromType()->isPointerType() ||
226        getFromType()->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 NarrowingKind
292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293                                              const Expr *Converted,
294                                              APValue &ConstantValue,
295                                              QualType &ConstantType) 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       llvm::APSInt IntConstantValue;
333       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334       assert(Initializer && "Unknown conversion expression");
335 
336       // If it's value-dependent, we can't tell whether it's narrowing.
337       if (Initializer->isValueDependent())
338         return NK_Dependent_Narrowing;
339 
340       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
341         // Convert the integer to the floating type.
342         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
343         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
344                                 llvm::APFloat::rmNearestTiesToEven);
345         // And back.
346         llvm::APSInt ConvertedValue = IntConstantValue;
347         bool ignored;
348         Result.convertToInteger(ConvertedValue,
349                                 llvm::APFloat::rmTowardZero, &ignored);
350         // If the resulting value is different, this was a narrowing conversion.
351         if (IntConstantValue != ConvertedValue) {
352           ConstantValue = APValue(IntConstantValue);
353           ConstantType = Initializer->getType();
354           return NK_Constant_Narrowing;
355         }
356       } else {
357         // Variables are always narrowings.
358         return NK_Variable_Narrowing;
359       }
360     }
361     return NK_Not_Narrowing;
362 
363   // -- from long double to double or float, or from double to float, except
364   //    where the source is a constant expression and the actual value after
365   //    conversion is within the range of values that can be represented (even
366   //    if it cannot be represented exactly), or
367   case ICK_Floating_Conversion:
368     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
369         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
370       // FromType is larger than ToType.
371       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
372 
373       // If it's value-dependent, we can't tell whether it's narrowing.
374       if (Initializer->isValueDependent())
375         return NK_Dependent_Narrowing;
376 
377       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
378         // Constant!
379         assert(ConstantValue.isFloat());
380         llvm::APFloat FloatVal = ConstantValue.getFloat();
381         // Convert the source value into the target type.
382         bool ignored;
383         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
384           Ctx.getFloatTypeSemantics(ToType),
385           llvm::APFloat::rmNearestTiesToEven, &ignored);
386         // If there was no overflow, the source value is within the range of
387         // values that can be represented.
388         if (ConvertStatus & llvm::APFloat::opOverflow) {
389           ConstantType = Initializer->getType();
390           return NK_Constant_Narrowing;
391         }
392       } else {
393         return NK_Variable_Narrowing;
394       }
395     }
396     return NK_Not_Narrowing;
397 
398   // -- from an integer type or unscoped enumeration type to an integer type
399   //    that cannot represent all the values of the original type, except where
400   //    the source is a constant expression and the actual value after
401   //    conversion will fit into the target type and will produce the original
402   //    value when converted back to the original type.
403   case ICK_Integral_Conversion:
404   IntegralConversion: {
405     assert(FromType->isIntegralOrUnscopedEnumerationType());
406     assert(ToType->isIntegralOrUnscopedEnumerationType());
407     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
408     const unsigned FromWidth = Ctx.getIntWidth(FromType);
409     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
410     const unsigned ToWidth = Ctx.getIntWidth(ToType);
411 
412     if (FromWidth > ToWidth ||
413         (FromWidth == ToWidth && FromSigned != ToSigned) ||
414         (FromSigned && !ToSigned)) {
415       // Not all values of FromType can be represented in ToType.
416       llvm::APSInt InitializerValue;
417       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
418 
419       // If it's value-dependent, we can't tell whether it's narrowing.
420       if (Initializer->isValueDependent())
421         return NK_Dependent_Narrowing;
422 
423       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
424         // Such conversions on variables are always narrowing.
425         return NK_Variable_Narrowing;
426       }
427       bool Narrowing = false;
428       if (FromWidth < ToWidth) {
429         // Negative -> unsigned is narrowing. Otherwise, more bits is never
430         // narrowing.
431         if (InitializerValue.isSigned() && InitializerValue.isNegative())
432           Narrowing = true;
433       } else {
434         // Add a bit to the InitializerValue so we don't have to worry about
435         // signed vs. unsigned comparisons.
436         InitializerValue = InitializerValue.extend(
437           InitializerValue.getBitWidth() + 1);
438         // Convert the initializer to and from the target width and signed-ness.
439         llvm::APSInt ConvertedValue = InitializerValue;
440         ConvertedValue = ConvertedValue.trunc(ToWidth);
441         ConvertedValue.setIsSigned(ToSigned);
442         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
443         ConvertedValue.setIsSigned(InitializerValue.isSigned());
444         // If the result is different, this was a narrowing conversion.
445         if (ConvertedValue != InitializerValue)
446           Narrowing = true;
447       }
448       if (Narrowing) {
449         ConstantType = Initializer->getType();
450         ConstantValue = APValue(InitializerValue);
451         return NK_Constant_Narrowing;
452       }
453     }
454     return NK_Not_Narrowing;
455   }
456 
457   default:
458     // Other kinds of conversions are not narrowings.
459     return NK_Not_Narrowing;
460   }
461 }
462 
463 /// dump - Print this standard conversion sequence to standard
464 /// error. Useful for debugging overloading issues.
465 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
466   raw_ostream &OS = llvm::errs();
467   bool PrintedSomething = false;
468   if (First != ICK_Identity) {
469     OS << GetImplicitConversionName(First);
470     PrintedSomething = true;
471   }
472 
473   if (Second != ICK_Identity) {
474     if (PrintedSomething) {
475       OS << " -> ";
476     }
477     OS << GetImplicitConversionName(Second);
478 
479     if (CopyConstructor) {
480       OS << " (by copy constructor)";
481     } else if (DirectBinding) {
482       OS << " (direct reference binding)";
483     } else if (ReferenceBinding) {
484       OS << " (reference binding)";
485     }
486     PrintedSomething = true;
487   }
488 
489   if (Third != ICK_Identity) {
490     if (PrintedSomething) {
491       OS << " -> ";
492     }
493     OS << GetImplicitConversionName(Third);
494     PrintedSomething = true;
495   }
496 
497   if (!PrintedSomething) {
498     OS << "No conversions required";
499   }
500 }
501 
502 /// dump - Print this user-defined conversion sequence to standard
503 /// error. Useful for debugging overloading issues.
504 void UserDefinedConversionSequence::dump() const {
505   raw_ostream &OS = llvm::errs();
506   if (Before.First || Before.Second || Before.Third) {
507     Before.dump();
508     OS << " -> ";
509   }
510   if (ConversionFunction)
511     OS << '\'' << *ConversionFunction << '\'';
512   else
513     OS << "aggregate initialization";
514   if (After.First || After.Second || After.Third) {
515     OS << " -> ";
516     After.dump();
517   }
518 }
519 
520 /// dump - Print this implicit conversion sequence to standard
521 /// error. Useful for debugging overloading issues.
522 void ImplicitConversionSequence::dump() const {
523   raw_ostream &OS = llvm::errs();
524   if (isStdInitializerListElement())
525     OS << "Worst std::initializer_list element conversion: ";
526   switch (ConversionKind) {
527   case StandardConversion:
528     OS << "Standard conversion: ";
529     Standard.dump();
530     break;
531   case UserDefinedConversion:
532     OS << "User-defined conversion: ";
533     UserDefined.dump();
534     break;
535   case EllipsisConversion:
536     OS << "Ellipsis conversion";
537     break;
538   case AmbiguousConversion:
539     OS << "Ambiguous conversion";
540     break;
541   case BadConversion:
542     OS << "Bad conversion";
543     break;
544   }
545 
546   OS << "\n";
547 }
548 
549 void AmbiguousConversionSequence::construct() {
550   new (&conversions()) ConversionSet();
551 }
552 
553 void AmbiguousConversionSequence::destruct() {
554   conversions().~ConversionSet();
555 }
556 
557 void
558 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
559   FromTypePtr = O.FromTypePtr;
560   ToTypePtr = O.ToTypePtr;
561   new (&conversions()) ConversionSet(O.conversions());
562 }
563 
564 namespace {
565   // Structure used by DeductionFailureInfo to store
566   // template argument information.
567   struct DFIArguments {
568     TemplateArgument FirstArg;
569     TemplateArgument SecondArg;
570   };
571   // Structure used by DeductionFailureInfo to store
572   // template parameter and template argument information.
573   struct DFIParamWithArguments : DFIArguments {
574     TemplateParameter Param;
575   };
576   // Structure used by DeductionFailureInfo to store template argument
577   // information and the index of the problematic call argument.
578   struct DFIDeducedMismatchArgs : DFIArguments {
579     TemplateArgumentList *TemplateArgs;
580     unsigned CallArgIndex;
581   };
582 }
583 
584 /// \brief Convert from Sema's representation of template deduction information
585 /// to the form used in overload-candidate information.
586 DeductionFailureInfo
587 clang::MakeDeductionFailureInfo(ASTContext &Context,
588                                 Sema::TemplateDeductionResult TDK,
589                                 TemplateDeductionInfo &Info) {
590   DeductionFailureInfo Result;
591   Result.Result = static_cast<unsigned>(TDK);
592   Result.HasDiagnostic = false;
593   switch (TDK) {
594   case Sema::TDK_Invalid:
595   case Sema::TDK_InstantiationDepth:
596   case Sema::TDK_TooManyArguments:
597   case Sema::TDK_TooFewArguments:
598   case Sema::TDK_MiscellaneousDeductionFailure:
599   case Sema::TDK_CUDATargetMismatch:
600     Result.Data = nullptr;
601     break;
602 
603   case Sema::TDK_Incomplete:
604   case Sema::TDK_InvalidExplicitArguments:
605     Result.Data = Info.Param.getOpaqueValue();
606     break;
607 
608   case Sema::TDK_DeducedMismatch:
609   case Sema::TDK_DeducedMismatchNested: {
610     // FIXME: Should allocate from normal heap so that we can free this later.
611     auto *Saved = new (Context) DFIDeducedMismatchArgs;
612     Saved->FirstArg = Info.FirstArg;
613     Saved->SecondArg = Info.SecondArg;
614     Saved->TemplateArgs = Info.take();
615     Saved->CallArgIndex = Info.CallArgIndex;
616     Result.Data = Saved;
617     break;
618   }
619 
620   case Sema::TDK_NonDeducedMismatch: {
621     // FIXME: Should allocate from normal heap so that we can free this later.
622     DFIArguments *Saved = new (Context) DFIArguments;
623     Saved->FirstArg = Info.FirstArg;
624     Saved->SecondArg = Info.SecondArg;
625     Result.Data = Saved;
626     break;
627   }
628 
629   case Sema::TDK_Inconsistent:
630   case Sema::TDK_Underqualified: {
631     // FIXME: Should allocate from normal heap so that we can free this later.
632     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
633     Saved->Param = Info.Param;
634     Saved->FirstArg = Info.FirstArg;
635     Saved->SecondArg = Info.SecondArg;
636     Result.Data = Saved;
637     break;
638   }
639 
640   case Sema::TDK_SubstitutionFailure:
641     Result.Data = Info.take();
642     if (Info.hasSFINAEDiagnostic()) {
643       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
644           SourceLocation(), PartialDiagnostic::NullDiagnostic());
645       Info.takeSFINAEDiagnostic(*Diag);
646       Result.HasDiagnostic = true;
647     }
648     break;
649 
650   case Sema::TDK_Success:
651   case Sema::TDK_NonDependentConversionFailure:
652     llvm_unreachable("not a deduction failure");
653   }
654 
655   return Result;
656 }
657 
658 void DeductionFailureInfo::Destroy() {
659   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
660   case Sema::TDK_Success:
661   case Sema::TDK_Invalid:
662   case Sema::TDK_InstantiationDepth:
663   case Sema::TDK_Incomplete:
664   case Sema::TDK_TooManyArguments:
665   case Sema::TDK_TooFewArguments:
666   case Sema::TDK_InvalidExplicitArguments:
667   case Sema::TDK_CUDATargetMismatch:
668   case Sema::TDK_NonDependentConversionFailure:
669     break;
670 
671   case Sema::TDK_Inconsistent:
672   case Sema::TDK_Underqualified:
673   case Sema::TDK_DeducedMismatch:
674   case Sema::TDK_DeducedMismatchNested:
675   case Sema::TDK_NonDeducedMismatch:
676     // FIXME: Destroy the data?
677     Data = nullptr;
678     break;
679 
680   case Sema::TDK_SubstitutionFailure:
681     // FIXME: Destroy the template argument list?
682     Data = nullptr;
683     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
684       Diag->~PartialDiagnosticAt();
685       HasDiagnostic = false;
686     }
687     break;
688 
689   // Unhandled
690   case Sema::TDK_MiscellaneousDeductionFailure:
691     break;
692   }
693 }
694 
695 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
696   if (HasDiagnostic)
697     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
698   return nullptr;
699 }
700 
701 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
702   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
703   case Sema::TDK_Success:
704   case Sema::TDK_Invalid:
705   case Sema::TDK_InstantiationDepth:
706   case Sema::TDK_TooManyArguments:
707   case Sema::TDK_TooFewArguments:
708   case Sema::TDK_SubstitutionFailure:
709   case Sema::TDK_DeducedMismatch:
710   case Sema::TDK_DeducedMismatchNested:
711   case Sema::TDK_NonDeducedMismatch:
712   case Sema::TDK_CUDATargetMismatch:
713   case Sema::TDK_NonDependentConversionFailure:
714     return TemplateParameter();
715 
716   case Sema::TDK_Incomplete:
717   case Sema::TDK_InvalidExplicitArguments:
718     return TemplateParameter::getFromOpaqueValue(Data);
719 
720   case Sema::TDK_Inconsistent:
721   case Sema::TDK_Underqualified:
722     return static_cast<DFIParamWithArguments*>(Data)->Param;
723 
724   // Unhandled
725   case Sema::TDK_MiscellaneousDeductionFailure:
726     break;
727   }
728 
729   return TemplateParameter();
730 }
731 
732 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
733   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
734   case Sema::TDK_Success:
735   case Sema::TDK_Invalid:
736   case Sema::TDK_InstantiationDepth:
737   case Sema::TDK_TooManyArguments:
738   case Sema::TDK_TooFewArguments:
739   case Sema::TDK_Incomplete:
740   case Sema::TDK_InvalidExplicitArguments:
741   case Sema::TDK_Inconsistent:
742   case Sema::TDK_Underqualified:
743   case Sema::TDK_NonDeducedMismatch:
744   case Sema::TDK_CUDATargetMismatch:
745   case Sema::TDK_NonDependentConversionFailure:
746     return nullptr;
747 
748   case Sema::TDK_DeducedMismatch:
749   case Sema::TDK_DeducedMismatchNested:
750     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
751 
752   case Sema::TDK_SubstitutionFailure:
753     return static_cast<TemplateArgumentList*>(Data);
754 
755   // Unhandled
756   case Sema::TDK_MiscellaneousDeductionFailure:
757     break;
758   }
759 
760   return nullptr;
761 }
762 
763 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
764   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
765   case Sema::TDK_Success:
766   case Sema::TDK_Invalid:
767   case Sema::TDK_InstantiationDepth:
768   case Sema::TDK_Incomplete:
769   case Sema::TDK_TooManyArguments:
770   case Sema::TDK_TooFewArguments:
771   case Sema::TDK_InvalidExplicitArguments:
772   case Sema::TDK_SubstitutionFailure:
773   case Sema::TDK_CUDATargetMismatch:
774   case Sema::TDK_NonDependentConversionFailure:
775     return nullptr;
776 
777   case Sema::TDK_Inconsistent:
778   case Sema::TDK_Underqualified:
779   case Sema::TDK_DeducedMismatch:
780   case Sema::TDK_DeducedMismatchNested:
781   case Sema::TDK_NonDeducedMismatch:
782     return &static_cast<DFIArguments*>(Data)->FirstArg;
783 
784   // Unhandled
785   case Sema::TDK_MiscellaneousDeductionFailure:
786     break;
787   }
788 
789   return nullptr;
790 }
791 
792 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
793   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
794   case Sema::TDK_Success:
795   case Sema::TDK_Invalid:
796   case Sema::TDK_InstantiationDepth:
797   case Sema::TDK_Incomplete:
798   case Sema::TDK_TooManyArguments:
799   case Sema::TDK_TooFewArguments:
800   case Sema::TDK_InvalidExplicitArguments:
801   case Sema::TDK_SubstitutionFailure:
802   case Sema::TDK_CUDATargetMismatch:
803   case Sema::TDK_NonDependentConversionFailure:
804     return nullptr;
805 
806   case Sema::TDK_Inconsistent:
807   case Sema::TDK_Underqualified:
808   case Sema::TDK_DeducedMismatch:
809   case Sema::TDK_DeducedMismatchNested:
810   case Sema::TDK_NonDeducedMismatch:
811     return &static_cast<DFIArguments*>(Data)->SecondArg;
812 
813   // Unhandled
814   case Sema::TDK_MiscellaneousDeductionFailure:
815     break;
816   }
817 
818   return nullptr;
819 }
820 
821 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
822   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
823   case Sema::TDK_DeducedMismatch:
824   case Sema::TDK_DeducedMismatchNested:
825     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
826 
827   default:
828     return llvm::None;
829   }
830 }
831 
832 void OverloadCandidateSet::destroyCandidates() {
833   for (iterator i = begin(), e = end(); i != e; ++i) {
834     for (auto &C : i->Conversions)
835       C.~ImplicitConversionSequence();
836     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
837       i->DeductionFailure.Destroy();
838   }
839 }
840 
841 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
842   destroyCandidates();
843   SlabAllocator.Reset();
844   NumInlineBytesUsed = 0;
845   Candidates.clear();
846   Functions.clear();
847   Kind = CSK;
848 }
849 
850 namespace {
851   class UnbridgedCastsSet {
852     struct Entry {
853       Expr **Addr;
854       Expr *Saved;
855     };
856     SmallVector<Entry, 2> Entries;
857 
858   public:
859     void save(Sema &S, Expr *&E) {
860       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
861       Entry entry = { &E, E };
862       Entries.push_back(entry);
863       E = S.stripARCUnbridgedCast(E);
864     }
865 
866     void restore() {
867       for (SmallVectorImpl<Entry>::iterator
868              i = Entries.begin(), e = Entries.end(); i != e; ++i)
869         *i->Addr = i->Saved;
870     }
871   };
872 }
873 
874 /// checkPlaceholderForOverload - Do any interesting placeholder-like
875 /// preprocessing on the given expression.
876 ///
877 /// \param unbridgedCasts a collection to which to add unbridged casts;
878 ///   without this, they will be immediately diagnosed as errors
879 ///
880 /// Return true on unrecoverable error.
881 static bool
882 checkPlaceholderForOverload(Sema &S, Expr *&E,
883                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
884   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
885     // We can't handle overloaded expressions here because overload
886     // resolution might reasonably tweak them.
887     if (placeholder->getKind() == BuiltinType::Overload) return false;
888 
889     // If the context potentially accepts unbridged ARC casts, strip
890     // the unbridged cast and add it to the collection for later restoration.
891     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
892         unbridgedCasts) {
893       unbridgedCasts->save(S, E);
894       return false;
895     }
896 
897     // Go ahead and check everything else.
898     ExprResult result = S.CheckPlaceholderExpr(E);
899     if (result.isInvalid())
900       return true;
901 
902     E = result.get();
903     return false;
904   }
905 
906   // Nothing to do.
907   return false;
908 }
909 
910 /// checkArgPlaceholdersForOverload - Check a set of call operands for
911 /// placeholders.
912 static bool checkArgPlaceholdersForOverload(Sema &S,
913                                             MultiExprArg Args,
914                                             UnbridgedCastsSet &unbridged) {
915   for (unsigned i = 0, e = Args.size(); i != e; ++i)
916     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
917       return true;
918 
919   return false;
920 }
921 
922 /// Determine whether the given New declaration is an overload of the
923 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
924 /// New and Old cannot be overloaded, e.g., if New has the same signature as
925 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
926 /// functions (or function templates) at all. When it does return Ovl_Match or
927 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
928 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
929 /// declaration.
930 ///
931 /// Example: Given the following input:
932 ///
933 ///   void f(int, float); // #1
934 ///   void f(int, int); // #2
935 ///   int f(int, int); // #3
936 ///
937 /// When we process #1, there is no previous declaration of "f", so IsOverload
938 /// will not be used.
939 ///
940 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
941 /// the parameter types, we see that #1 and #2 are overloaded (since they have
942 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
943 /// unchanged.
944 ///
945 /// When we process #3, Old is an overload set containing #1 and #2. We compare
946 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
947 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
948 /// functions are not part of the signature), IsOverload returns Ovl_Match and
949 /// MatchedDecl will be set to point to the FunctionDecl for #2.
950 ///
951 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
952 /// by a using declaration. The rules for whether to hide shadow declarations
953 /// ignore some properties which otherwise figure into a function template's
954 /// signature.
955 Sema::OverloadKind
956 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
957                     NamedDecl *&Match, bool NewIsUsingDecl) {
958   for (LookupResult::iterator I = Old.begin(), E = Old.end();
959          I != E; ++I) {
960     NamedDecl *OldD = *I;
961 
962     bool OldIsUsingDecl = false;
963     if (isa<UsingShadowDecl>(OldD)) {
964       OldIsUsingDecl = true;
965 
966       // We can always introduce two using declarations into the same
967       // context, even if they have identical signatures.
968       if (NewIsUsingDecl) continue;
969 
970       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
971     }
972 
973     // A using-declaration does not conflict with another declaration
974     // if one of them is hidden.
975     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
976       continue;
977 
978     // If either declaration was introduced by a using declaration,
979     // we'll need to use slightly different rules for matching.
980     // Essentially, these rules are the normal rules, except that
981     // function templates hide function templates with different
982     // return types or template parameter lists.
983     bool UseMemberUsingDeclRules =
984       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
985       !New->getFriendObjectKind();
986 
987     if (FunctionDecl *OldF = OldD->getAsFunction()) {
988       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
989         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
990           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
991           continue;
992         }
993 
994         if (!isa<FunctionTemplateDecl>(OldD) &&
995             !shouldLinkPossiblyHiddenDecl(*I, New))
996           continue;
997 
998         Match = *I;
999         return Ovl_Match;
1000       }
1001 
1002       // Builtins that have custom typechecking or have a reference should
1003       // not be overloadable or redeclarable.
1004       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1005         Match = *I;
1006         return Ovl_NonFunction;
1007       }
1008     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1009       // We can overload with these, which can show up when doing
1010       // redeclaration checks for UsingDecls.
1011       assert(Old.getLookupKind() == LookupUsingDeclName);
1012     } else if (isa<TagDecl>(OldD)) {
1013       // We can always overload with tags by hiding them.
1014     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1015       // Optimistically assume that an unresolved using decl will
1016       // overload; if it doesn't, we'll have to diagnose during
1017       // template instantiation.
1018       //
1019       // Exception: if the scope is dependent and this is not a class
1020       // member, the using declaration can only introduce an enumerator.
1021       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1022         Match = *I;
1023         return Ovl_NonFunction;
1024       }
1025     } else {
1026       // (C++ 13p1):
1027       //   Only function declarations can be overloaded; object and type
1028       //   declarations cannot be overloaded.
1029       Match = *I;
1030       return Ovl_NonFunction;
1031     }
1032   }
1033 
1034   return Ovl_Overload;
1035 }
1036 
1037 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1038                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1039   // C++ [basic.start.main]p2: This function shall not be overloaded.
1040   if (New->isMain())
1041     return false;
1042 
1043   // MSVCRT user defined entry points cannot be overloaded.
1044   if (New->isMSVCRTEntryPoint())
1045     return false;
1046 
1047   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1048   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1049 
1050   // C++ [temp.fct]p2:
1051   //   A function template can be overloaded with other function templates
1052   //   and with normal (non-template) functions.
1053   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1054     return true;
1055 
1056   // Is the function New an overload of the function Old?
1057   QualType OldQType = Context.getCanonicalType(Old->getType());
1058   QualType NewQType = Context.getCanonicalType(New->getType());
1059 
1060   // Compare the signatures (C++ 1.3.10) of the two functions to
1061   // determine whether they are overloads. If we find any mismatch
1062   // in the signature, they are overloads.
1063 
1064   // If either of these functions is a K&R-style function (no
1065   // prototype), then we consider them to have matching signatures.
1066   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1067       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1068     return false;
1069 
1070   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1071   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1072 
1073   // The signature of a function includes the types of its
1074   // parameters (C++ 1.3.10), which includes the presence or absence
1075   // of the ellipsis; see C++ DR 357).
1076   if (OldQType != NewQType &&
1077       (OldType->getNumParams() != NewType->getNumParams() ||
1078        OldType->isVariadic() != NewType->isVariadic() ||
1079        !FunctionParamTypesAreEqual(OldType, NewType)))
1080     return true;
1081 
1082   // C++ [temp.over.link]p4:
1083   //   The signature of a function template consists of its function
1084   //   signature, its return type and its template parameter list. The names
1085   //   of the template parameters are significant only for establishing the
1086   //   relationship between the template parameters and the rest of the
1087   //   signature.
1088   //
1089   // We check the return type and template parameter lists for function
1090   // templates first; the remaining checks follow.
1091   //
1092   // However, we don't consider either of these when deciding whether
1093   // a member introduced by a shadow declaration is hidden.
1094   if (!UseMemberUsingDeclRules && NewTemplate &&
1095       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1096                                        OldTemplate->getTemplateParameters(),
1097                                        false, TPL_TemplateMatch) ||
1098        OldType->getReturnType() != NewType->getReturnType()))
1099     return true;
1100 
1101   // If the function is a class member, its signature includes the
1102   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1103   //
1104   // As part of this, also check whether one of the member functions
1105   // is static, in which case they are not overloads (C++
1106   // 13.1p2). While not part of the definition of the signature,
1107   // this check is important to determine whether these functions
1108   // can be overloaded.
1109   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1110   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1111   if (OldMethod && NewMethod &&
1112       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1113     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1114       if (!UseMemberUsingDeclRules &&
1115           (OldMethod->getRefQualifier() == RQ_None ||
1116            NewMethod->getRefQualifier() == RQ_None)) {
1117         // C++0x [over.load]p2:
1118         //   - Member function declarations with the same name and the same
1119         //     parameter-type-list as well as member function template
1120         //     declarations with the same name, the same parameter-type-list, and
1121         //     the same template parameter lists cannot be overloaded if any of
1122         //     them, but not all, have a ref-qualifier (8.3.5).
1123         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1124           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1125         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1126       }
1127       return true;
1128     }
1129 
1130     // We may not have applied the implicit const for a constexpr member
1131     // function yet (because we haven't yet resolved whether this is a static
1132     // or non-static member function). Add it now, on the assumption that this
1133     // is a redeclaration of OldMethod.
1134     unsigned OldQuals = OldMethod->getTypeQualifiers();
1135     unsigned NewQuals = NewMethod->getTypeQualifiers();
1136     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1137         !isa<CXXConstructorDecl>(NewMethod))
1138       NewQuals |= Qualifiers::Const;
1139 
1140     // We do not allow overloading based off of '__restrict'.
1141     OldQuals &= ~Qualifiers::Restrict;
1142     NewQuals &= ~Qualifiers::Restrict;
1143     if (OldQuals != NewQuals)
1144       return true;
1145   }
1146 
1147   // Though pass_object_size is placed on parameters and takes an argument, we
1148   // consider it to be a function-level modifier for the sake of function
1149   // identity. Either the function has one or more parameters with
1150   // pass_object_size or it doesn't.
1151   if (functionHasPassObjectSizeParams(New) !=
1152       functionHasPassObjectSizeParams(Old))
1153     return true;
1154 
1155   // enable_if attributes are an order-sensitive part of the signature.
1156   for (specific_attr_iterator<EnableIfAttr>
1157          NewI = New->specific_attr_begin<EnableIfAttr>(),
1158          NewE = New->specific_attr_end<EnableIfAttr>(),
1159          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1160          OldE = Old->specific_attr_end<EnableIfAttr>();
1161        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1162     if (NewI == NewE || OldI == OldE)
1163       return true;
1164     llvm::FoldingSetNodeID NewID, OldID;
1165     NewI->getCond()->Profile(NewID, Context, true);
1166     OldI->getCond()->Profile(OldID, Context, true);
1167     if (NewID != OldID)
1168       return true;
1169   }
1170 
1171   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1172     // Don't allow overloading of destructors.  (In theory we could, but it
1173     // would be a giant change to clang.)
1174     if (isa<CXXDestructorDecl>(New))
1175       return false;
1176 
1177     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1178                        OldTarget = IdentifyCUDATarget(Old);
1179     if (NewTarget == CFT_InvalidTarget)
1180       return false;
1181 
1182     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1183 
1184     // Allow overloading of functions with same signature and different CUDA
1185     // target attributes.
1186     return NewTarget != OldTarget;
1187   }
1188 
1189   // The signatures match; this is not an overload.
1190   return false;
1191 }
1192 
1193 /// \brief Checks availability of the function depending on the current
1194 /// function context. Inside an unavailable function, unavailability is ignored.
1195 ///
1196 /// \returns true if \arg FD is unavailable and current context is inside
1197 /// an available function, false otherwise.
1198 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1199   if (!FD->isUnavailable())
1200     return false;
1201 
1202   // Walk up the context of the caller.
1203   Decl *C = cast<Decl>(CurContext);
1204   do {
1205     if (C->isUnavailable())
1206       return false;
1207   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1208   return true;
1209 }
1210 
1211 /// \brief Tries a user-defined conversion from From to ToType.
1212 ///
1213 /// Produces an implicit conversion sequence for when a standard conversion
1214 /// is not an option. See TryImplicitConversion for more information.
1215 static ImplicitConversionSequence
1216 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1217                          bool SuppressUserConversions,
1218                          bool AllowExplicit,
1219                          bool InOverloadResolution,
1220                          bool CStyle,
1221                          bool AllowObjCWritebackConversion,
1222                          bool AllowObjCConversionOnExplicit) {
1223   ImplicitConversionSequence ICS;
1224 
1225   if (SuppressUserConversions) {
1226     // We're not in the case above, so there is no conversion that
1227     // we can perform.
1228     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1229     return ICS;
1230   }
1231 
1232   // Attempt user-defined conversion.
1233   OverloadCandidateSet Conversions(From->getExprLoc(),
1234                                    OverloadCandidateSet::CSK_Normal);
1235   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1236                                   Conversions, AllowExplicit,
1237                                   AllowObjCConversionOnExplicit)) {
1238   case OR_Success:
1239   case OR_Deleted:
1240     ICS.setUserDefined();
1241     // C++ [over.ics.user]p4:
1242     //   A conversion of an expression of class type to the same class
1243     //   type is given Exact Match rank, and a conversion of an
1244     //   expression of class type to a base class of that type is
1245     //   given Conversion rank, in spite of the fact that a copy
1246     //   constructor (i.e., a user-defined conversion function) is
1247     //   called for those cases.
1248     if (CXXConstructorDecl *Constructor
1249           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1250       QualType FromCanon
1251         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1252       QualType ToCanon
1253         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1254       if (Constructor->isCopyConstructor() &&
1255           (FromCanon == ToCanon ||
1256            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1257         // Turn this into a "standard" conversion sequence, so that it
1258         // gets ranked with standard conversion sequences.
1259         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1260         ICS.setStandard();
1261         ICS.Standard.setAsIdentityConversion();
1262         ICS.Standard.setFromType(From->getType());
1263         ICS.Standard.setAllToTypes(ToType);
1264         ICS.Standard.CopyConstructor = Constructor;
1265         ICS.Standard.FoundCopyConstructor = Found;
1266         if (ToCanon != FromCanon)
1267           ICS.Standard.Second = ICK_Derived_To_Base;
1268       }
1269     }
1270     break;
1271 
1272   case OR_Ambiguous:
1273     ICS.setAmbiguous();
1274     ICS.Ambiguous.setFromType(From->getType());
1275     ICS.Ambiguous.setToType(ToType);
1276     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1277          Cand != Conversions.end(); ++Cand)
1278       if (Cand->Viable)
1279         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1280     break;
1281 
1282     // Fall through.
1283   case OR_No_Viable_Function:
1284     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1285     break;
1286   }
1287 
1288   return ICS;
1289 }
1290 
1291 /// TryImplicitConversion - Attempt to perform an implicit conversion
1292 /// from the given expression (Expr) to the given type (ToType). This
1293 /// function returns an implicit conversion sequence that can be used
1294 /// to perform the initialization. Given
1295 ///
1296 ///   void f(float f);
1297 ///   void g(int i) { f(i); }
1298 ///
1299 /// this routine would produce an implicit conversion sequence to
1300 /// describe the initialization of f from i, which will be a standard
1301 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1302 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1303 //
1304 /// Note that this routine only determines how the conversion can be
1305 /// performed; it does not actually perform the conversion. As such,
1306 /// it will not produce any diagnostics if no conversion is available,
1307 /// but will instead return an implicit conversion sequence of kind
1308 /// "BadConversion".
1309 ///
1310 /// If @p SuppressUserConversions, then user-defined conversions are
1311 /// not permitted.
1312 /// If @p AllowExplicit, then explicit user-defined conversions are
1313 /// permitted.
1314 ///
1315 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1316 /// writeback conversion, which allows __autoreleasing id* parameters to
1317 /// be initialized with __strong id* or __weak id* arguments.
1318 static ImplicitConversionSequence
1319 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1320                       bool SuppressUserConversions,
1321                       bool AllowExplicit,
1322                       bool InOverloadResolution,
1323                       bool CStyle,
1324                       bool AllowObjCWritebackConversion,
1325                       bool AllowObjCConversionOnExplicit) {
1326   ImplicitConversionSequence ICS;
1327   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1328                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1329     ICS.setStandard();
1330     return ICS;
1331   }
1332 
1333   if (!S.getLangOpts().CPlusPlus) {
1334     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1335     return ICS;
1336   }
1337 
1338   // C++ [over.ics.user]p4:
1339   //   A conversion of an expression of class type to the same class
1340   //   type is given Exact Match rank, and a conversion of an
1341   //   expression of class type to a base class of that type is
1342   //   given Conversion rank, in spite of the fact that a copy/move
1343   //   constructor (i.e., a user-defined conversion function) is
1344   //   called for those cases.
1345   QualType FromType = From->getType();
1346   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1347       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1348        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1349     ICS.setStandard();
1350     ICS.Standard.setAsIdentityConversion();
1351     ICS.Standard.setFromType(FromType);
1352     ICS.Standard.setAllToTypes(ToType);
1353 
1354     // We don't actually check at this point whether there is a valid
1355     // copy/move constructor, since overloading just assumes that it
1356     // exists. When we actually perform initialization, we'll find the
1357     // appropriate constructor to copy the returned object, if needed.
1358     ICS.Standard.CopyConstructor = nullptr;
1359 
1360     // Determine whether this is considered a derived-to-base conversion.
1361     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1362       ICS.Standard.Second = ICK_Derived_To_Base;
1363 
1364     return ICS;
1365   }
1366 
1367   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1368                                   AllowExplicit, InOverloadResolution, CStyle,
1369                                   AllowObjCWritebackConversion,
1370                                   AllowObjCConversionOnExplicit);
1371 }
1372 
1373 ImplicitConversionSequence
1374 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1375                             bool SuppressUserConversions,
1376                             bool AllowExplicit,
1377                             bool InOverloadResolution,
1378                             bool CStyle,
1379                             bool AllowObjCWritebackConversion) {
1380   return ::TryImplicitConversion(*this, From, ToType,
1381                                  SuppressUserConversions, AllowExplicit,
1382                                  InOverloadResolution, CStyle,
1383                                  AllowObjCWritebackConversion,
1384                                  /*AllowObjCConversionOnExplicit=*/false);
1385 }
1386 
1387 /// PerformImplicitConversion - Perform an implicit conversion of the
1388 /// expression From to the type ToType. Returns the
1389 /// converted expression. Flavor is the kind of conversion we're
1390 /// performing, used in the error message. If @p AllowExplicit,
1391 /// explicit user-defined conversions are permitted.
1392 ExprResult
1393 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1394                                 AssignmentAction Action, bool AllowExplicit) {
1395   ImplicitConversionSequence ICS;
1396   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1397 }
1398 
1399 ExprResult
1400 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1401                                 AssignmentAction Action, bool AllowExplicit,
1402                                 ImplicitConversionSequence& ICS) {
1403   if (checkPlaceholderForOverload(*this, From))
1404     return ExprError();
1405 
1406   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1407   bool AllowObjCWritebackConversion
1408     = getLangOpts().ObjCAutoRefCount &&
1409       (Action == AA_Passing || Action == AA_Sending);
1410   if (getLangOpts().ObjC1)
1411     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1412                                       ToType, From->getType(), From);
1413   ICS = ::TryImplicitConversion(*this, From, ToType,
1414                                 /*SuppressUserConversions=*/false,
1415                                 AllowExplicit,
1416                                 /*InOverloadResolution=*/false,
1417                                 /*CStyle=*/false,
1418                                 AllowObjCWritebackConversion,
1419                                 /*AllowObjCConversionOnExplicit=*/false);
1420   return PerformImplicitConversion(From, ToType, ICS, Action);
1421 }
1422 
1423 /// \brief Determine whether the conversion from FromType to ToType is a valid
1424 /// conversion that strips "noexcept" or "noreturn" off the nested function
1425 /// type.
1426 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1427                                 QualType &ResultTy) {
1428   if (Context.hasSameUnqualifiedType(FromType, ToType))
1429     return false;
1430 
1431   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1432   //                    or F(t noexcept) -> F(t)
1433   // where F adds one of the following at most once:
1434   //   - a pointer
1435   //   - a member pointer
1436   //   - a block pointer
1437   // Changes here need matching changes in FindCompositePointerType.
1438   CanQualType CanTo = Context.getCanonicalType(ToType);
1439   CanQualType CanFrom = Context.getCanonicalType(FromType);
1440   Type::TypeClass TyClass = CanTo->getTypeClass();
1441   if (TyClass != CanFrom->getTypeClass()) return false;
1442   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1443     if (TyClass == Type::Pointer) {
1444       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1445       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1446     } else if (TyClass == Type::BlockPointer) {
1447       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1448       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1449     } else if (TyClass == Type::MemberPointer) {
1450       auto ToMPT = CanTo.getAs<MemberPointerType>();
1451       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1452       // A function pointer conversion cannot change the class of the function.
1453       if (ToMPT->getClass() != FromMPT->getClass())
1454         return false;
1455       CanTo = ToMPT->getPointeeType();
1456       CanFrom = FromMPT->getPointeeType();
1457     } else {
1458       return false;
1459     }
1460 
1461     TyClass = CanTo->getTypeClass();
1462     if (TyClass != CanFrom->getTypeClass()) return false;
1463     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1464       return false;
1465   }
1466 
1467   const auto *FromFn = cast<FunctionType>(CanFrom);
1468   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1469 
1470   const auto *ToFn = cast<FunctionType>(CanTo);
1471   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1472 
1473   bool Changed = false;
1474 
1475   // Drop 'noreturn' if not present in target type.
1476   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1477     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1478     Changed = true;
1479   }
1480 
1481   // Drop 'noexcept' if not present in target type.
1482   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1483     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1484     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1485       FromFn = cast<FunctionType>(
1486           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1487                                                    EST_None)
1488                  .getTypePtr());
1489       Changed = true;
1490     }
1491 
1492     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1493     // only if the ExtParameterInfo lists of the two function prototypes can be
1494     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1495     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1496     bool CanUseToFPT, CanUseFromFPT;
1497     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1498                                       CanUseFromFPT, NewParamInfos) &&
1499         CanUseToFPT && !CanUseFromFPT) {
1500       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1501       ExtInfo.ExtParameterInfos =
1502           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1503       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1504                                             FromFPT->getParamTypes(), ExtInfo);
1505       FromFn = QT->getAs<FunctionType>();
1506       Changed = true;
1507     }
1508   }
1509 
1510   if (!Changed)
1511     return false;
1512 
1513   assert(QualType(FromFn, 0).isCanonical());
1514   if (QualType(FromFn, 0) != CanTo) return false;
1515 
1516   ResultTy = ToType;
1517   return true;
1518 }
1519 
1520 /// \brief Determine whether the conversion from FromType to ToType is a valid
1521 /// vector conversion.
1522 ///
1523 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1524 /// conversion.
1525 static bool IsVectorConversion(Sema &S, QualType FromType,
1526                                QualType ToType, ImplicitConversionKind &ICK) {
1527   // We need at least one of these types to be a vector type to have a vector
1528   // conversion.
1529   if (!ToType->isVectorType() && !FromType->isVectorType())
1530     return false;
1531 
1532   // Identical types require no conversions.
1533   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1534     return false;
1535 
1536   // There are no conversions between extended vector types, only identity.
1537   if (ToType->isExtVectorType()) {
1538     // There are no conversions between extended vector types other than the
1539     // identity conversion.
1540     if (FromType->isExtVectorType())
1541       return false;
1542 
1543     // Vector splat from any arithmetic type to a vector.
1544     if (FromType->isArithmeticType()) {
1545       ICK = ICK_Vector_Splat;
1546       return true;
1547     }
1548   }
1549 
1550   // We can perform the conversion between vector types in the following cases:
1551   // 1)vector types are equivalent AltiVec and GCC vector types
1552   // 2)lax vector conversions are permitted and the vector types are of the
1553   //   same size
1554   if (ToType->isVectorType() && FromType->isVectorType()) {
1555     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1556         S.isLaxVectorConversion(FromType, ToType)) {
1557       ICK = ICK_Vector_Conversion;
1558       return true;
1559     }
1560   }
1561 
1562   return false;
1563 }
1564 
1565 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1566                                 bool InOverloadResolution,
1567                                 StandardConversionSequence &SCS,
1568                                 bool CStyle);
1569 
1570 /// IsStandardConversion - Determines whether there is a standard
1571 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1572 /// expression From to the type ToType. Standard conversion sequences
1573 /// only consider non-class types; for conversions that involve class
1574 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1575 /// contain the standard conversion sequence required to perform this
1576 /// conversion and this routine will return true. Otherwise, this
1577 /// routine will return false and the value of SCS is unspecified.
1578 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1579                                  bool InOverloadResolution,
1580                                  StandardConversionSequence &SCS,
1581                                  bool CStyle,
1582                                  bool AllowObjCWritebackConversion) {
1583   QualType FromType = From->getType();
1584 
1585   // Standard conversions (C++ [conv])
1586   SCS.setAsIdentityConversion();
1587   SCS.IncompatibleObjC = false;
1588   SCS.setFromType(FromType);
1589   SCS.CopyConstructor = nullptr;
1590 
1591   // There are no standard conversions for class types in C++, so
1592   // abort early. When overloading in C, however, we do permit them.
1593   if (S.getLangOpts().CPlusPlus &&
1594       (FromType->isRecordType() || ToType->isRecordType()))
1595     return false;
1596 
1597   // The first conversion can be an lvalue-to-rvalue conversion,
1598   // array-to-pointer conversion, or function-to-pointer conversion
1599   // (C++ 4p1).
1600 
1601   if (FromType == S.Context.OverloadTy) {
1602     DeclAccessPair AccessPair;
1603     if (FunctionDecl *Fn
1604           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1605                                                  AccessPair)) {
1606       // We were able to resolve the address of the overloaded function,
1607       // so we can convert to the type of that function.
1608       FromType = Fn->getType();
1609       SCS.setFromType(FromType);
1610 
1611       // we can sometimes resolve &foo<int> regardless of ToType, so check
1612       // if the type matches (identity) or we are converting to bool
1613       if (!S.Context.hasSameUnqualifiedType(
1614                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1615         QualType resultTy;
1616         // if the function type matches except for [[noreturn]], it's ok
1617         if (!S.IsFunctionConversion(FromType,
1618               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1619           // otherwise, only a boolean conversion is standard
1620           if (!ToType->isBooleanType())
1621             return false;
1622       }
1623 
1624       // Check if the "from" expression is taking the address of an overloaded
1625       // function and recompute the FromType accordingly. Take advantage of the
1626       // fact that non-static member functions *must* have such an address-of
1627       // expression.
1628       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1629       if (Method && !Method->isStatic()) {
1630         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1631                "Non-unary operator on non-static member address");
1632         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1633                == UO_AddrOf &&
1634                "Non-address-of operator on non-static member address");
1635         const Type *ClassType
1636           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1637         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1638       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1639         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1640                UO_AddrOf &&
1641                "Non-address-of operator for overloaded function expression");
1642         FromType = S.Context.getPointerType(FromType);
1643       }
1644 
1645       // Check that we've computed the proper type after overload resolution.
1646       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1647       // be calling it from within an NDEBUG block.
1648       assert(S.Context.hasSameType(
1649         FromType,
1650         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1651     } else {
1652       return false;
1653     }
1654   }
1655   // Lvalue-to-rvalue conversion (C++11 4.1):
1656   //   A glvalue (3.10) of a non-function, non-array type T can
1657   //   be converted to a prvalue.
1658   bool argIsLValue = From->isGLValue();
1659   if (argIsLValue &&
1660       !FromType->isFunctionType() && !FromType->isArrayType() &&
1661       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1662     SCS.First = ICK_Lvalue_To_Rvalue;
1663 
1664     // C11 6.3.2.1p2:
1665     //   ... if the lvalue has atomic type, the value has the non-atomic version
1666     //   of the type of the lvalue ...
1667     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1668       FromType = Atomic->getValueType();
1669 
1670     // If T is a non-class type, the type of the rvalue is the
1671     // cv-unqualified version of T. Otherwise, the type of the rvalue
1672     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1673     // just strip the qualifiers because they don't matter.
1674     FromType = FromType.getUnqualifiedType();
1675   } else if (FromType->isArrayType()) {
1676     // Array-to-pointer conversion (C++ 4.2)
1677     SCS.First = ICK_Array_To_Pointer;
1678 
1679     // An lvalue or rvalue of type "array of N T" or "array of unknown
1680     // bound of T" can be converted to an rvalue of type "pointer to
1681     // T" (C++ 4.2p1).
1682     FromType = S.Context.getArrayDecayedType(FromType);
1683 
1684     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1685       // This conversion is deprecated in C++03 (D.4)
1686       SCS.DeprecatedStringLiteralToCharPtr = true;
1687 
1688       // For the purpose of ranking in overload resolution
1689       // (13.3.3.1.1), this conversion is considered an
1690       // array-to-pointer conversion followed by a qualification
1691       // conversion (4.4). (C++ 4.2p2)
1692       SCS.Second = ICK_Identity;
1693       SCS.Third = ICK_Qualification;
1694       SCS.QualificationIncludesObjCLifetime = false;
1695       SCS.setAllToTypes(FromType);
1696       return true;
1697     }
1698   } else if (FromType->isFunctionType() && argIsLValue) {
1699     // Function-to-pointer conversion (C++ 4.3).
1700     SCS.First = ICK_Function_To_Pointer;
1701 
1702     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1703       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1704         if (!S.checkAddressOfFunctionIsAvailable(FD))
1705           return false;
1706 
1707     // An lvalue of function type T can be converted to an rvalue of
1708     // type "pointer to T." The result is a pointer to the
1709     // function. (C++ 4.3p1).
1710     FromType = S.Context.getPointerType(FromType);
1711   } else {
1712     // We don't require any conversions for the first step.
1713     SCS.First = ICK_Identity;
1714   }
1715   SCS.setToType(0, FromType);
1716 
1717   // The second conversion can be an integral promotion, floating
1718   // point promotion, integral conversion, floating point conversion,
1719   // floating-integral conversion, pointer conversion,
1720   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1721   // For overloading in C, this can also be a "compatible-type"
1722   // conversion.
1723   bool IncompatibleObjC = false;
1724   ImplicitConversionKind SecondICK = ICK_Identity;
1725   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1726     // The unqualified versions of the types are the same: there's no
1727     // conversion to do.
1728     SCS.Second = ICK_Identity;
1729   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1730     // Integral promotion (C++ 4.5).
1731     SCS.Second = ICK_Integral_Promotion;
1732     FromType = ToType.getUnqualifiedType();
1733   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1734     // Floating point promotion (C++ 4.6).
1735     SCS.Second = ICK_Floating_Promotion;
1736     FromType = ToType.getUnqualifiedType();
1737   } else if (S.IsComplexPromotion(FromType, ToType)) {
1738     // Complex promotion (Clang extension)
1739     SCS.Second = ICK_Complex_Promotion;
1740     FromType = ToType.getUnqualifiedType();
1741   } else if (ToType->isBooleanType() &&
1742              (FromType->isArithmeticType() ||
1743               FromType->isAnyPointerType() ||
1744               FromType->isBlockPointerType() ||
1745               FromType->isMemberPointerType() ||
1746               FromType->isNullPtrType())) {
1747     // Boolean conversions (C++ 4.12).
1748     SCS.Second = ICK_Boolean_Conversion;
1749     FromType = S.Context.BoolTy;
1750   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1751              ToType->isIntegralType(S.Context)) {
1752     // Integral conversions (C++ 4.7).
1753     SCS.Second = ICK_Integral_Conversion;
1754     FromType = ToType.getUnqualifiedType();
1755   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1756     // Complex conversions (C99 6.3.1.6)
1757     SCS.Second = ICK_Complex_Conversion;
1758     FromType = ToType.getUnqualifiedType();
1759   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1760              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1761     // Complex-real conversions (C99 6.3.1.7)
1762     SCS.Second = ICK_Complex_Real;
1763     FromType = ToType.getUnqualifiedType();
1764   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1765     // FIXME: disable conversions between long double and __float128 if
1766     // their representation is different until there is back end support
1767     // We of course allow this conversion if long double is really double.
1768     if (&S.Context.getFloatTypeSemantics(FromType) !=
1769         &S.Context.getFloatTypeSemantics(ToType)) {
1770       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1771                                     ToType == S.Context.LongDoubleTy) ||
1772                                    (FromType == S.Context.LongDoubleTy &&
1773                                     ToType == S.Context.Float128Ty));
1774       if (Float128AndLongDouble &&
1775           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1776            &llvm::APFloat::PPCDoubleDouble()))
1777         return false;
1778     }
1779     // Floating point conversions (C++ 4.8).
1780     SCS.Second = ICK_Floating_Conversion;
1781     FromType = ToType.getUnqualifiedType();
1782   } else if ((FromType->isRealFloatingType() &&
1783               ToType->isIntegralType(S.Context)) ||
1784              (FromType->isIntegralOrUnscopedEnumerationType() &&
1785               ToType->isRealFloatingType())) {
1786     // Floating-integral conversions (C++ 4.9).
1787     SCS.Second = ICK_Floating_Integral;
1788     FromType = ToType.getUnqualifiedType();
1789   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1790     SCS.Second = ICK_Block_Pointer_Conversion;
1791   } else if (AllowObjCWritebackConversion &&
1792              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1793     SCS.Second = ICK_Writeback_Conversion;
1794   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1795                                    FromType, IncompatibleObjC)) {
1796     // Pointer conversions (C++ 4.10).
1797     SCS.Second = ICK_Pointer_Conversion;
1798     SCS.IncompatibleObjC = IncompatibleObjC;
1799     FromType = FromType.getUnqualifiedType();
1800   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1801                                          InOverloadResolution, FromType)) {
1802     // Pointer to member conversions (4.11).
1803     SCS.Second = ICK_Pointer_Member;
1804   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1805     SCS.Second = SecondICK;
1806     FromType = ToType.getUnqualifiedType();
1807   } else if (!S.getLangOpts().CPlusPlus &&
1808              S.Context.typesAreCompatible(ToType, FromType)) {
1809     // Compatible conversions (Clang extension for C function overloading)
1810     SCS.Second = ICK_Compatible_Conversion;
1811     FromType = ToType.getUnqualifiedType();
1812   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1813                                              InOverloadResolution,
1814                                              SCS, CStyle)) {
1815     SCS.Second = ICK_TransparentUnionConversion;
1816     FromType = ToType;
1817   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1818                                  CStyle)) {
1819     // tryAtomicConversion has updated the standard conversion sequence
1820     // appropriately.
1821     return true;
1822   } else if (ToType->isEventT() &&
1823              From->isIntegerConstantExpr(S.getASTContext()) &&
1824              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1825     SCS.Second = ICK_Zero_Event_Conversion;
1826     FromType = ToType;
1827   } else if (ToType->isQueueT() &&
1828              From->isIntegerConstantExpr(S.getASTContext()) &&
1829              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1830     SCS.Second = ICK_Zero_Queue_Conversion;
1831     FromType = ToType;
1832   } else {
1833     // No second conversion required.
1834     SCS.Second = ICK_Identity;
1835   }
1836   SCS.setToType(1, FromType);
1837 
1838   // The third conversion can be a function pointer conversion or a
1839   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1840   bool ObjCLifetimeConversion;
1841   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1842     // Function pointer conversions (removing 'noexcept') including removal of
1843     // 'noreturn' (Clang extension).
1844     SCS.Third = ICK_Function_Conversion;
1845   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1846                                          ObjCLifetimeConversion)) {
1847     SCS.Third = ICK_Qualification;
1848     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1849     FromType = ToType;
1850   } else {
1851     // No conversion required
1852     SCS.Third = ICK_Identity;
1853   }
1854 
1855   // C++ [over.best.ics]p6:
1856   //   [...] Any difference in top-level cv-qualification is
1857   //   subsumed by the initialization itself and does not constitute
1858   //   a conversion. [...]
1859   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1860   QualType CanonTo = S.Context.getCanonicalType(ToType);
1861   if (CanonFrom.getLocalUnqualifiedType()
1862                                      == CanonTo.getLocalUnqualifiedType() &&
1863       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1864     FromType = ToType;
1865     CanonFrom = CanonTo;
1866   }
1867 
1868   SCS.setToType(2, FromType);
1869 
1870   if (CanonFrom == CanonTo)
1871     return true;
1872 
1873   // If we have not converted the argument type to the parameter type,
1874   // this is a bad conversion sequence, unless we're resolving an overload in C.
1875   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1876     return false;
1877 
1878   ExprResult ER = ExprResult{From};
1879   Sema::AssignConvertType Conv =
1880       S.CheckSingleAssignmentConstraints(ToType, ER,
1881                                          /*Diagnose=*/false,
1882                                          /*DiagnoseCFAudited=*/false,
1883                                          /*ConvertRHS=*/false);
1884   ImplicitConversionKind SecondConv;
1885   switch (Conv) {
1886   case Sema::Compatible:
1887     SecondConv = ICK_C_Only_Conversion;
1888     break;
1889   // For our purposes, discarding qualifiers is just as bad as using an
1890   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1891   // qualifiers, as well.
1892   case Sema::CompatiblePointerDiscardsQualifiers:
1893   case Sema::IncompatiblePointer:
1894   case Sema::IncompatiblePointerSign:
1895     SecondConv = ICK_Incompatible_Pointer_Conversion;
1896     break;
1897   default:
1898     return false;
1899   }
1900 
1901   // First can only be an lvalue conversion, so we pretend that this was the
1902   // second conversion. First should already be valid from earlier in the
1903   // function.
1904   SCS.Second = SecondConv;
1905   SCS.setToType(1, ToType);
1906 
1907   // Third is Identity, because Second should rank us worse than any other
1908   // conversion. This could also be ICK_Qualification, but it's simpler to just
1909   // lump everything in with the second conversion, and we don't gain anything
1910   // from making this ICK_Qualification.
1911   SCS.Third = ICK_Identity;
1912   SCS.setToType(2, ToType);
1913   return true;
1914 }
1915 
1916 static bool
1917 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1918                                      QualType &ToType,
1919                                      bool InOverloadResolution,
1920                                      StandardConversionSequence &SCS,
1921                                      bool CStyle) {
1922 
1923   const RecordType *UT = ToType->getAsUnionType();
1924   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1925     return false;
1926   // The field to initialize within the transparent union.
1927   RecordDecl *UD = UT->getDecl();
1928   // It's compatible if the expression matches any of the fields.
1929   for (const auto *it : UD->fields()) {
1930     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1931                              CStyle, /*ObjCWritebackConversion=*/false)) {
1932       ToType = it->getType();
1933       return true;
1934     }
1935   }
1936   return false;
1937 }
1938 
1939 /// IsIntegralPromotion - Determines whether the conversion from the
1940 /// expression From (whose potentially-adjusted type is FromType) to
1941 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1942 /// sets PromotedType to the promoted type.
1943 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1944   const BuiltinType *To = ToType->getAs<BuiltinType>();
1945   // All integers are built-in.
1946   if (!To) {
1947     return false;
1948   }
1949 
1950   // An rvalue of type char, signed char, unsigned char, short int, or
1951   // unsigned short int can be converted to an rvalue of type int if
1952   // int can represent all the values of the source type; otherwise,
1953   // the source rvalue can be converted to an rvalue of type unsigned
1954   // int (C++ 4.5p1).
1955   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1956       !FromType->isEnumeralType()) {
1957     if (// We can promote any signed, promotable integer type to an int
1958         (FromType->isSignedIntegerType() ||
1959          // We can promote any unsigned integer type whose size is
1960          // less than int to an int.
1961          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1962       return To->getKind() == BuiltinType::Int;
1963     }
1964 
1965     return To->getKind() == BuiltinType::UInt;
1966   }
1967 
1968   // C++11 [conv.prom]p3:
1969   //   A prvalue of an unscoped enumeration type whose underlying type is not
1970   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1971   //   following types that can represent all the values of the enumeration
1972   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1973   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1974   //   long long int. If none of the types in that list can represent all the
1975   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1976   //   type can be converted to an rvalue a prvalue of the extended integer type
1977   //   with lowest integer conversion rank (4.13) greater than the rank of long
1978   //   long in which all the values of the enumeration can be represented. If
1979   //   there are two such extended types, the signed one is chosen.
1980   // C++11 [conv.prom]p4:
1981   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1982   //   can be converted to a prvalue of its underlying type. Moreover, if
1983   //   integral promotion can be applied to its underlying type, a prvalue of an
1984   //   unscoped enumeration type whose underlying type is fixed can also be
1985   //   converted to a prvalue of the promoted underlying type.
1986   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1987     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1988     // provided for a scoped enumeration.
1989     if (FromEnumType->getDecl()->isScoped())
1990       return false;
1991 
1992     // We can perform an integral promotion to the underlying type of the enum,
1993     // even if that's not the promoted type. Note that the check for promoting
1994     // the underlying type is based on the type alone, and does not consider
1995     // the bitfield-ness of the actual source expression.
1996     if (FromEnumType->getDecl()->isFixed()) {
1997       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1998       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1999              IsIntegralPromotion(nullptr, Underlying, ToType);
2000     }
2001 
2002     // We have already pre-calculated the promotion type, so this is trivial.
2003     if (ToType->isIntegerType() &&
2004         isCompleteType(From->getLocStart(), FromType))
2005       return Context.hasSameUnqualifiedType(
2006           ToType, FromEnumType->getDecl()->getPromotionType());
2007   }
2008 
2009   // C++0x [conv.prom]p2:
2010   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2011   //   to an rvalue a prvalue of the first of the following types that can
2012   //   represent all the values of its underlying type: int, unsigned int,
2013   //   long int, unsigned long int, long long int, or unsigned long long int.
2014   //   If none of the types in that list can represent all the values of its
2015   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2016   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2017   //   type.
2018   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2019       ToType->isIntegerType()) {
2020     // Determine whether the type we're converting from is signed or
2021     // unsigned.
2022     bool FromIsSigned = FromType->isSignedIntegerType();
2023     uint64_t FromSize = Context.getTypeSize(FromType);
2024 
2025     // The types we'll try to promote to, in the appropriate
2026     // order. Try each of these types.
2027     QualType PromoteTypes[6] = {
2028       Context.IntTy, Context.UnsignedIntTy,
2029       Context.LongTy, Context.UnsignedLongTy ,
2030       Context.LongLongTy, Context.UnsignedLongLongTy
2031     };
2032     for (int Idx = 0; Idx < 6; ++Idx) {
2033       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2034       if (FromSize < ToSize ||
2035           (FromSize == ToSize &&
2036            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2037         // We found the type that we can promote to. If this is the
2038         // type we wanted, we have a promotion. Otherwise, no
2039         // promotion.
2040         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2041       }
2042     }
2043   }
2044 
2045   // An rvalue for an integral bit-field (9.6) can be converted to an
2046   // rvalue of type int if int can represent all the values of the
2047   // bit-field; otherwise, it can be converted to unsigned int if
2048   // unsigned int can represent all the values of the bit-field. If
2049   // the bit-field is larger yet, no integral promotion applies to
2050   // it. If the bit-field has an enumerated type, it is treated as any
2051   // other value of that type for promotion purposes (C++ 4.5p3).
2052   // FIXME: We should delay checking of bit-fields until we actually perform the
2053   // conversion.
2054   if (From) {
2055     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2056       llvm::APSInt BitWidth;
2057       if (FromType->isIntegralType(Context) &&
2058           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2059         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2060         ToSize = Context.getTypeSize(ToType);
2061 
2062         // Are we promoting to an int from a bitfield that fits in an int?
2063         if (BitWidth < ToSize ||
2064             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2065           return To->getKind() == BuiltinType::Int;
2066         }
2067 
2068         // Are we promoting to an unsigned int from an unsigned bitfield
2069         // that fits into an unsigned int?
2070         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2071           return To->getKind() == BuiltinType::UInt;
2072         }
2073 
2074         return false;
2075       }
2076     }
2077   }
2078 
2079   // An rvalue of type bool can be converted to an rvalue of type int,
2080   // with false becoming zero and true becoming one (C++ 4.5p4).
2081   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2082     return true;
2083   }
2084 
2085   return false;
2086 }
2087 
2088 /// IsFloatingPointPromotion - Determines whether the conversion from
2089 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2090 /// returns true and sets PromotedType to the promoted type.
2091 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2092   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2093     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2094       /// An rvalue of type float can be converted to an rvalue of type
2095       /// double. (C++ 4.6p1).
2096       if (FromBuiltin->getKind() == BuiltinType::Float &&
2097           ToBuiltin->getKind() == BuiltinType::Double)
2098         return true;
2099 
2100       // C99 6.3.1.5p1:
2101       //   When a float is promoted to double or long double, or a
2102       //   double is promoted to long double [...].
2103       if (!getLangOpts().CPlusPlus &&
2104           (FromBuiltin->getKind() == BuiltinType::Float ||
2105            FromBuiltin->getKind() == BuiltinType::Double) &&
2106           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2107            ToBuiltin->getKind() == BuiltinType::Float128))
2108         return true;
2109 
2110       // Half can be promoted to float.
2111       if (!getLangOpts().NativeHalfType &&
2112            FromBuiltin->getKind() == BuiltinType::Half &&
2113           ToBuiltin->getKind() == BuiltinType::Float)
2114         return true;
2115     }
2116 
2117   return false;
2118 }
2119 
2120 /// \brief Determine if a conversion is a complex promotion.
2121 ///
2122 /// A complex promotion is defined as a complex -> complex conversion
2123 /// where the conversion between the underlying real types is a
2124 /// floating-point or integral promotion.
2125 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2126   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2127   if (!FromComplex)
2128     return false;
2129 
2130   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2131   if (!ToComplex)
2132     return false;
2133 
2134   return IsFloatingPointPromotion(FromComplex->getElementType(),
2135                                   ToComplex->getElementType()) ||
2136     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2137                         ToComplex->getElementType());
2138 }
2139 
2140 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2141 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2142 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2143 /// if non-empty, will be a pointer to ToType that may or may not have
2144 /// the right set of qualifiers on its pointee.
2145 ///
2146 static QualType
2147 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2148                                    QualType ToPointee, QualType ToType,
2149                                    ASTContext &Context,
2150                                    bool StripObjCLifetime = false) {
2151   assert((FromPtr->getTypeClass() == Type::Pointer ||
2152           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2153          "Invalid similarly-qualified pointer type");
2154 
2155   /// Conversions to 'id' subsume cv-qualifier conversions.
2156   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2157     return ToType.getUnqualifiedType();
2158 
2159   QualType CanonFromPointee
2160     = Context.getCanonicalType(FromPtr->getPointeeType());
2161   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2162   Qualifiers Quals = CanonFromPointee.getQualifiers();
2163 
2164   if (StripObjCLifetime)
2165     Quals.removeObjCLifetime();
2166 
2167   // Exact qualifier match -> return the pointer type we're converting to.
2168   if (CanonToPointee.getLocalQualifiers() == Quals) {
2169     // ToType is exactly what we need. Return it.
2170     if (!ToType.isNull())
2171       return ToType.getUnqualifiedType();
2172 
2173     // Build a pointer to ToPointee. It has the right qualifiers
2174     // already.
2175     if (isa<ObjCObjectPointerType>(ToType))
2176       return Context.getObjCObjectPointerType(ToPointee);
2177     return Context.getPointerType(ToPointee);
2178   }
2179 
2180   // Just build a canonical type that has the right qualifiers.
2181   QualType QualifiedCanonToPointee
2182     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2183 
2184   if (isa<ObjCObjectPointerType>(ToType))
2185     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2186   return Context.getPointerType(QualifiedCanonToPointee);
2187 }
2188 
2189 static bool isNullPointerConstantForConversion(Expr *Expr,
2190                                                bool InOverloadResolution,
2191                                                ASTContext &Context) {
2192   // Handle value-dependent integral null pointer constants correctly.
2193   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2194   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2195       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2196     return !InOverloadResolution;
2197 
2198   return Expr->isNullPointerConstant(Context,
2199                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2200                                         : Expr::NPC_ValueDependentIsNull);
2201 }
2202 
2203 /// IsPointerConversion - Determines whether the conversion of the
2204 /// expression From, which has the (possibly adjusted) type FromType,
2205 /// can be converted to the type ToType via a pointer conversion (C++
2206 /// 4.10). If so, returns true and places the converted type (that
2207 /// might differ from ToType in its cv-qualifiers at some level) into
2208 /// ConvertedType.
2209 ///
2210 /// This routine also supports conversions to and from block pointers
2211 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2212 /// pointers to interfaces. FIXME: Once we've determined the
2213 /// appropriate overloading rules for Objective-C, we may want to
2214 /// split the Objective-C checks into a different routine; however,
2215 /// GCC seems to consider all of these conversions to be pointer
2216 /// conversions, so for now they live here. IncompatibleObjC will be
2217 /// set if the conversion is an allowed Objective-C conversion that
2218 /// should result in a warning.
2219 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2220                                bool InOverloadResolution,
2221                                QualType& ConvertedType,
2222                                bool &IncompatibleObjC) {
2223   IncompatibleObjC = false;
2224   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2225                               IncompatibleObjC))
2226     return true;
2227 
2228   // Conversion from a null pointer constant to any Objective-C pointer type.
2229   if (ToType->isObjCObjectPointerType() &&
2230       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2231     ConvertedType = ToType;
2232     return true;
2233   }
2234 
2235   // Blocks: Block pointers can be converted to void*.
2236   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2237       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2238     ConvertedType = ToType;
2239     return true;
2240   }
2241   // Blocks: A null pointer constant can be converted to a block
2242   // pointer type.
2243   if (ToType->isBlockPointerType() &&
2244       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2245     ConvertedType = ToType;
2246     return true;
2247   }
2248 
2249   // If the left-hand-side is nullptr_t, the right side can be a null
2250   // pointer constant.
2251   if (ToType->isNullPtrType() &&
2252       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2253     ConvertedType = ToType;
2254     return true;
2255   }
2256 
2257   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2258   if (!ToTypePtr)
2259     return false;
2260 
2261   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2262   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2263     ConvertedType = ToType;
2264     return true;
2265   }
2266 
2267   // Beyond this point, both types need to be pointers
2268   // , including objective-c pointers.
2269   QualType ToPointeeType = ToTypePtr->getPointeeType();
2270   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2271       !getLangOpts().ObjCAutoRefCount) {
2272     ConvertedType = BuildSimilarlyQualifiedPointerType(
2273                                       FromType->getAs<ObjCObjectPointerType>(),
2274                                                        ToPointeeType,
2275                                                        ToType, Context);
2276     return true;
2277   }
2278   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2279   if (!FromTypePtr)
2280     return false;
2281 
2282   QualType FromPointeeType = FromTypePtr->getPointeeType();
2283 
2284   // If the unqualified pointee types are the same, this can't be a
2285   // pointer conversion, so don't do all of the work below.
2286   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2287     return false;
2288 
2289   // An rvalue of type "pointer to cv T," where T is an object type,
2290   // can be converted to an rvalue of type "pointer to cv void" (C++
2291   // 4.10p2).
2292   if (FromPointeeType->isIncompleteOrObjectType() &&
2293       ToPointeeType->isVoidType()) {
2294     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2295                                                        ToPointeeType,
2296                                                        ToType, Context,
2297                                                    /*StripObjCLifetime=*/true);
2298     return true;
2299   }
2300 
2301   // MSVC allows implicit function to void* type conversion.
2302   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2303       ToPointeeType->isVoidType()) {
2304     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2305                                                        ToPointeeType,
2306                                                        ToType, Context);
2307     return true;
2308   }
2309 
2310   // When we're overloading in C, we allow a special kind of pointer
2311   // conversion for compatible-but-not-identical pointee types.
2312   if (!getLangOpts().CPlusPlus &&
2313       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2314     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2315                                                        ToPointeeType,
2316                                                        ToType, Context);
2317     return true;
2318   }
2319 
2320   // C++ [conv.ptr]p3:
2321   //
2322   //   An rvalue of type "pointer to cv D," where D is a class type,
2323   //   can be converted to an rvalue of type "pointer to cv B," where
2324   //   B is a base class (clause 10) of D. If B is an inaccessible
2325   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2326   //   necessitates this conversion is ill-formed. The result of the
2327   //   conversion is a pointer to the base class sub-object of the
2328   //   derived class object. The null pointer value is converted to
2329   //   the null pointer value of the destination type.
2330   //
2331   // Note that we do not check for ambiguity or inaccessibility
2332   // here. That is handled by CheckPointerConversion.
2333   if (getLangOpts().CPlusPlus &&
2334       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2335       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2336       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2337     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2338                                                        ToPointeeType,
2339                                                        ToType, Context);
2340     return true;
2341   }
2342 
2343   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2344       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2345     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2346                                                        ToPointeeType,
2347                                                        ToType, Context);
2348     return true;
2349   }
2350 
2351   return false;
2352 }
2353 
2354 /// \brief Adopt the given qualifiers for the given type.
2355 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2356   Qualifiers TQs = T.getQualifiers();
2357 
2358   // Check whether qualifiers already match.
2359   if (TQs == Qs)
2360     return T;
2361 
2362   if (Qs.compatiblyIncludes(TQs))
2363     return Context.getQualifiedType(T, Qs);
2364 
2365   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2366 }
2367 
2368 /// isObjCPointerConversion - Determines whether this is an
2369 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2370 /// with the same arguments and return values.
2371 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2372                                    QualType& ConvertedType,
2373                                    bool &IncompatibleObjC) {
2374   if (!getLangOpts().ObjC1)
2375     return false;
2376 
2377   // The set of qualifiers on the type we're converting from.
2378   Qualifiers FromQualifiers = FromType.getQualifiers();
2379 
2380   // First, we handle all conversions on ObjC object pointer types.
2381   const ObjCObjectPointerType* ToObjCPtr =
2382     ToType->getAs<ObjCObjectPointerType>();
2383   const ObjCObjectPointerType *FromObjCPtr =
2384     FromType->getAs<ObjCObjectPointerType>();
2385 
2386   if (ToObjCPtr && FromObjCPtr) {
2387     // If the pointee types are the same (ignoring qualifications),
2388     // then this is not a pointer conversion.
2389     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2390                                        FromObjCPtr->getPointeeType()))
2391       return false;
2392 
2393     // Conversion between Objective-C pointers.
2394     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2395       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2396       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2397       if (getLangOpts().CPlusPlus && LHS && RHS &&
2398           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2399                                                 FromObjCPtr->getPointeeType()))
2400         return false;
2401       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2402                                                    ToObjCPtr->getPointeeType(),
2403                                                          ToType, Context);
2404       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2405       return true;
2406     }
2407 
2408     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2409       // Okay: this is some kind of implicit downcast of Objective-C
2410       // interfaces, which is permitted. However, we're going to
2411       // complain about it.
2412       IncompatibleObjC = true;
2413       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2414                                                    ToObjCPtr->getPointeeType(),
2415                                                          ToType, Context);
2416       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2417       return true;
2418     }
2419   }
2420   // Beyond this point, both types need to be C pointers or block pointers.
2421   QualType ToPointeeType;
2422   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2423     ToPointeeType = ToCPtr->getPointeeType();
2424   else if (const BlockPointerType *ToBlockPtr =
2425             ToType->getAs<BlockPointerType>()) {
2426     // Objective C++: We're able to convert from a pointer to any object
2427     // to a block pointer type.
2428     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2429       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2430       return true;
2431     }
2432     ToPointeeType = ToBlockPtr->getPointeeType();
2433   }
2434   else if (FromType->getAs<BlockPointerType>() &&
2435            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2436     // Objective C++: We're able to convert from a block pointer type to a
2437     // pointer to any object.
2438     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2439     return true;
2440   }
2441   else
2442     return false;
2443 
2444   QualType FromPointeeType;
2445   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2446     FromPointeeType = FromCPtr->getPointeeType();
2447   else if (const BlockPointerType *FromBlockPtr =
2448            FromType->getAs<BlockPointerType>())
2449     FromPointeeType = FromBlockPtr->getPointeeType();
2450   else
2451     return false;
2452 
2453   // If we have pointers to pointers, recursively check whether this
2454   // is an Objective-C conversion.
2455   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2456       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2457                               IncompatibleObjC)) {
2458     // We always complain about this conversion.
2459     IncompatibleObjC = true;
2460     ConvertedType = Context.getPointerType(ConvertedType);
2461     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2462     return true;
2463   }
2464   // Allow conversion of pointee being objective-c pointer to another one;
2465   // as in I* to id.
2466   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2467       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2468       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2469                               IncompatibleObjC)) {
2470 
2471     ConvertedType = Context.getPointerType(ConvertedType);
2472     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2473     return true;
2474   }
2475 
2476   // If we have pointers to functions or blocks, check whether the only
2477   // differences in the argument and result types are in Objective-C
2478   // pointer conversions. If so, we permit the conversion (but
2479   // complain about it).
2480   const FunctionProtoType *FromFunctionType
2481     = FromPointeeType->getAs<FunctionProtoType>();
2482   const FunctionProtoType *ToFunctionType
2483     = ToPointeeType->getAs<FunctionProtoType>();
2484   if (FromFunctionType && ToFunctionType) {
2485     // If the function types are exactly the same, this isn't an
2486     // Objective-C pointer conversion.
2487     if (Context.getCanonicalType(FromPointeeType)
2488           == Context.getCanonicalType(ToPointeeType))
2489       return false;
2490 
2491     // Perform the quick checks that will tell us whether these
2492     // function types are obviously different.
2493     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2494         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2495         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2496       return false;
2497 
2498     bool HasObjCConversion = false;
2499     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2500         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2501       // Okay, the types match exactly. Nothing to do.
2502     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2503                                        ToFunctionType->getReturnType(),
2504                                        ConvertedType, IncompatibleObjC)) {
2505       // Okay, we have an Objective-C pointer conversion.
2506       HasObjCConversion = true;
2507     } else {
2508       // Function types are too different. Abort.
2509       return false;
2510     }
2511 
2512     // Check argument types.
2513     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2514          ArgIdx != NumArgs; ++ArgIdx) {
2515       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2516       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2517       if (Context.getCanonicalType(FromArgType)
2518             == Context.getCanonicalType(ToArgType)) {
2519         // Okay, the types match exactly. Nothing to do.
2520       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2521                                          ConvertedType, IncompatibleObjC)) {
2522         // Okay, we have an Objective-C pointer conversion.
2523         HasObjCConversion = true;
2524       } else {
2525         // Argument types are too different. Abort.
2526         return false;
2527       }
2528     }
2529 
2530     if (HasObjCConversion) {
2531       // We had an Objective-C conversion. Allow this pointer
2532       // conversion, but complain about it.
2533       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2534       IncompatibleObjC = true;
2535       return true;
2536     }
2537   }
2538 
2539   return false;
2540 }
2541 
2542 /// \brief Determine whether this is an Objective-C writeback conversion,
2543 /// used for parameter passing when performing automatic reference counting.
2544 ///
2545 /// \param FromType The type we're converting form.
2546 ///
2547 /// \param ToType The type we're converting to.
2548 ///
2549 /// \param ConvertedType The type that will be produced after applying
2550 /// this conversion.
2551 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2552                                      QualType &ConvertedType) {
2553   if (!getLangOpts().ObjCAutoRefCount ||
2554       Context.hasSameUnqualifiedType(FromType, ToType))
2555     return false;
2556 
2557   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2558   QualType ToPointee;
2559   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2560     ToPointee = ToPointer->getPointeeType();
2561   else
2562     return false;
2563 
2564   Qualifiers ToQuals = ToPointee.getQualifiers();
2565   if (!ToPointee->isObjCLifetimeType() ||
2566       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2567       !ToQuals.withoutObjCLifetime().empty())
2568     return false;
2569 
2570   // Argument must be a pointer to __strong to __weak.
2571   QualType FromPointee;
2572   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2573     FromPointee = FromPointer->getPointeeType();
2574   else
2575     return false;
2576 
2577   Qualifiers FromQuals = FromPointee.getQualifiers();
2578   if (!FromPointee->isObjCLifetimeType() ||
2579       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2580        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2581     return false;
2582 
2583   // Make sure that we have compatible qualifiers.
2584   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2585   if (!ToQuals.compatiblyIncludes(FromQuals))
2586     return false;
2587 
2588   // Remove qualifiers from the pointee type we're converting from; they
2589   // aren't used in the compatibility check belong, and we'll be adding back
2590   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2591   FromPointee = FromPointee.getUnqualifiedType();
2592 
2593   // The unqualified form of the pointee types must be compatible.
2594   ToPointee = ToPointee.getUnqualifiedType();
2595   bool IncompatibleObjC;
2596   if (Context.typesAreCompatible(FromPointee, ToPointee))
2597     FromPointee = ToPointee;
2598   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2599                                     IncompatibleObjC))
2600     return false;
2601 
2602   /// \brief Construct the type we're converting to, which is a pointer to
2603   /// __autoreleasing pointee.
2604   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2605   ConvertedType = Context.getPointerType(FromPointee);
2606   return true;
2607 }
2608 
2609 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2610                                     QualType& ConvertedType) {
2611   QualType ToPointeeType;
2612   if (const BlockPointerType *ToBlockPtr =
2613         ToType->getAs<BlockPointerType>())
2614     ToPointeeType = ToBlockPtr->getPointeeType();
2615   else
2616     return false;
2617 
2618   QualType FromPointeeType;
2619   if (const BlockPointerType *FromBlockPtr =
2620       FromType->getAs<BlockPointerType>())
2621     FromPointeeType = FromBlockPtr->getPointeeType();
2622   else
2623     return false;
2624   // We have pointer to blocks, check whether the only
2625   // differences in the argument and result types are in Objective-C
2626   // pointer conversions. If so, we permit the conversion.
2627 
2628   const FunctionProtoType *FromFunctionType
2629     = FromPointeeType->getAs<FunctionProtoType>();
2630   const FunctionProtoType *ToFunctionType
2631     = ToPointeeType->getAs<FunctionProtoType>();
2632 
2633   if (!FromFunctionType || !ToFunctionType)
2634     return false;
2635 
2636   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2637     return true;
2638 
2639   // Perform the quick checks that will tell us whether these
2640   // function types are obviously different.
2641   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2642       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2643     return false;
2644 
2645   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2646   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2647   if (FromEInfo != ToEInfo)
2648     return false;
2649 
2650   bool IncompatibleObjC = false;
2651   if (Context.hasSameType(FromFunctionType->getReturnType(),
2652                           ToFunctionType->getReturnType())) {
2653     // Okay, the types match exactly. Nothing to do.
2654   } else {
2655     QualType RHS = FromFunctionType->getReturnType();
2656     QualType LHS = ToFunctionType->getReturnType();
2657     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2658         !RHS.hasQualifiers() && LHS.hasQualifiers())
2659        LHS = LHS.getUnqualifiedType();
2660 
2661      if (Context.hasSameType(RHS,LHS)) {
2662        // OK exact match.
2663      } else if (isObjCPointerConversion(RHS, LHS,
2664                                         ConvertedType, IncompatibleObjC)) {
2665      if (IncompatibleObjC)
2666        return false;
2667      // Okay, we have an Objective-C pointer conversion.
2668      }
2669      else
2670        return false;
2671    }
2672 
2673    // Check argument types.
2674    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2675         ArgIdx != NumArgs; ++ArgIdx) {
2676      IncompatibleObjC = false;
2677      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2678      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2679      if (Context.hasSameType(FromArgType, ToArgType)) {
2680        // Okay, the types match exactly. Nothing to do.
2681      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2682                                         ConvertedType, IncompatibleObjC)) {
2683        if (IncompatibleObjC)
2684          return false;
2685        // Okay, we have an Objective-C pointer conversion.
2686      } else
2687        // Argument types are too different. Abort.
2688        return false;
2689    }
2690 
2691    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2692    bool CanUseToFPT, CanUseFromFPT;
2693    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2694                                       CanUseToFPT, CanUseFromFPT,
2695                                       NewParamInfos))
2696      return false;
2697 
2698    ConvertedType = ToType;
2699    return true;
2700 }
2701 
2702 enum {
2703   ft_default,
2704   ft_different_class,
2705   ft_parameter_arity,
2706   ft_parameter_mismatch,
2707   ft_return_type,
2708   ft_qualifer_mismatch,
2709   ft_noexcept
2710 };
2711 
2712 /// Attempts to get the FunctionProtoType from a Type. Handles
2713 /// MemberFunctionPointers properly.
2714 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2715   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2716     return FPT;
2717 
2718   if (auto *MPT = FromType->getAs<MemberPointerType>())
2719     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2720 
2721   return nullptr;
2722 }
2723 
2724 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2725 /// function types.  Catches different number of parameter, mismatch in
2726 /// parameter types, and different return types.
2727 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2728                                       QualType FromType, QualType ToType) {
2729   // If either type is not valid, include no extra info.
2730   if (FromType.isNull() || ToType.isNull()) {
2731     PDiag << ft_default;
2732     return;
2733   }
2734 
2735   // Get the function type from the pointers.
2736   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2737     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2738                             *ToMember = ToType->getAs<MemberPointerType>();
2739     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2740       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2741             << QualType(FromMember->getClass(), 0);
2742       return;
2743     }
2744     FromType = FromMember->getPointeeType();
2745     ToType = ToMember->getPointeeType();
2746   }
2747 
2748   if (FromType->isPointerType())
2749     FromType = FromType->getPointeeType();
2750   if (ToType->isPointerType())
2751     ToType = ToType->getPointeeType();
2752 
2753   // Remove references.
2754   FromType = FromType.getNonReferenceType();
2755   ToType = ToType.getNonReferenceType();
2756 
2757   // Don't print extra info for non-specialized template functions.
2758   if (FromType->isInstantiationDependentType() &&
2759       !FromType->getAs<TemplateSpecializationType>()) {
2760     PDiag << ft_default;
2761     return;
2762   }
2763 
2764   // No extra info for same types.
2765   if (Context.hasSameType(FromType, ToType)) {
2766     PDiag << ft_default;
2767     return;
2768   }
2769 
2770   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2771                           *ToFunction = tryGetFunctionProtoType(ToType);
2772 
2773   // Both types need to be function types.
2774   if (!FromFunction || !ToFunction) {
2775     PDiag << ft_default;
2776     return;
2777   }
2778 
2779   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2780     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2781           << FromFunction->getNumParams();
2782     return;
2783   }
2784 
2785   // Handle different parameter types.
2786   unsigned ArgPos;
2787   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2788     PDiag << ft_parameter_mismatch << ArgPos + 1
2789           << ToFunction->getParamType(ArgPos)
2790           << FromFunction->getParamType(ArgPos);
2791     return;
2792   }
2793 
2794   // Handle different return type.
2795   if (!Context.hasSameType(FromFunction->getReturnType(),
2796                            ToFunction->getReturnType())) {
2797     PDiag << ft_return_type << ToFunction->getReturnType()
2798           << FromFunction->getReturnType();
2799     return;
2800   }
2801 
2802   unsigned FromQuals = FromFunction->getTypeQuals(),
2803            ToQuals = ToFunction->getTypeQuals();
2804   if (FromQuals != ToQuals) {
2805     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2806     return;
2807   }
2808 
2809   // Handle exception specification differences on canonical type (in C++17
2810   // onwards).
2811   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2812           ->isNothrow() !=
2813       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2814           ->isNothrow()) {
2815     PDiag << ft_noexcept;
2816     return;
2817   }
2818 
2819   // Unable to find a difference, so add no extra info.
2820   PDiag << ft_default;
2821 }
2822 
2823 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2824 /// for equality of their argument types. Caller has already checked that
2825 /// they have same number of arguments.  If the parameters are different,
2826 /// ArgPos will have the parameter index of the first different parameter.
2827 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2828                                       const FunctionProtoType *NewType,
2829                                       unsigned *ArgPos) {
2830   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2831                                               N = NewType->param_type_begin(),
2832                                               E = OldType->param_type_end();
2833        O && (O != E); ++O, ++N) {
2834     if (!Context.hasSameType(O->getUnqualifiedType(),
2835                              N->getUnqualifiedType())) {
2836       if (ArgPos)
2837         *ArgPos = O - OldType->param_type_begin();
2838       return false;
2839     }
2840   }
2841   return true;
2842 }
2843 
2844 /// CheckPointerConversion - Check the pointer conversion from the
2845 /// expression From to the type ToType. This routine checks for
2846 /// ambiguous or inaccessible derived-to-base pointer
2847 /// conversions for which IsPointerConversion has already returned
2848 /// true. It returns true and produces a diagnostic if there was an
2849 /// error, or returns false otherwise.
2850 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2851                                   CastKind &Kind,
2852                                   CXXCastPath& BasePath,
2853                                   bool IgnoreBaseAccess,
2854                                   bool Diagnose) {
2855   QualType FromType = From->getType();
2856   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2857 
2858   Kind = CK_BitCast;
2859 
2860   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2861       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2862           Expr::NPCK_ZeroExpression) {
2863     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2864       DiagRuntimeBehavior(From->getExprLoc(), From,
2865                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2866                             << ToType << From->getSourceRange());
2867     else if (!isUnevaluatedContext())
2868       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2869         << ToType << From->getSourceRange();
2870   }
2871   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2872     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2873       QualType FromPointeeType = FromPtrType->getPointeeType(),
2874                ToPointeeType   = ToPtrType->getPointeeType();
2875 
2876       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2877           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2878         // We must have a derived-to-base conversion. Check an
2879         // ambiguous or inaccessible conversion.
2880         unsigned InaccessibleID = 0;
2881         unsigned AmbigiousID = 0;
2882         if (Diagnose) {
2883           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2884           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2885         }
2886         if (CheckDerivedToBaseConversion(
2887                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2888                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2889                 &BasePath, IgnoreBaseAccess))
2890           return true;
2891 
2892         // The conversion was successful.
2893         Kind = CK_DerivedToBase;
2894       }
2895 
2896       if (Diagnose && !IsCStyleOrFunctionalCast &&
2897           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2898         assert(getLangOpts().MSVCCompat &&
2899                "this should only be possible with MSVCCompat!");
2900         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2901             << From->getSourceRange();
2902       }
2903     }
2904   } else if (const ObjCObjectPointerType *ToPtrType =
2905                ToType->getAs<ObjCObjectPointerType>()) {
2906     if (const ObjCObjectPointerType *FromPtrType =
2907           FromType->getAs<ObjCObjectPointerType>()) {
2908       // Objective-C++ conversions are always okay.
2909       // FIXME: We should have a different class of conversions for the
2910       // Objective-C++ implicit conversions.
2911       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2912         return false;
2913     } else if (FromType->isBlockPointerType()) {
2914       Kind = CK_BlockPointerToObjCPointerCast;
2915     } else {
2916       Kind = CK_CPointerToObjCPointerCast;
2917     }
2918   } else if (ToType->isBlockPointerType()) {
2919     if (!FromType->isBlockPointerType())
2920       Kind = CK_AnyPointerToBlockPointerCast;
2921   }
2922 
2923   // We shouldn't fall into this case unless it's valid for other
2924   // reasons.
2925   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2926     Kind = CK_NullToPointer;
2927 
2928   return false;
2929 }
2930 
2931 /// IsMemberPointerConversion - Determines whether the conversion of the
2932 /// expression From, which has the (possibly adjusted) type FromType, can be
2933 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2934 /// If so, returns true and places the converted type (that might differ from
2935 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2936 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2937                                      QualType ToType,
2938                                      bool InOverloadResolution,
2939                                      QualType &ConvertedType) {
2940   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2941   if (!ToTypePtr)
2942     return false;
2943 
2944   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2945   if (From->isNullPointerConstant(Context,
2946                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2947                                         : Expr::NPC_ValueDependentIsNull)) {
2948     ConvertedType = ToType;
2949     return true;
2950   }
2951 
2952   // Otherwise, both types have to be member pointers.
2953   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2954   if (!FromTypePtr)
2955     return false;
2956 
2957   // A pointer to member of B can be converted to a pointer to member of D,
2958   // where D is derived from B (C++ 4.11p2).
2959   QualType FromClass(FromTypePtr->getClass(), 0);
2960   QualType ToClass(ToTypePtr->getClass(), 0);
2961 
2962   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2963       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2964     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2965                                                  ToClass.getTypePtr());
2966     return true;
2967   }
2968 
2969   return false;
2970 }
2971 
2972 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2973 /// expression From to the type ToType. This routine checks for ambiguous or
2974 /// virtual or inaccessible base-to-derived member pointer conversions
2975 /// for which IsMemberPointerConversion has already returned true. It returns
2976 /// true and produces a diagnostic if there was an error, or returns false
2977 /// otherwise.
2978 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2979                                         CastKind &Kind,
2980                                         CXXCastPath &BasePath,
2981                                         bool IgnoreBaseAccess) {
2982   QualType FromType = From->getType();
2983   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2984   if (!FromPtrType) {
2985     // This must be a null pointer to member pointer conversion
2986     assert(From->isNullPointerConstant(Context,
2987                                        Expr::NPC_ValueDependentIsNull) &&
2988            "Expr must be null pointer constant!");
2989     Kind = CK_NullToMemberPointer;
2990     return false;
2991   }
2992 
2993   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2994   assert(ToPtrType && "No member pointer cast has a target type "
2995                       "that is not a member pointer.");
2996 
2997   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2998   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2999 
3000   // FIXME: What about dependent types?
3001   assert(FromClass->isRecordType() && "Pointer into non-class.");
3002   assert(ToClass->isRecordType() && "Pointer into non-class.");
3003 
3004   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3005                      /*DetectVirtual=*/true);
3006   bool DerivationOkay =
3007       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3008   assert(DerivationOkay &&
3009          "Should not have been called if derivation isn't OK.");
3010   (void)DerivationOkay;
3011 
3012   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3013                                   getUnqualifiedType())) {
3014     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3015     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3016       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3017     return true;
3018   }
3019 
3020   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3021     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3022       << FromClass << ToClass << QualType(VBase, 0)
3023       << From->getSourceRange();
3024     return true;
3025   }
3026 
3027   if (!IgnoreBaseAccess)
3028     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3029                          Paths.front(),
3030                          diag::err_downcast_from_inaccessible_base);
3031 
3032   // Must be a base to derived member conversion.
3033   BuildBasePathArray(Paths, BasePath);
3034   Kind = CK_BaseToDerivedMemberPointer;
3035   return false;
3036 }
3037 
3038 /// Determine whether the lifetime conversion between the two given
3039 /// qualifiers sets is nontrivial.
3040 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3041                                                Qualifiers ToQuals) {
3042   // Converting anything to const __unsafe_unretained is trivial.
3043   if (ToQuals.hasConst() &&
3044       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3045     return false;
3046 
3047   return true;
3048 }
3049 
3050 /// IsQualificationConversion - Determines whether the conversion from
3051 /// an rvalue of type FromType to ToType is a qualification conversion
3052 /// (C++ 4.4).
3053 ///
3054 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3055 /// when the qualification conversion involves a change in the Objective-C
3056 /// object lifetime.
3057 bool
3058 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3059                                 bool CStyle, bool &ObjCLifetimeConversion) {
3060   FromType = Context.getCanonicalType(FromType);
3061   ToType = Context.getCanonicalType(ToType);
3062   ObjCLifetimeConversion = false;
3063 
3064   // If FromType and ToType are the same type, this is not a
3065   // qualification conversion.
3066   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3067     return false;
3068 
3069   // (C++ 4.4p4):
3070   //   A conversion can add cv-qualifiers at levels other than the first
3071   //   in multi-level pointers, subject to the following rules: [...]
3072   bool PreviousToQualsIncludeConst = true;
3073   bool UnwrappedAnyPointer = false;
3074   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3075     // Within each iteration of the loop, we check the qualifiers to
3076     // determine if this still looks like a qualification
3077     // conversion. Then, if all is well, we unwrap one more level of
3078     // pointers or pointers-to-members and do it all again
3079     // until there are no more pointers or pointers-to-members left to
3080     // unwrap.
3081     UnwrappedAnyPointer = true;
3082 
3083     Qualifiers FromQuals = FromType.getQualifiers();
3084     Qualifiers ToQuals = ToType.getQualifiers();
3085 
3086     // Ignore __unaligned qualifier if this type is void.
3087     if (ToType.getUnqualifiedType()->isVoidType())
3088       FromQuals.removeUnaligned();
3089 
3090     // Objective-C ARC:
3091     //   Check Objective-C lifetime conversions.
3092     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3093         UnwrappedAnyPointer) {
3094       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3095         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3096           ObjCLifetimeConversion = true;
3097         FromQuals.removeObjCLifetime();
3098         ToQuals.removeObjCLifetime();
3099       } else {
3100         // Qualification conversions cannot cast between different
3101         // Objective-C lifetime qualifiers.
3102         return false;
3103       }
3104     }
3105 
3106     // Allow addition/removal of GC attributes but not changing GC attributes.
3107     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3108         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3109       FromQuals.removeObjCGCAttr();
3110       ToQuals.removeObjCGCAttr();
3111     }
3112 
3113     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3114     //      2,j, and similarly for volatile.
3115     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3116       return false;
3117 
3118     //   -- if the cv 1,j and cv 2,j are different, then const is in
3119     //      every cv for 0 < k < j.
3120     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3121         && !PreviousToQualsIncludeConst)
3122       return false;
3123 
3124     // Keep track of whether all prior cv-qualifiers in the "to" type
3125     // include const.
3126     PreviousToQualsIncludeConst
3127       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3128   }
3129 
3130   // We are left with FromType and ToType being the pointee types
3131   // after unwrapping the original FromType and ToType the same number
3132   // of types. If we unwrapped any pointers, and if FromType and
3133   // ToType have the same unqualified type (since we checked
3134   // qualifiers above), then this is a qualification conversion.
3135   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3136 }
3137 
3138 /// \brief - Determine whether this is a conversion from a scalar type to an
3139 /// atomic type.
3140 ///
3141 /// If successful, updates \c SCS's second and third steps in the conversion
3142 /// sequence to finish the conversion.
3143 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3144                                 bool InOverloadResolution,
3145                                 StandardConversionSequence &SCS,
3146                                 bool CStyle) {
3147   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3148   if (!ToAtomic)
3149     return false;
3150 
3151   StandardConversionSequence InnerSCS;
3152   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3153                             InOverloadResolution, InnerSCS,
3154                             CStyle, /*AllowObjCWritebackConversion=*/false))
3155     return false;
3156 
3157   SCS.Second = InnerSCS.Second;
3158   SCS.setToType(1, InnerSCS.getToType(1));
3159   SCS.Third = InnerSCS.Third;
3160   SCS.QualificationIncludesObjCLifetime
3161     = InnerSCS.QualificationIncludesObjCLifetime;
3162   SCS.setToType(2, InnerSCS.getToType(2));
3163   return true;
3164 }
3165 
3166 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3167                                               CXXConstructorDecl *Constructor,
3168                                               QualType Type) {
3169   const FunctionProtoType *CtorType =
3170       Constructor->getType()->getAs<FunctionProtoType>();
3171   if (CtorType->getNumParams() > 0) {
3172     QualType FirstArg = CtorType->getParamType(0);
3173     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3174       return true;
3175   }
3176   return false;
3177 }
3178 
3179 static OverloadingResult
3180 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3181                                        CXXRecordDecl *To,
3182                                        UserDefinedConversionSequence &User,
3183                                        OverloadCandidateSet &CandidateSet,
3184                                        bool AllowExplicit) {
3185   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3186   for (auto *D : S.LookupConstructors(To)) {
3187     auto Info = getConstructorInfo(D);
3188     if (!Info)
3189       continue;
3190 
3191     bool Usable = !Info.Constructor->isInvalidDecl() &&
3192                   S.isInitListConstructor(Info.Constructor) &&
3193                   (AllowExplicit || !Info.Constructor->isExplicit());
3194     if (Usable) {
3195       // If the first argument is (a reference to) the target type,
3196       // suppress conversions.
3197       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3198           S.Context, Info.Constructor, ToType);
3199       if (Info.ConstructorTmpl)
3200         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3201                                        /*ExplicitArgs*/ nullptr, From,
3202                                        CandidateSet, SuppressUserConversions);
3203       else
3204         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3205                                CandidateSet, SuppressUserConversions);
3206     }
3207   }
3208 
3209   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3210 
3211   OverloadCandidateSet::iterator Best;
3212   switch (auto Result =
3213             CandidateSet.BestViableFunction(S, From->getLocStart(),
3214                                             Best)) {
3215   case OR_Deleted:
3216   case OR_Success: {
3217     // Record the standard conversion we used and the conversion function.
3218     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3219     QualType ThisType = Constructor->getThisType(S.Context);
3220     // Initializer lists don't have conversions as such.
3221     User.Before.setAsIdentityConversion();
3222     User.HadMultipleCandidates = HadMultipleCandidates;
3223     User.ConversionFunction = Constructor;
3224     User.FoundConversionFunction = Best->FoundDecl;
3225     User.After.setAsIdentityConversion();
3226     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3227     User.After.setAllToTypes(ToType);
3228     return Result;
3229   }
3230 
3231   case OR_No_Viable_Function:
3232     return OR_No_Viable_Function;
3233   case OR_Ambiguous:
3234     return OR_Ambiguous;
3235   }
3236 
3237   llvm_unreachable("Invalid OverloadResult!");
3238 }
3239 
3240 /// Determines whether there is a user-defined conversion sequence
3241 /// (C++ [over.ics.user]) that converts expression From to the type
3242 /// ToType. If such a conversion exists, User will contain the
3243 /// user-defined conversion sequence that performs such a conversion
3244 /// and this routine will return true. Otherwise, this routine returns
3245 /// false and User is unspecified.
3246 ///
3247 /// \param AllowExplicit  true if the conversion should consider C++0x
3248 /// "explicit" conversion functions as well as non-explicit conversion
3249 /// functions (C++0x [class.conv.fct]p2).
3250 ///
3251 /// \param AllowObjCConversionOnExplicit true if the conversion should
3252 /// allow an extra Objective-C pointer conversion on uses of explicit
3253 /// constructors. Requires \c AllowExplicit to also be set.
3254 static OverloadingResult
3255 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3256                         UserDefinedConversionSequence &User,
3257                         OverloadCandidateSet &CandidateSet,
3258                         bool AllowExplicit,
3259                         bool AllowObjCConversionOnExplicit) {
3260   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3261   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3262 
3263   // Whether we will only visit constructors.
3264   bool ConstructorsOnly = false;
3265 
3266   // If the type we are conversion to is a class type, enumerate its
3267   // constructors.
3268   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3269     // C++ [over.match.ctor]p1:
3270     //   When objects of class type are direct-initialized (8.5), or
3271     //   copy-initialized from an expression of the same or a
3272     //   derived class type (8.5), overload resolution selects the
3273     //   constructor. [...] For copy-initialization, the candidate
3274     //   functions are all the converting constructors (12.3.1) of
3275     //   that class. The argument list is the expression-list within
3276     //   the parentheses of the initializer.
3277     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3278         (From->getType()->getAs<RecordType>() &&
3279          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3280       ConstructorsOnly = true;
3281 
3282     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3283       // We're not going to find any constructors.
3284     } else if (CXXRecordDecl *ToRecordDecl
3285                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3286 
3287       Expr **Args = &From;
3288       unsigned NumArgs = 1;
3289       bool ListInitializing = false;
3290       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3291         // But first, see if there is an init-list-constructor that will work.
3292         OverloadingResult Result = IsInitializerListConstructorConversion(
3293             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3294         if (Result != OR_No_Viable_Function)
3295           return Result;
3296         // Never mind.
3297         CandidateSet.clear(
3298             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3299 
3300         // If we're list-initializing, we pass the individual elements as
3301         // arguments, not the entire list.
3302         Args = InitList->getInits();
3303         NumArgs = InitList->getNumInits();
3304         ListInitializing = true;
3305       }
3306 
3307       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3308         auto Info = getConstructorInfo(D);
3309         if (!Info)
3310           continue;
3311 
3312         bool Usable = !Info.Constructor->isInvalidDecl();
3313         if (ListInitializing)
3314           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3315         else
3316           Usable = Usable &&
3317                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3318         if (Usable) {
3319           bool SuppressUserConversions = !ConstructorsOnly;
3320           if (SuppressUserConversions && ListInitializing) {
3321             SuppressUserConversions = false;
3322             if (NumArgs == 1) {
3323               // If the first argument is (a reference to) the target type,
3324               // suppress conversions.
3325               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3326                   S.Context, Info.Constructor, ToType);
3327             }
3328           }
3329           if (Info.ConstructorTmpl)
3330             S.AddTemplateOverloadCandidate(
3331                 Info.ConstructorTmpl, Info.FoundDecl,
3332                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3333                 CandidateSet, SuppressUserConversions);
3334           else
3335             // Allow one user-defined conversion when user specifies a
3336             // From->ToType conversion via an static cast (c-style, etc).
3337             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3338                                    llvm::makeArrayRef(Args, NumArgs),
3339                                    CandidateSet, SuppressUserConversions);
3340         }
3341       }
3342     }
3343   }
3344 
3345   // Enumerate conversion functions, if we're allowed to.
3346   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3347   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3348     // No conversion functions from incomplete types.
3349   } else if (const RecordType *FromRecordType
3350                                    = From->getType()->getAs<RecordType>()) {
3351     if (CXXRecordDecl *FromRecordDecl
3352          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3353       // Add all of the conversion functions as candidates.
3354       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3355       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3356         DeclAccessPair FoundDecl = I.getPair();
3357         NamedDecl *D = FoundDecl.getDecl();
3358         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3359         if (isa<UsingShadowDecl>(D))
3360           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3361 
3362         CXXConversionDecl *Conv;
3363         FunctionTemplateDecl *ConvTemplate;
3364         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3365           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3366         else
3367           Conv = cast<CXXConversionDecl>(D);
3368 
3369         if (AllowExplicit || !Conv->isExplicit()) {
3370           if (ConvTemplate)
3371             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3372                                              ActingContext, From, ToType,
3373                                              CandidateSet,
3374                                              AllowObjCConversionOnExplicit);
3375           else
3376             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3377                                      From, ToType, CandidateSet,
3378                                      AllowObjCConversionOnExplicit);
3379         }
3380       }
3381     }
3382   }
3383 
3384   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3385 
3386   OverloadCandidateSet::iterator Best;
3387   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3388                                                         Best)) {
3389   case OR_Success:
3390   case OR_Deleted:
3391     // Record the standard conversion we used and the conversion function.
3392     if (CXXConstructorDecl *Constructor
3393           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3394       // C++ [over.ics.user]p1:
3395       //   If the user-defined conversion is specified by a
3396       //   constructor (12.3.1), the initial standard conversion
3397       //   sequence converts the source type to the type required by
3398       //   the argument of the constructor.
3399       //
3400       QualType ThisType = Constructor->getThisType(S.Context);
3401       if (isa<InitListExpr>(From)) {
3402         // Initializer lists don't have conversions as such.
3403         User.Before.setAsIdentityConversion();
3404       } else {
3405         if (Best->Conversions[0].isEllipsis())
3406           User.EllipsisConversion = true;
3407         else {
3408           User.Before = Best->Conversions[0].Standard;
3409           User.EllipsisConversion = false;
3410         }
3411       }
3412       User.HadMultipleCandidates = HadMultipleCandidates;
3413       User.ConversionFunction = Constructor;
3414       User.FoundConversionFunction = Best->FoundDecl;
3415       User.After.setAsIdentityConversion();
3416       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3417       User.After.setAllToTypes(ToType);
3418       return Result;
3419     }
3420     if (CXXConversionDecl *Conversion
3421                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3422       // C++ [over.ics.user]p1:
3423       //
3424       //   [...] If the user-defined conversion is specified by a
3425       //   conversion function (12.3.2), the initial standard
3426       //   conversion sequence converts the source type to the
3427       //   implicit object parameter of the conversion function.
3428       User.Before = Best->Conversions[0].Standard;
3429       User.HadMultipleCandidates = HadMultipleCandidates;
3430       User.ConversionFunction = Conversion;
3431       User.FoundConversionFunction = Best->FoundDecl;
3432       User.EllipsisConversion = false;
3433 
3434       // C++ [over.ics.user]p2:
3435       //   The second standard conversion sequence converts the
3436       //   result of the user-defined conversion to the target type
3437       //   for the sequence. Since an implicit conversion sequence
3438       //   is an initialization, the special rules for
3439       //   initialization by user-defined conversion apply when
3440       //   selecting the best user-defined conversion for a
3441       //   user-defined conversion sequence (see 13.3.3 and
3442       //   13.3.3.1).
3443       User.After = Best->FinalConversion;
3444       return Result;
3445     }
3446     llvm_unreachable("Not a constructor or conversion function?");
3447 
3448   case OR_No_Viable_Function:
3449     return OR_No_Viable_Function;
3450 
3451   case OR_Ambiguous:
3452     return OR_Ambiguous;
3453   }
3454 
3455   llvm_unreachable("Invalid OverloadResult!");
3456 }
3457 
3458 bool
3459 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3460   ImplicitConversionSequence ICS;
3461   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3462                                     OverloadCandidateSet::CSK_Normal);
3463   OverloadingResult OvResult =
3464     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3465                             CandidateSet, false, false);
3466   if (OvResult == OR_Ambiguous)
3467     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3468         << From->getType() << ToType << From->getSourceRange();
3469   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3470     if (!RequireCompleteType(From->getLocStart(), ToType,
3471                              diag::err_typecheck_nonviable_condition_incomplete,
3472                              From->getType(), From->getSourceRange()))
3473       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3474           << false << From->getType() << From->getSourceRange() << ToType;
3475   } else
3476     return false;
3477   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3478   return true;
3479 }
3480 
3481 /// \brief Compare the user-defined conversion functions or constructors
3482 /// of two user-defined conversion sequences to determine whether any ordering
3483 /// is possible.
3484 static ImplicitConversionSequence::CompareKind
3485 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3486                            FunctionDecl *Function2) {
3487   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3488     return ImplicitConversionSequence::Indistinguishable;
3489 
3490   // Objective-C++:
3491   //   If both conversion functions are implicitly-declared conversions from
3492   //   a lambda closure type to a function pointer and a block pointer,
3493   //   respectively, always prefer the conversion to a function pointer,
3494   //   because the function pointer is more lightweight and is more likely
3495   //   to keep code working.
3496   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3497   if (!Conv1)
3498     return ImplicitConversionSequence::Indistinguishable;
3499 
3500   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3501   if (!Conv2)
3502     return ImplicitConversionSequence::Indistinguishable;
3503 
3504   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3505     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3506     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3507     if (Block1 != Block2)
3508       return Block1 ? ImplicitConversionSequence::Worse
3509                     : ImplicitConversionSequence::Better;
3510   }
3511 
3512   return ImplicitConversionSequence::Indistinguishable;
3513 }
3514 
3515 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3516     const ImplicitConversionSequence &ICS) {
3517   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3518          (ICS.isUserDefined() &&
3519           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3520 }
3521 
3522 /// CompareImplicitConversionSequences - Compare two implicit
3523 /// conversion sequences to determine whether one is better than the
3524 /// other or if they are indistinguishable (C++ 13.3.3.2).
3525 static ImplicitConversionSequence::CompareKind
3526 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3527                                    const ImplicitConversionSequence& ICS1,
3528                                    const ImplicitConversionSequence& ICS2)
3529 {
3530   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3531   // conversion sequences (as defined in 13.3.3.1)
3532   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3533   //      conversion sequence than a user-defined conversion sequence or
3534   //      an ellipsis conversion sequence, and
3535   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3536   //      conversion sequence than an ellipsis conversion sequence
3537   //      (13.3.3.1.3).
3538   //
3539   // C++0x [over.best.ics]p10:
3540   //   For the purpose of ranking implicit conversion sequences as
3541   //   described in 13.3.3.2, the ambiguous conversion sequence is
3542   //   treated as a user-defined sequence that is indistinguishable
3543   //   from any other user-defined conversion sequence.
3544 
3545   // String literal to 'char *' conversion has been deprecated in C++03. It has
3546   // been removed from C++11. We still accept this conversion, if it happens at
3547   // the best viable function. Otherwise, this conversion is considered worse
3548   // than ellipsis conversion. Consider this as an extension; this is not in the
3549   // standard. For example:
3550   //
3551   // int &f(...);    // #1
3552   // void f(char*);  // #2
3553   // void g() { int &r = f("foo"); }
3554   //
3555   // In C++03, we pick #2 as the best viable function.
3556   // In C++11, we pick #1 as the best viable function, because ellipsis
3557   // conversion is better than string-literal to char* conversion (since there
3558   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3559   // convert arguments, #2 would be the best viable function in C++11.
3560   // If the best viable function has this conversion, a warning will be issued
3561   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3562 
3563   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3564       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3565       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3566     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3567                ? ImplicitConversionSequence::Worse
3568                : ImplicitConversionSequence::Better;
3569 
3570   if (ICS1.getKindRank() < ICS2.getKindRank())
3571     return ImplicitConversionSequence::Better;
3572   if (ICS2.getKindRank() < ICS1.getKindRank())
3573     return ImplicitConversionSequence::Worse;
3574 
3575   // The following checks require both conversion sequences to be of
3576   // the same kind.
3577   if (ICS1.getKind() != ICS2.getKind())
3578     return ImplicitConversionSequence::Indistinguishable;
3579 
3580   ImplicitConversionSequence::CompareKind Result =
3581       ImplicitConversionSequence::Indistinguishable;
3582 
3583   // Two implicit conversion sequences of the same form are
3584   // indistinguishable conversion sequences unless one of the
3585   // following rules apply: (C++ 13.3.3.2p3):
3586 
3587   // List-initialization sequence L1 is a better conversion sequence than
3588   // list-initialization sequence L2 if:
3589   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3590   //   if not that,
3591   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3592   //   and N1 is smaller than N2.,
3593   // even if one of the other rules in this paragraph would otherwise apply.
3594   if (!ICS1.isBad()) {
3595     if (ICS1.isStdInitializerListElement() &&
3596         !ICS2.isStdInitializerListElement())
3597       return ImplicitConversionSequence::Better;
3598     if (!ICS1.isStdInitializerListElement() &&
3599         ICS2.isStdInitializerListElement())
3600       return ImplicitConversionSequence::Worse;
3601   }
3602 
3603   if (ICS1.isStandard())
3604     // Standard conversion sequence S1 is a better conversion sequence than
3605     // standard conversion sequence S2 if [...]
3606     Result = CompareStandardConversionSequences(S, Loc,
3607                                                 ICS1.Standard, ICS2.Standard);
3608   else if (ICS1.isUserDefined()) {
3609     // User-defined conversion sequence U1 is a better conversion
3610     // sequence than another user-defined conversion sequence U2 if
3611     // they contain the same user-defined conversion function or
3612     // constructor and if the second standard conversion sequence of
3613     // U1 is better than the second standard conversion sequence of
3614     // U2 (C++ 13.3.3.2p3).
3615     if (ICS1.UserDefined.ConversionFunction ==
3616           ICS2.UserDefined.ConversionFunction)
3617       Result = CompareStandardConversionSequences(S, Loc,
3618                                                   ICS1.UserDefined.After,
3619                                                   ICS2.UserDefined.After);
3620     else
3621       Result = compareConversionFunctions(S,
3622                                           ICS1.UserDefined.ConversionFunction,
3623                                           ICS2.UserDefined.ConversionFunction);
3624   }
3625 
3626   return Result;
3627 }
3628 
3629 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3630   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3631     Qualifiers Quals;
3632     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3633     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3634   }
3635 
3636   return Context.hasSameUnqualifiedType(T1, T2);
3637 }
3638 
3639 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3640 // determine if one is a proper subset of the other.
3641 static ImplicitConversionSequence::CompareKind
3642 compareStandardConversionSubsets(ASTContext &Context,
3643                                  const StandardConversionSequence& SCS1,
3644                                  const StandardConversionSequence& SCS2) {
3645   ImplicitConversionSequence::CompareKind Result
3646     = ImplicitConversionSequence::Indistinguishable;
3647 
3648   // the identity conversion sequence is considered to be a subsequence of
3649   // any non-identity conversion sequence
3650   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3651     return ImplicitConversionSequence::Better;
3652   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3653     return ImplicitConversionSequence::Worse;
3654 
3655   if (SCS1.Second != SCS2.Second) {
3656     if (SCS1.Second == ICK_Identity)
3657       Result = ImplicitConversionSequence::Better;
3658     else if (SCS2.Second == ICK_Identity)
3659       Result = ImplicitConversionSequence::Worse;
3660     else
3661       return ImplicitConversionSequence::Indistinguishable;
3662   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3663     return ImplicitConversionSequence::Indistinguishable;
3664 
3665   if (SCS1.Third == SCS2.Third) {
3666     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3667                              : ImplicitConversionSequence::Indistinguishable;
3668   }
3669 
3670   if (SCS1.Third == ICK_Identity)
3671     return Result == ImplicitConversionSequence::Worse
3672              ? ImplicitConversionSequence::Indistinguishable
3673              : ImplicitConversionSequence::Better;
3674 
3675   if (SCS2.Third == ICK_Identity)
3676     return Result == ImplicitConversionSequence::Better
3677              ? ImplicitConversionSequence::Indistinguishable
3678              : ImplicitConversionSequence::Worse;
3679 
3680   return ImplicitConversionSequence::Indistinguishable;
3681 }
3682 
3683 /// \brief Determine whether one of the given reference bindings is better
3684 /// than the other based on what kind of bindings they are.
3685 static bool
3686 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3687                              const StandardConversionSequence &SCS2) {
3688   // C++0x [over.ics.rank]p3b4:
3689   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3690   //      implicit object parameter of a non-static member function declared
3691   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3692   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3693   //      lvalue reference to a function lvalue and S2 binds an rvalue
3694   //      reference*.
3695   //
3696   // FIXME: Rvalue references. We're going rogue with the above edits,
3697   // because the semantics in the current C++0x working paper (N3225 at the
3698   // time of this writing) break the standard definition of std::forward
3699   // and std::reference_wrapper when dealing with references to functions.
3700   // Proposed wording changes submitted to CWG for consideration.
3701   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3702       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3703     return false;
3704 
3705   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3706           SCS2.IsLvalueReference) ||
3707          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3708           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3709 }
3710 
3711 /// CompareStandardConversionSequences - Compare two standard
3712 /// conversion sequences to determine whether one is better than the
3713 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3714 static ImplicitConversionSequence::CompareKind
3715 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3716                                    const StandardConversionSequence& SCS1,
3717                                    const StandardConversionSequence& SCS2)
3718 {
3719   // Standard conversion sequence S1 is a better conversion sequence
3720   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3721 
3722   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3723   //     sequences in the canonical form defined by 13.3.3.1.1,
3724   //     excluding any Lvalue Transformation; the identity conversion
3725   //     sequence is considered to be a subsequence of any
3726   //     non-identity conversion sequence) or, if not that,
3727   if (ImplicitConversionSequence::CompareKind CK
3728         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3729     return CK;
3730 
3731   //  -- the rank of S1 is better than the rank of S2 (by the rules
3732   //     defined below), or, if not that,
3733   ImplicitConversionRank Rank1 = SCS1.getRank();
3734   ImplicitConversionRank Rank2 = SCS2.getRank();
3735   if (Rank1 < Rank2)
3736     return ImplicitConversionSequence::Better;
3737   else if (Rank2 < Rank1)
3738     return ImplicitConversionSequence::Worse;
3739 
3740   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3741   // are indistinguishable unless one of the following rules
3742   // applies:
3743 
3744   //   A conversion that is not a conversion of a pointer, or
3745   //   pointer to member, to bool is better than another conversion
3746   //   that is such a conversion.
3747   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3748     return SCS2.isPointerConversionToBool()
3749              ? ImplicitConversionSequence::Better
3750              : ImplicitConversionSequence::Worse;
3751 
3752   // C++ [over.ics.rank]p4b2:
3753   //
3754   //   If class B is derived directly or indirectly from class A,
3755   //   conversion of B* to A* is better than conversion of B* to
3756   //   void*, and conversion of A* to void* is better than conversion
3757   //   of B* to void*.
3758   bool SCS1ConvertsToVoid
3759     = SCS1.isPointerConversionToVoidPointer(S.Context);
3760   bool SCS2ConvertsToVoid
3761     = SCS2.isPointerConversionToVoidPointer(S.Context);
3762   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3763     // Exactly one of the conversion sequences is a conversion to
3764     // a void pointer; it's the worse conversion.
3765     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3766                               : ImplicitConversionSequence::Worse;
3767   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3768     // Neither conversion sequence converts to a void pointer; compare
3769     // their derived-to-base conversions.
3770     if (ImplicitConversionSequence::CompareKind DerivedCK
3771           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3772       return DerivedCK;
3773   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3774              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3775     // Both conversion sequences are conversions to void
3776     // pointers. Compare the source types to determine if there's an
3777     // inheritance relationship in their sources.
3778     QualType FromType1 = SCS1.getFromType();
3779     QualType FromType2 = SCS2.getFromType();
3780 
3781     // Adjust the types we're converting from via the array-to-pointer
3782     // conversion, if we need to.
3783     if (SCS1.First == ICK_Array_To_Pointer)
3784       FromType1 = S.Context.getArrayDecayedType(FromType1);
3785     if (SCS2.First == ICK_Array_To_Pointer)
3786       FromType2 = S.Context.getArrayDecayedType(FromType2);
3787 
3788     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3789     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3790 
3791     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3792       return ImplicitConversionSequence::Better;
3793     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3794       return ImplicitConversionSequence::Worse;
3795 
3796     // Objective-C++: If one interface is more specific than the
3797     // other, it is the better one.
3798     const ObjCObjectPointerType* FromObjCPtr1
3799       = FromType1->getAs<ObjCObjectPointerType>();
3800     const ObjCObjectPointerType* FromObjCPtr2
3801       = FromType2->getAs<ObjCObjectPointerType>();
3802     if (FromObjCPtr1 && FromObjCPtr2) {
3803       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3804                                                           FromObjCPtr2);
3805       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3806                                                            FromObjCPtr1);
3807       if (AssignLeft != AssignRight) {
3808         return AssignLeft? ImplicitConversionSequence::Better
3809                          : ImplicitConversionSequence::Worse;
3810       }
3811     }
3812   }
3813 
3814   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3815   // bullet 3).
3816   if (ImplicitConversionSequence::CompareKind QualCK
3817         = CompareQualificationConversions(S, SCS1, SCS2))
3818     return QualCK;
3819 
3820   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3821     // Check for a better reference binding based on the kind of bindings.
3822     if (isBetterReferenceBindingKind(SCS1, SCS2))
3823       return ImplicitConversionSequence::Better;
3824     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3825       return ImplicitConversionSequence::Worse;
3826 
3827     // C++ [over.ics.rank]p3b4:
3828     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3829     //      which the references refer are the same type except for
3830     //      top-level cv-qualifiers, and the type to which the reference
3831     //      initialized by S2 refers is more cv-qualified than the type
3832     //      to which the reference initialized by S1 refers.
3833     QualType T1 = SCS1.getToType(2);
3834     QualType T2 = SCS2.getToType(2);
3835     T1 = S.Context.getCanonicalType(T1);
3836     T2 = S.Context.getCanonicalType(T2);
3837     Qualifiers T1Quals, T2Quals;
3838     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3839     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3840     if (UnqualT1 == UnqualT2) {
3841       // Objective-C++ ARC: If the references refer to objects with different
3842       // lifetimes, prefer bindings that don't change lifetime.
3843       if (SCS1.ObjCLifetimeConversionBinding !=
3844                                           SCS2.ObjCLifetimeConversionBinding) {
3845         return SCS1.ObjCLifetimeConversionBinding
3846                                            ? ImplicitConversionSequence::Worse
3847                                            : ImplicitConversionSequence::Better;
3848       }
3849 
3850       // If the type is an array type, promote the element qualifiers to the
3851       // type for comparison.
3852       if (isa<ArrayType>(T1) && T1Quals)
3853         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3854       if (isa<ArrayType>(T2) && T2Quals)
3855         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3856       if (T2.isMoreQualifiedThan(T1))
3857         return ImplicitConversionSequence::Better;
3858       else if (T1.isMoreQualifiedThan(T2))
3859         return ImplicitConversionSequence::Worse;
3860     }
3861   }
3862 
3863   // In Microsoft mode, prefer an integral conversion to a
3864   // floating-to-integral conversion if the integral conversion
3865   // is between types of the same size.
3866   // For example:
3867   // void f(float);
3868   // void f(int);
3869   // int main {
3870   //    long a;
3871   //    f(a);
3872   // }
3873   // Here, MSVC will call f(int) instead of generating a compile error
3874   // as clang will do in standard mode.
3875   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3876       SCS2.Second == ICK_Floating_Integral &&
3877       S.Context.getTypeSize(SCS1.getFromType()) ==
3878           S.Context.getTypeSize(SCS1.getToType(2)))
3879     return ImplicitConversionSequence::Better;
3880 
3881   return ImplicitConversionSequence::Indistinguishable;
3882 }
3883 
3884 /// CompareQualificationConversions - Compares two standard conversion
3885 /// sequences to determine whether they can be ranked based on their
3886 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3887 static ImplicitConversionSequence::CompareKind
3888 CompareQualificationConversions(Sema &S,
3889                                 const StandardConversionSequence& SCS1,
3890                                 const StandardConversionSequence& SCS2) {
3891   // C++ 13.3.3.2p3:
3892   //  -- S1 and S2 differ only in their qualification conversion and
3893   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3894   //     cv-qualification signature of type T1 is a proper subset of
3895   //     the cv-qualification signature of type T2, and S1 is not the
3896   //     deprecated string literal array-to-pointer conversion (4.2).
3897   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3898       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3899     return ImplicitConversionSequence::Indistinguishable;
3900 
3901   // FIXME: the example in the standard doesn't use a qualification
3902   // conversion (!)
3903   QualType T1 = SCS1.getToType(2);
3904   QualType T2 = SCS2.getToType(2);
3905   T1 = S.Context.getCanonicalType(T1);
3906   T2 = S.Context.getCanonicalType(T2);
3907   Qualifiers T1Quals, T2Quals;
3908   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3909   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3910 
3911   // If the types are the same, we won't learn anything by unwrapped
3912   // them.
3913   if (UnqualT1 == UnqualT2)
3914     return ImplicitConversionSequence::Indistinguishable;
3915 
3916   // If the type is an array type, promote the element qualifiers to the type
3917   // for comparison.
3918   if (isa<ArrayType>(T1) && T1Quals)
3919     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3920   if (isa<ArrayType>(T2) && T2Quals)
3921     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3922 
3923   ImplicitConversionSequence::CompareKind Result
3924     = ImplicitConversionSequence::Indistinguishable;
3925 
3926   // Objective-C++ ARC:
3927   //   Prefer qualification conversions not involving a change in lifetime
3928   //   to qualification conversions that do not change lifetime.
3929   if (SCS1.QualificationIncludesObjCLifetime !=
3930                                       SCS2.QualificationIncludesObjCLifetime) {
3931     Result = SCS1.QualificationIncludesObjCLifetime
3932                ? ImplicitConversionSequence::Worse
3933                : ImplicitConversionSequence::Better;
3934   }
3935 
3936   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3937     // Within each iteration of the loop, we check the qualifiers to
3938     // determine if this still looks like a qualification
3939     // conversion. Then, if all is well, we unwrap one more level of
3940     // pointers or pointers-to-members and do it all again
3941     // until there are no more pointers or pointers-to-members left
3942     // to unwrap. This essentially mimics what
3943     // IsQualificationConversion does, but here we're checking for a
3944     // strict subset of qualifiers.
3945     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3946       // The qualifiers are the same, so this doesn't tell us anything
3947       // about how the sequences rank.
3948       ;
3949     else if (T2.isMoreQualifiedThan(T1)) {
3950       // T1 has fewer qualifiers, so it could be the better sequence.
3951       if (Result == ImplicitConversionSequence::Worse)
3952         // Neither has qualifiers that are a subset of the other's
3953         // qualifiers.
3954         return ImplicitConversionSequence::Indistinguishable;
3955 
3956       Result = ImplicitConversionSequence::Better;
3957     } else if (T1.isMoreQualifiedThan(T2)) {
3958       // T2 has fewer qualifiers, so it could be the better sequence.
3959       if (Result == ImplicitConversionSequence::Better)
3960         // Neither has qualifiers that are a subset of the other's
3961         // qualifiers.
3962         return ImplicitConversionSequence::Indistinguishable;
3963 
3964       Result = ImplicitConversionSequence::Worse;
3965     } else {
3966       // Qualifiers are disjoint.
3967       return ImplicitConversionSequence::Indistinguishable;
3968     }
3969 
3970     // If the types after this point are equivalent, we're done.
3971     if (S.Context.hasSameUnqualifiedType(T1, T2))
3972       break;
3973   }
3974 
3975   // Check that the winning standard conversion sequence isn't using
3976   // the deprecated string literal array to pointer conversion.
3977   switch (Result) {
3978   case ImplicitConversionSequence::Better:
3979     if (SCS1.DeprecatedStringLiteralToCharPtr)
3980       Result = ImplicitConversionSequence::Indistinguishable;
3981     break;
3982 
3983   case ImplicitConversionSequence::Indistinguishable:
3984     break;
3985 
3986   case ImplicitConversionSequence::Worse:
3987     if (SCS2.DeprecatedStringLiteralToCharPtr)
3988       Result = ImplicitConversionSequence::Indistinguishable;
3989     break;
3990   }
3991 
3992   return Result;
3993 }
3994 
3995 /// CompareDerivedToBaseConversions - Compares two standard conversion
3996 /// sequences to determine whether they can be ranked based on their
3997 /// various kinds of derived-to-base conversions (C++
3998 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3999 /// conversions between Objective-C interface types.
4000 static ImplicitConversionSequence::CompareKind
4001 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4002                                 const StandardConversionSequence& SCS1,
4003                                 const StandardConversionSequence& SCS2) {
4004   QualType FromType1 = SCS1.getFromType();
4005   QualType ToType1 = SCS1.getToType(1);
4006   QualType FromType2 = SCS2.getFromType();
4007   QualType ToType2 = SCS2.getToType(1);
4008 
4009   // Adjust the types we're converting from via the array-to-pointer
4010   // conversion, if we need to.
4011   if (SCS1.First == ICK_Array_To_Pointer)
4012     FromType1 = S.Context.getArrayDecayedType(FromType1);
4013   if (SCS2.First == ICK_Array_To_Pointer)
4014     FromType2 = S.Context.getArrayDecayedType(FromType2);
4015 
4016   // Canonicalize all of the types.
4017   FromType1 = S.Context.getCanonicalType(FromType1);
4018   ToType1 = S.Context.getCanonicalType(ToType1);
4019   FromType2 = S.Context.getCanonicalType(FromType2);
4020   ToType2 = S.Context.getCanonicalType(ToType2);
4021 
4022   // C++ [over.ics.rank]p4b3:
4023   //
4024   //   If class B is derived directly or indirectly from class A and
4025   //   class C is derived directly or indirectly from B,
4026   //
4027   // Compare based on pointer conversions.
4028   if (SCS1.Second == ICK_Pointer_Conversion &&
4029       SCS2.Second == ICK_Pointer_Conversion &&
4030       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4031       FromType1->isPointerType() && FromType2->isPointerType() &&
4032       ToType1->isPointerType() && ToType2->isPointerType()) {
4033     QualType FromPointee1
4034       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4035     QualType ToPointee1
4036       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4037     QualType FromPointee2
4038       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4039     QualType ToPointee2
4040       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4041 
4042     //   -- conversion of C* to B* is better than conversion of C* to A*,
4043     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4044       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4045         return ImplicitConversionSequence::Better;
4046       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4047         return ImplicitConversionSequence::Worse;
4048     }
4049 
4050     //   -- conversion of B* to A* is better than conversion of C* to A*,
4051     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4052       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4053         return ImplicitConversionSequence::Better;
4054       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4055         return ImplicitConversionSequence::Worse;
4056     }
4057   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4058              SCS2.Second == ICK_Pointer_Conversion) {
4059     const ObjCObjectPointerType *FromPtr1
4060       = FromType1->getAs<ObjCObjectPointerType>();
4061     const ObjCObjectPointerType *FromPtr2
4062       = FromType2->getAs<ObjCObjectPointerType>();
4063     const ObjCObjectPointerType *ToPtr1
4064       = ToType1->getAs<ObjCObjectPointerType>();
4065     const ObjCObjectPointerType *ToPtr2
4066       = ToType2->getAs<ObjCObjectPointerType>();
4067 
4068     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4069       // Apply the same conversion ranking rules for Objective-C pointer types
4070       // that we do for C++ pointers to class types. However, we employ the
4071       // Objective-C pseudo-subtyping relationship used for assignment of
4072       // Objective-C pointer types.
4073       bool FromAssignLeft
4074         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4075       bool FromAssignRight
4076         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4077       bool ToAssignLeft
4078         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4079       bool ToAssignRight
4080         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4081 
4082       // A conversion to an a non-id object pointer type or qualified 'id'
4083       // type is better than a conversion to 'id'.
4084       if (ToPtr1->isObjCIdType() &&
4085           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4086         return ImplicitConversionSequence::Worse;
4087       if (ToPtr2->isObjCIdType() &&
4088           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4089         return ImplicitConversionSequence::Better;
4090 
4091       // A conversion to a non-id object pointer type is better than a
4092       // conversion to a qualified 'id' type
4093       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4094         return ImplicitConversionSequence::Worse;
4095       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4096         return ImplicitConversionSequence::Better;
4097 
4098       // A conversion to an a non-Class object pointer type or qualified 'Class'
4099       // type is better than a conversion to 'Class'.
4100       if (ToPtr1->isObjCClassType() &&
4101           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4102         return ImplicitConversionSequence::Worse;
4103       if (ToPtr2->isObjCClassType() &&
4104           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4105         return ImplicitConversionSequence::Better;
4106 
4107       // A conversion to a non-Class object pointer type is better than a
4108       // conversion to a qualified 'Class' type.
4109       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4110         return ImplicitConversionSequence::Worse;
4111       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4112         return ImplicitConversionSequence::Better;
4113 
4114       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4115       if (S.Context.hasSameType(FromType1, FromType2) &&
4116           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4117           (ToAssignLeft != ToAssignRight)) {
4118         if (FromPtr1->isSpecialized()) {
4119           // "conversion of B<A> * to B * is better than conversion of B * to
4120           // C *.
4121           bool IsFirstSame =
4122               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4123           bool IsSecondSame =
4124               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4125           if (IsFirstSame) {
4126             if (!IsSecondSame)
4127               return ImplicitConversionSequence::Better;
4128           } else if (IsSecondSame)
4129             return ImplicitConversionSequence::Worse;
4130         }
4131         return ToAssignLeft? ImplicitConversionSequence::Worse
4132                            : ImplicitConversionSequence::Better;
4133       }
4134 
4135       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4136       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4137           (FromAssignLeft != FromAssignRight))
4138         return FromAssignLeft? ImplicitConversionSequence::Better
4139         : ImplicitConversionSequence::Worse;
4140     }
4141   }
4142 
4143   // Ranking of member-pointer types.
4144   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4145       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4146       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4147     const MemberPointerType * FromMemPointer1 =
4148                                         FromType1->getAs<MemberPointerType>();
4149     const MemberPointerType * ToMemPointer1 =
4150                                           ToType1->getAs<MemberPointerType>();
4151     const MemberPointerType * FromMemPointer2 =
4152                                           FromType2->getAs<MemberPointerType>();
4153     const MemberPointerType * ToMemPointer2 =
4154                                           ToType2->getAs<MemberPointerType>();
4155     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4156     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4157     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4158     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4159     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4160     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4161     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4162     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4163     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4164     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4165       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4166         return ImplicitConversionSequence::Worse;
4167       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4168         return ImplicitConversionSequence::Better;
4169     }
4170     // conversion of B::* to C::* is better than conversion of A::* to C::*
4171     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4172       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4173         return ImplicitConversionSequence::Better;
4174       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4175         return ImplicitConversionSequence::Worse;
4176     }
4177   }
4178 
4179   if (SCS1.Second == ICK_Derived_To_Base) {
4180     //   -- conversion of C to B is better than conversion of C to A,
4181     //   -- binding of an expression of type C to a reference of type
4182     //      B& is better than binding an expression of type C to a
4183     //      reference of type A&,
4184     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4185         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4186       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4187         return ImplicitConversionSequence::Better;
4188       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4189         return ImplicitConversionSequence::Worse;
4190     }
4191 
4192     //   -- conversion of B to A is better than conversion of C to A.
4193     //   -- binding of an expression of type B to a reference of type
4194     //      A& is better than binding an expression of type C to a
4195     //      reference of type A&,
4196     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4197         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4198       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4199         return ImplicitConversionSequence::Better;
4200       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4201         return ImplicitConversionSequence::Worse;
4202     }
4203   }
4204 
4205   return ImplicitConversionSequence::Indistinguishable;
4206 }
4207 
4208 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4209 /// C++ class.
4210 static bool isTypeValid(QualType T) {
4211   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4212     return !Record->isInvalidDecl();
4213 
4214   return true;
4215 }
4216 
4217 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4218 /// determine whether they are reference-related,
4219 /// reference-compatible, reference-compatible with added
4220 /// qualification, or incompatible, for use in C++ initialization by
4221 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4222 /// type, and the first type (T1) is the pointee type of the reference
4223 /// type being initialized.
4224 Sema::ReferenceCompareResult
4225 Sema::CompareReferenceRelationship(SourceLocation Loc,
4226                                    QualType OrigT1, QualType OrigT2,
4227                                    bool &DerivedToBase,
4228                                    bool &ObjCConversion,
4229                                    bool &ObjCLifetimeConversion) {
4230   assert(!OrigT1->isReferenceType() &&
4231     "T1 must be the pointee type of the reference type");
4232   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4233 
4234   QualType T1 = Context.getCanonicalType(OrigT1);
4235   QualType T2 = Context.getCanonicalType(OrigT2);
4236   Qualifiers T1Quals, T2Quals;
4237   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4238   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4239 
4240   // C++ [dcl.init.ref]p4:
4241   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4242   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4243   //   T1 is a base class of T2.
4244   DerivedToBase = false;
4245   ObjCConversion = false;
4246   ObjCLifetimeConversion = false;
4247   QualType ConvertedT2;
4248   if (UnqualT1 == UnqualT2) {
4249     // Nothing to do.
4250   } else if (isCompleteType(Loc, OrigT2) &&
4251              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4252              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4253     DerivedToBase = true;
4254   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4255            UnqualT2->isObjCObjectOrInterfaceType() &&
4256            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4257     ObjCConversion = true;
4258   else if (UnqualT2->isFunctionType() &&
4259            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4260     // C++1z [dcl.init.ref]p4:
4261     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4262     //   function" and T1 is "function"
4263     //
4264     // We extend this to also apply to 'noreturn', so allow any function
4265     // conversion between function types.
4266     return Ref_Compatible;
4267   else
4268     return Ref_Incompatible;
4269 
4270   // At this point, we know that T1 and T2 are reference-related (at
4271   // least).
4272 
4273   // If the type is an array type, promote the element qualifiers to the type
4274   // for comparison.
4275   if (isa<ArrayType>(T1) && T1Quals)
4276     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4277   if (isa<ArrayType>(T2) && T2Quals)
4278     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4279 
4280   // C++ [dcl.init.ref]p4:
4281   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4282   //   reference-related to T2 and cv1 is the same cv-qualification
4283   //   as, or greater cv-qualification than, cv2. For purposes of
4284   //   overload resolution, cases for which cv1 is greater
4285   //   cv-qualification than cv2 are identified as
4286   //   reference-compatible with added qualification (see 13.3.3.2).
4287   //
4288   // Note that we also require equivalence of Objective-C GC and address-space
4289   // qualifiers when performing these computations, so that e.g., an int in
4290   // address space 1 is not reference-compatible with an int in address
4291   // space 2.
4292   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4293       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4294     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4295       ObjCLifetimeConversion = true;
4296 
4297     T1Quals.removeObjCLifetime();
4298     T2Quals.removeObjCLifetime();
4299   }
4300 
4301   // MS compiler ignores __unaligned qualifier for references; do the same.
4302   T1Quals.removeUnaligned();
4303   T2Quals.removeUnaligned();
4304 
4305   if (T1Quals.compatiblyIncludes(T2Quals))
4306     return Ref_Compatible;
4307   else
4308     return Ref_Related;
4309 }
4310 
4311 /// \brief Look for a user-defined conversion to a value reference-compatible
4312 ///        with DeclType. Return true if something definite is found.
4313 static bool
4314 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4315                          QualType DeclType, SourceLocation DeclLoc,
4316                          Expr *Init, QualType T2, bool AllowRvalues,
4317                          bool AllowExplicit) {
4318   assert(T2->isRecordType() && "Can only find conversions of record types.");
4319   CXXRecordDecl *T2RecordDecl
4320     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4321 
4322   OverloadCandidateSet CandidateSet(
4323       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4324   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4325   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4326     NamedDecl *D = *I;
4327     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4328     if (isa<UsingShadowDecl>(D))
4329       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4330 
4331     FunctionTemplateDecl *ConvTemplate
4332       = dyn_cast<FunctionTemplateDecl>(D);
4333     CXXConversionDecl *Conv;
4334     if (ConvTemplate)
4335       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4336     else
4337       Conv = cast<CXXConversionDecl>(D);
4338 
4339     // If this is an explicit conversion, and we're not allowed to consider
4340     // explicit conversions, skip it.
4341     if (!AllowExplicit && Conv->isExplicit())
4342       continue;
4343 
4344     if (AllowRvalues) {
4345       bool DerivedToBase = false;
4346       bool ObjCConversion = false;
4347       bool ObjCLifetimeConversion = false;
4348 
4349       // If we are initializing an rvalue reference, don't permit conversion
4350       // functions that return lvalues.
4351       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4352         const ReferenceType *RefType
4353           = Conv->getConversionType()->getAs<LValueReferenceType>();
4354         if (RefType && !RefType->getPointeeType()->isFunctionType())
4355           continue;
4356       }
4357 
4358       if (!ConvTemplate &&
4359           S.CompareReferenceRelationship(
4360             DeclLoc,
4361             Conv->getConversionType().getNonReferenceType()
4362               .getUnqualifiedType(),
4363             DeclType.getNonReferenceType().getUnqualifiedType(),
4364             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4365           Sema::Ref_Incompatible)
4366         continue;
4367     } else {
4368       // If the conversion function doesn't return a reference type,
4369       // it can't be considered for this conversion. An rvalue reference
4370       // is only acceptable if its referencee is a function type.
4371 
4372       const ReferenceType *RefType =
4373         Conv->getConversionType()->getAs<ReferenceType>();
4374       if (!RefType ||
4375           (!RefType->isLValueReferenceType() &&
4376            !RefType->getPointeeType()->isFunctionType()))
4377         continue;
4378     }
4379 
4380     if (ConvTemplate)
4381       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4382                                        Init, DeclType, CandidateSet,
4383                                        /*AllowObjCConversionOnExplicit=*/false);
4384     else
4385       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4386                                DeclType, CandidateSet,
4387                                /*AllowObjCConversionOnExplicit=*/false);
4388   }
4389 
4390   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4391 
4392   OverloadCandidateSet::iterator Best;
4393   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4394   case OR_Success:
4395     // C++ [over.ics.ref]p1:
4396     //
4397     //   [...] If the parameter binds directly to the result of
4398     //   applying a conversion function to the argument
4399     //   expression, the implicit conversion sequence is a
4400     //   user-defined conversion sequence (13.3.3.1.2), with the
4401     //   second standard conversion sequence either an identity
4402     //   conversion or, if the conversion function returns an
4403     //   entity of a type that is a derived class of the parameter
4404     //   type, a derived-to-base Conversion.
4405     if (!Best->FinalConversion.DirectBinding)
4406       return false;
4407 
4408     ICS.setUserDefined();
4409     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4410     ICS.UserDefined.After = Best->FinalConversion;
4411     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4412     ICS.UserDefined.ConversionFunction = Best->Function;
4413     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4414     ICS.UserDefined.EllipsisConversion = false;
4415     assert(ICS.UserDefined.After.ReferenceBinding &&
4416            ICS.UserDefined.After.DirectBinding &&
4417            "Expected a direct reference binding!");
4418     return true;
4419 
4420   case OR_Ambiguous:
4421     ICS.setAmbiguous();
4422     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4423          Cand != CandidateSet.end(); ++Cand)
4424       if (Cand->Viable)
4425         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4426     return true;
4427 
4428   case OR_No_Viable_Function:
4429   case OR_Deleted:
4430     // There was no suitable conversion, or we found a deleted
4431     // conversion; continue with other checks.
4432     return false;
4433   }
4434 
4435   llvm_unreachable("Invalid OverloadResult!");
4436 }
4437 
4438 /// \brief Compute an implicit conversion sequence for reference
4439 /// initialization.
4440 static ImplicitConversionSequence
4441 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4442                  SourceLocation DeclLoc,
4443                  bool SuppressUserConversions,
4444                  bool AllowExplicit) {
4445   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4446 
4447   // Most paths end in a failed conversion.
4448   ImplicitConversionSequence ICS;
4449   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4450 
4451   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4452   QualType T2 = Init->getType();
4453 
4454   // If the initializer is the address of an overloaded function, try
4455   // to resolve the overloaded function. If all goes well, T2 is the
4456   // type of the resulting function.
4457   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4458     DeclAccessPair Found;
4459     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4460                                                                 false, Found))
4461       T2 = Fn->getType();
4462   }
4463 
4464   // Compute some basic properties of the types and the initializer.
4465   bool isRValRef = DeclType->isRValueReferenceType();
4466   bool DerivedToBase = false;
4467   bool ObjCConversion = false;
4468   bool ObjCLifetimeConversion = false;
4469   Expr::Classification InitCategory = Init->Classify(S.Context);
4470   Sema::ReferenceCompareResult RefRelationship
4471     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4472                                      ObjCConversion, ObjCLifetimeConversion);
4473 
4474 
4475   // C++0x [dcl.init.ref]p5:
4476   //   A reference to type "cv1 T1" is initialized by an expression
4477   //   of type "cv2 T2" as follows:
4478 
4479   //     -- If reference is an lvalue reference and the initializer expression
4480   if (!isRValRef) {
4481     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4482     //        reference-compatible with "cv2 T2," or
4483     //
4484     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4485     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4486       // C++ [over.ics.ref]p1:
4487       //   When a parameter of reference type binds directly (8.5.3)
4488       //   to an argument expression, the implicit conversion sequence
4489       //   is the identity conversion, unless the argument expression
4490       //   has a type that is a derived class of the parameter type,
4491       //   in which case the implicit conversion sequence is a
4492       //   derived-to-base Conversion (13.3.3.1).
4493       ICS.setStandard();
4494       ICS.Standard.First = ICK_Identity;
4495       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4496                          : ObjCConversion? ICK_Compatible_Conversion
4497                          : ICK_Identity;
4498       ICS.Standard.Third = ICK_Identity;
4499       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4500       ICS.Standard.setToType(0, T2);
4501       ICS.Standard.setToType(1, T1);
4502       ICS.Standard.setToType(2, T1);
4503       ICS.Standard.ReferenceBinding = true;
4504       ICS.Standard.DirectBinding = true;
4505       ICS.Standard.IsLvalueReference = !isRValRef;
4506       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4507       ICS.Standard.BindsToRvalue = false;
4508       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4509       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4510       ICS.Standard.CopyConstructor = nullptr;
4511       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4512 
4513       // Nothing more to do: the inaccessibility/ambiguity check for
4514       // derived-to-base conversions is suppressed when we're
4515       // computing the implicit conversion sequence (C++
4516       // [over.best.ics]p2).
4517       return ICS;
4518     }
4519 
4520     //       -- has a class type (i.e., T2 is a class type), where T1 is
4521     //          not reference-related to T2, and can be implicitly
4522     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4523     //          is reference-compatible with "cv3 T3" 92) (this
4524     //          conversion is selected by enumerating the applicable
4525     //          conversion functions (13.3.1.6) and choosing the best
4526     //          one through overload resolution (13.3)),
4527     if (!SuppressUserConversions && T2->isRecordType() &&
4528         S.isCompleteType(DeclLoc, T2) &&
4529         RefRelationship == Sema::Ref_Incompatible) {
4530       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4531                                    Init, T2, /*AllowRvalues=*/false,
4532                                    AllowExplicit))
4533         return ICS;
4534     }
4535   }
4536 
4537   //     -- Otherwise, the reference shall be an lvalue reference to a
4538   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4539   //        shall be an rvalue reference.
4540   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4541     return ICS;
4542 
4543   //       -- If the initializer expression
4544   //
4545   //            -- is an xvalue, class prvalue, array prvalue or function
4546   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4547   if (RefRelationship == Sema::Ref_Compatible &&
4548       (InitCategory.isXValue() ||
4549        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4550        (InitCategory.isLValue() && T2->isFunctionType()))) {
4551     ICS.setStandard();
4552     ICS.Standard.First = ICK_Identity;
4553     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4554                       : ObjCConversion? ICK_Compatible_Conversion
4555                       : ICK_Identity;
4556     ICS.Standard.Third = ICK_Identity;
4557     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4558     ICS.Standard.setToType(0, T2);
4559     ICS.Standard.setToType(1, T1);
4560     ICS.Standard.setToType(2, T1);
4561     ICS.Standard.ReferenceBinding = true;
4562     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4563     // binding unless we're binding to a class prvalue.
4564     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4565     // allow the use of rvalue references in C++98/03 for the benefit of
4566     // standard library implementors; therefore, we need the xvalue check here.
4567     ICS.Standard.DirectBinding =
4568       S.getLangOpts().CPlusPlus11 ||
4569       !(InitCategory.isPRValue() || T2->isRecordType());
4570     ICS.Standard.IsLvalueReference = !isRValRef;
4571     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4572     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4573     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4574     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4575     ICS.Standard.CopyConstructor = nullptr;
4576     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4577     return ICS;
4578   }
4579 
4580   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4581   //               reference-related to T2, and can be implicitly converted to
4582   //               an xvalue, class prvalue, or function lvalue of type
4583   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4584   //               "cv3 T3",
4585   //
4586   //          then the reference is bound to the value of the initializer
4587   //          expression in the first case and to the result of the conversion
4588   //          in the second case (or, in either case, to an appropriate base
4589   //          class subobject).
4590   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4591       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4592       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4593                                Init, T2, /*AllowRvalues=*/true,
4594                                AllowExplicit)) {
4595     // In the second case, if the reference is an rvalue reference
4596     // and the second standard conversion sequence of the
4597     // user-defined conversion sequence includes an lvalue-to-rvalue
4598     // conversion, the program is ill-formed.
4599     if (ICS.isUserDefined() && isRValRef &&
4600         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4601       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4602 
4603     return ICS;
4604   }
4605 
4606   // A temporary of function type cannot be created; don't even try.
4607   if (T1->isFunctionType())
4608     return ICS;
4609 
4610   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4611   //          initialized from the initializer expression using the
4612   //          rules for a non-reference copy initialization (8.5). The
4613   //          reference is then bound to the temporary. If T1 is
4614   //          reference-related to T2, cv1 must be the same
4615   //          cv-qualification as, or greater cv-qualification than,
4616   //          cv2; otherwise, the program is ill-formed.
4617   if (RefRelationship == Sema::Ref_Related) {
4618     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4619     // we would be reference-compatible or reference-compatible with
4620     // added qualification. But that wasn't the case, so the reference
4621     // initialization fails.
4622     //
4623     // Note that we only want to check address spaces and cvr-qualifiers here.
4624     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4625     Qualifiers T1Quals = T1.getQualifiers();
4626     Qualifiers T2Quals = T2.getQualifiers();
4627     T1Quals.removeObjCGCAttr();
4628     T1Quals.removeObjCLifetime();
4629     T2Quals.removeObjCGCAttr();
4630     T2Quals.removeObjCLifetime();
4631     // MS compiler ignores __unaligned qualifier for references; do the same.
4632     T1Quals.removeUnaligned();
4633     T2Quals.removeUnaligned();
4634     if (!T1Quals.compatiblyIncludes(T2Quals))
4635       return ICS;
4636   }
4637 
4638   // If at least one of the types is a class type, the types are not
4639   // related, and we aren't allowed any user conversions, the
4640   // reference binding fails. This case is important for breaking
4641   // recursion, since TryImplicitConversion below will attempt to
4642   // create a temporary through the use of a copy constructor.
4643   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4644       (T1->isRecordType() || T2->isRecordType()))
4645     return ICS;
4646 
4647   // If T1 is reference-related to T2 and the reference is an rvalue
4648   // reference, the initializer expression shall not be an lvalue.
4649   if (RefRelationship >= Sema::Ref_Related &&
4650       isRValRef && Init->Classify(S.Context).isLValue())
4651     return ICS;
4652 
4653   // C++ [over.ics.ref]p2:
4654   //   When a parameter of reference type is not bound directly to
4655   //   an argument expression, the conversion sequence is the one
4656   //   required to convert the argument expression to the
4657   //   underlying type of the reference according to
4658   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4659   //   to copy-initializing a temporary of the underlying type with
4660   //   the argument expression. Any difference in top-level
4661   //   cv-qualification is subsumed by the initialization itself
4662   //   and does not constitute a conversion.
4663   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4664                               /*AllowExplicit=*/false,
4665                               /*InOverloadResolution=*/false,
4666                               /*CStyle=*/false,
4667                               /*AllowObjCWritebackConversion=*/false,
4668                               /*AllowObjCConversionOnExplicit=*/false);
4669 
4670   // Of course, that's still a reference binding.
4671   if (ICS.isStandard()) {
4672     ICS.Standard.ReferenceBinding = true;
4673     ICS.Standard.IsLvalueReference = !isRValRef;
4674     ICS.Standard.BindsToFunctionLvalue = false;
4675     ICS.Standard.BindsToRvalue = true;
4676     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4677     ICS.Standard.ObjCLifetimeConversionBinding = false;
4678   } else if (ICS.isUserDefined()) {
4679     const ReferenceType *LValRefType =
4680         ICS.UserDefined.ConversionFunction->getReturnType()
4681             ->getAs<LValueReferenceType>();
4682 
4683     // C++ [over.ics.ref]p3:
4684     //   Except for an implicit object parameter, for which see 13.3.1, a
4685     //   standard conversion sequence cannot be formed if it requires [...]
4686     //   binding an rvalue reference to an lvalue other than a function
4687     //   lvalue.
4688     // Note that the function case is not possible here.
4689     if (DeclType->isRValueReferenceType() && LValRefType) {
4690       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4691       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4692       // reference to an rvalue!
4693       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4694       return ICS;
4695     }
4696 
4697     ICS.UserDefined.After.ReferenceBinding = true;
4698     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4699     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4700     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4701     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4702     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4703   }
4704 
4705   return ICS;
4706 }
4707 
4708 static ImplicitConversionSequence
4709 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4710                       bool SuppressUserConversions,
4711                       bool InOverloadResolution,
4712                       bool AllowObjCWritebackConversion,
4713                       bool AllowExplicit = false);
4714 
4715 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4716 /// initializer list From.
4717 static ImplicitConversionSequence
4718 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4719                   bool SuppressUserConversions,
4720                   bool InOverloadResolution,
4721                   bool AllowObjCWritebackConversion) {
4722   // C++11 [over.ics.list]p1:
4723   //   When an argument is an initializer list, it is not an expression and
4724   //   special rules apply for converting it to a parameter type.
4725 
4726   ImplicitConversionSequence Result;
4727   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4728 
4729   // We need a complete type for what follows. Incomplete types can never be
4730   // initialized from init lists.
4731   if (!S.isCompleteType(From->getLocStart(), ToType))
4732     return Result;
4733 
4734   // Per DR1467:
4735   //   If the parameter type is a class X and the initializer list has a single
4736   //   element of type cv U, where U is X or a class derived from X, the
4737   //   implicit conversion sequence is the one required to convert the element
4738   //   to the parameter type.
4739   //
4740   //   Otherwise, if the parameter type is a character array [... ]
4741   //   and the initializer list has a single element that is an
4742   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4743   //   implicit conversion sequence is the identity conversion.
4744   if (From->getNumInits() == 1) {
4745     if (ToType->isRecordType()) {
4746       QualType InitType = From->getInit(0)->getType();
4747       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4748           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4749         return TryCopyInitialization(S, From->getInit(0), ToType,
4750                                      SuppressUserConversions,
4751                                      InOverloadResolution,
4752                                      AllowObjCWritebackConversion);
4753     }
4754     // FIXME: Check the other conditions here: array of character type,
4755     // initializer is a string literal.
4756     if (ToType->isArrayType()) {
4757       InitializedEntity Entity =
4758         InitializedEntity::InitializeParameter(S.Context, ToType,
4759                                                /*Consumed=*/false);
4760       if (S.CanPerformCopyInitialization(Entity, From)) {
4761         Result.setStandard();
4762         Result.Standard.setAsIdentityConversion();
4763         Result.Standard.setFromType(ToType);
4764         Result.Standard.setAllToTypes(ToType);
4765         return Result;
4766       }
4767     }
4768   }
4769 
4770   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4771   // C++11 [over.ics.list]p2:
4772   //   If the parameter type is std::initializer_list<X> or "array of X" and
4773   //   all the elements can be implicitly converted to X, the implicit
4774   //   conversion sequence is the worst conversion necessary to convert an
4775   //   element of the list to X.
4776   //
4777   // C++14 [over.ics.list]p3:
4778   //   Otherwise, if the parameter type is "array of N X", if the initializer
4779   //   list has exactly N elements or if it has fewer than N elements and X is
4780   //   default-constructible, and if all the elements of the initializer list
4781   //   can be implicitly converted to X, the implicit conversion sequence is
4782   //   the worst conversion necessary to convert an element of the list to X.
4783   //
4784   // FIXME: We're missing a lot of these checks.
4785   bool toStdInitializerList = false;
4786   QualType X;
4787   if (ToType->isArrayType())
4788     X = S.Context.getAsArrayType(ToType)->getElementType();
4789   else
4790     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4791   if (!X.isNull()) {
4792     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4793       Expr *Init = From->getInit(i);
4794       ImplicitConversionSequence ICS =
4795           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4796                                 InOverloadResolution,
4797                                 AllowObjCWritebackConversion);
4798       // If a single element isn't convertible, fail.
4799       if (ICS.isBad()) {
4800         Result = ICS;
4801         break;
4802       }
4803       // Otherwise, look for the worst conversion.
4804       if (Result.isBad() ||
4805           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4806                                              Result) ==
4807               ImplicitConversionSequence::Worse)
4808         Result = ICS;
4809     }
4810 
4811     // For an empty list, we won't have computed any conversion sequence.
4812     // Introduce the identity conversion sequence.
4813     if (From->getNumInits() == 0) {
4814       Result.setStandard();
4815       Result.Standard.setAsIdentityConversion();
4816       Result.Standard.setFromType(ToType);
4817       Result.Standard.setAllToTypes(ToType);
4818     }
4819 
4820     Result.setStdInitializerListElement(toStdInitializerList);
4821     return Result;
4822   }
4823 
4824   // C++14 [over.ics.list]p4:
4825   // C++11 [over.ics.list]p3:
4826   //   Otherwise, if the parameter is a non-aggregate class X and overload
4827   //   resolution chooses a single best constructor [...] the implicit
4828   //   conversion sequence is a user-defined conversion sequence. If multiple
4829   //   constructors are viable but none is better than the others, the
4830   //   implicit conversion sequence is a user-defined conversion sequence.
4831   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4832     // This function can deal with initializer lists.
4833     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4834                                     /*AllowExplicit=*/false,
4835                                     InOverloadResolution, /*CStyle=*/false,
4836                                     AllowObjCWritebackConversion,
4837                                     /*AllowObjCConversionOnExplicit=*/false);
4838   }
4839 
4840   // C++14 [over.ics.list]p5:
4841   // C++11 [over.ics.list]p4:
4842   //   Otherwise, if the parameter has an aggregate type which can be
4843   //   initialized from the initializer list [...] the implicit conversion
4844   //   sequence is a user-defined conversion sequence.
4845   if (ToType->isAggregateType()) {
4846     // Type is an aggregate, argument is an init list. At this point it comes
4847     // down to checking whether the initialization works.
4848     // FIXME: Find out whether this parameter is consumed or not.
4849     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4850     // need to call into the initialization code here; overload resolution
4851     // should not be doing that.
4852     InitializedEntity Entity =
4853         InitializedEntity::InitializeParameter(S.Context, ToType,
4854                                                /*Consumed=*/false);
4855     if (S.CanPerformCopyInitialization(Entity, From)) {
4856       Result.setUserDefined();
4857       Result.UserDefined.Before.setAsIdentityConversion();
4858       // Initializer lists don't have a type.
4859       Result.UserDefined.Before.setFromType(QualType());
4860       Result.UserDefined.Before.setAllToTypes(QualType());
4861 
4862       Result.UserDefined.After.setAsIdentityConversion();
4863       Result.UserDefined.After.setFromType(ToType);
4864       Result.UserDefined.After.setAllToTypes(ToType);
4865       Result.UserDefined.ConversionFunction = nullptr;
4866     }
4867     return Result;
4868   }
4869 
4870   // C++14 [over.ics.list]p6:
4871   // C++11 [over.ics.list]p5:
4872   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4873   if (ToType->isReferenceType()) {
4874     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4875     // mention initializer lists in any way. So we go by what list-
4876     // initialization would do and try to extrapolate from that.
4877 
4878     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4879 
4880     // If the initializer list has a single element that is reference-related
4881     // to the parameter type, we initialize the reference from that.
4882     if (From->getNumInits() == 1) {
4883       Expr *Init = From->getInit(0);
4884 
4885       QualType T2 = Init->getType();
4886 
4887       // If the initializer is the address of an overloaded function, try
4888       // to resolve the overloaded function. If all goes well, T2 is the
4889       // type of the resulting function.
4890       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4891         DeclAccessPair Found;
4892         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4893                                    Init, ToType, false, Found))
4894           T2 = Fn->getType();
4895       }
4896 
4897       // Compute some basic properties of the types and the initializer.
4898       bool dummy1 = false;
4899       bool dummy2 = false;
4900       bool dummy3 = false;
4901       Sema::ReferenceCompareResult RefRelationship
4902         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4903                                          dummy2, dummy3);
4904 
4905       if (RefRelationship >= Sema::Ref_Related) {
4906         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4907                                 SuppressUserConversions,
4908                                 /*AllowExplicit=*/false);
4909       }
4910     }
4911 
4912     // Otherwise, we bind the reference to a temporary created from the
4913     // initializer list.
4914     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4915                                InOverloadResolution,
4916                                AllowObjCWritebackConversion);
4917     if (Result.isFailure())
4918       return Result;
4919     assert(!Result.isEllipsis() &&
4920            "Sub-initialization cannot result in ellipsis conversion.");
4921 
4922     // Can we even bind to a temporary?
4923     if (ToType->isRValueReferenceType() ||
4924         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4925       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4926                                             Result.UserDefined.After;
4927       SCS.ReferenceBinding = true;
4928       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4929       SCS.BindsToRvalue = true;
4930       SCS.BindsToFunctionLvalue = false;
4931       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4932       SCS.ObjCLifetimeConversionBinding = false;
4933     } else
4934       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4935                     From, ToType);
4936     return Result;
4937   }
4938 
4939   // C++14 [over.ics.list]p7:
4940   // C++11 [over.ics.list]p6:
4941   //   Otherwise, if the parameter type is not a class:
4942   if (!ToType->isRecordType()) {
4943     //    - if the initializer list has one element that is not itself an
4944     //      initializer list, the implicit conversion sequence is the one
4945     //      required to convert the element to the parameter type.
4946     unsigned NumInits = From->getNumInits();
4947     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4948       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4949                                      SuppressUserConversions,
4950                                      InOverloadResolution,
4951                                      AllowObjCWritebackConversion);
4952     //    - if the initializer list has no elements, the implicit conversion
4953     //      sequence is the identity conversion.
4954     else if (NumInits == 0) {
4955       Result.setStandard();
4956       Result.Standard.setAsIdentityConversion();
4957       Result.Standard.setFromType(ToType);
4958       Result.Standard.setAllToTypes(ToType);
4959     }
4960     return Result;
4961   }
4962 
4963   // C++14 [over.ics.list]p8:
4964   // C++11 [over.ics.list]p7:
4965   //   In all cases other than those enumerated above, no conversion is possible
4966   return Result;
4967 }
4968 
4969 /// TryCopyInitialization - Try to copy-initialize a value of type
4970 /// ToType from the expression From. Return the implicit conversion
4971 /// sequence required to pass this argument, which may be a bad
4972 /// conversion sequence (meaning that the argument cannot be passed to
4973 /// a parameter of this type). If @p SuppressUserConversions, then we
4974 /// do not permit any user-defined conversion sequences.
4975 static ImplicitConversionSequence
4976 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4977                       bool SuppressUserConversions,
4978                       bool InOverloadResolution,
4979                       bool AllowObjCWritebackConversion,
4980                       bool AllowExplicit) {
4981   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4982     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4983                              InOverloadResolution,AllowObjCWritebackConversion);
4984 
4985   if (ToType->isReferenceType())
4986     return TryReferenceInit(S, From, ToType,
4987                             /*FIXME:*/From->getLocStart(),
4988                             SuppressUserConversions,
4989                             AllowExplicit);
4990 
4991   return TryImplicitConversion(S, From, ToType,
4992                                SuppressUserConversions,
4993                                /*AllowExplicit=*/false,
4994                                InOverloadResolution,
4995                                /*CStyle=*/false,
4996                                AllowObjCWritebackConversion,
4997                                /*AllowObjCConversionOnExplicit=*/false);
4998 }
4999 
5000 static bool TryCopyInitialization(const CanQualType FromQTy,
5001                                   const CanQualType ToQTy,
5002                                   Sema &S,
5003                                   SourceLocation Loc,
5004                                   ExprValueKind FromVK) {
5005   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5006   ImplicitConversionSequence ICS =
5007     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5008 
5009   return !ICS.isBad();
5010 }
5011 
5012 /// TryObjectArgumentInitialization - Try to initialize the object
5013 /// parameter of the given member function (@c Method) from the
5014 /// expression @p From.
5015 static ImplicitConversionSequence
5016 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5017                                 Expr::Classification FromClassification,
5018                                 CXXMethodDecl *Method,
5019                                 CXXRecordDecl *ActingContext) {
5020   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5021   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5022   //                 const volatile object.
5023   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5024     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5025   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5026 
5027   // Set up the conversion sequence as a "bad" conversion, to allow us
5028   // to exit early.
5029   ImplicitConversionSequence ICS;
5030 
5031   // We need to have an object of class type.
5032   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5033     FromType = PT->getPointeeType();
5034 
5035     // When we had a pointer, it's implicitly dereferenced, so we
5036     // better have an lvalue.
5037     assert(FromClassification.isLValue());
5038   }
5039 
5040   assert(FromType->isRecordType());
5041 
5042   // C++0x [over.match.funcs]p4:
5043   //   For non-static member functions, the type of the implicit object
5044   //   parameter is
5045   //
5046   //     - "lvalue reference to cv X" for functions declared without a
5047   //        ref-qualifier or with the & ref-qualifier
5048   //     - "rvalue reference to cv X" for functions declared with the &&
5049   //        ref-qualifier
5050   //
5051   // where X is the class of which the function is a member and cv is the
5052   // cv-qualification on the member function declaration.
5053   //
5054   // However, when finding an implicit conversion sequence for the argument, we
5055   // are not allowed to perform user-defined conversions
5056   // (C++ [over.match.funcs]p5). We perform a simplified version of
5057   // reference binding here, that allows class rvalues to bind to
5058   // non-constant references.
5059 
5060   // First check the qualifiers.
5061   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5062   if (ImplicitParamType.getCVRQualifiers()
5063                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5064       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5065     ICS.setBad(BadConversionSequence::bad_qualifiers,
5066                FromType, ImplicitParamType);
5067     return ICS;
5068   }
5069 
5070   // Check that we have either the same type or a derived type. It
5071   // affects the conversion rank.
5072   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5073   ImplicitConversionKind SecondKind;
5074   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5075     SecondKind = ICK_Identity;
5076   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5077     SecondKind = ICK_Derived_To_Base;
5078   else {
5079     ICS.setBad(BadConversionSequence::unrelated_class,
5080                FromType, ImplicitParamType);
5081     return ICS;
5082   }
5083 
5084   // Check the ref-qualifier.
5085   switch (Method->getRefQualifier()) {
5086   case RQ_None:
5087     // Do nothing; we don't care about lvalueness or rvalueness.
5088     break;
5089 
5090   case RQ_LValue:
5091     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5092       // non-const lvalue reference cannot bind to an rvalue
5093       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5094                  ImplicitParamType);
5095       return ICS;
5096     }
5097     break;
5098 
5099   case RQ_RValue:
5100     if (!FromClassification.isRValue()) {
5101       // rvalue reference cannot bind to an lvalue
5102       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5103                  ImplicitParamType);
5104       return ICS;
5105     }
5106     break;
5107   }
5108 
5109   // Success. Mark this as a reference binding.
5110   ICS.setStandard();
5111   ICS.Standard.setAsIdentityConversion();
5112   ICS.Standard.Second = SecondKind;
5113   ICS.Standard.setFromType(FromType);
5114   ICS.Standard.setAllToTypes(ImplicitParamType);
5115   ICS.Standard.ReferenceBinding = true;
5116   ICS.Standard.DirectBinding = true;
5117   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5118   ICS.Standard.BindsToFunctionLvalue = false;
5119   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5120   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5121     = (Method->getRefQualifier() == RQ_None);
5122   return ICS;
5123 }
5124 
5125 /// PerformObjectArgumentInitialization - Perform initialization of
5126 /// the implicit object parameter for the given Method with the given
5127 /// expression.
5128 ExprResult
5129 Sema::PerformObjectArgumentInitialization(Expr *From,
5130                                           NestedNameSpecifier *Qualifier,
5131                                           NamedDecl *FoundDecl,
5132                                           CXXMethodDecl *Method) {
5133   QualType FromRecordType, DestType;
5134   QualType ImplicitParamRecordType  =
5135     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5136 
5137   Expr::Classification FromClassification;
5138   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5139     FromRecordType = PT->getPointeeType();
5140     DestType = Method->getThisType(Context);
5141     FromClassification = Expr::Classification::makeSimpleLValue();
5142   } else {
5143     FromRecordType = From->getType();
5144     DestType = ImplicitParamRecordType;
5145     FromClassification = From->Classify(Context);
5146   }
5147 
5148   // Note that we always use the true parent context when performing
5149   // the actual argument initialization.
5150   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5151       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5152       Method->getParent());
5153   if (ICS.isBad()) {
5154     switch (ICS.Bad.Kind) {
5155     case BadConversionSequence::bad_qualifiers: {
5156       Qualifiers FromQs = FromRecordType.getQualifiers();
5157       Qualifiers ToQs = DestType.getQualifiers();
5158       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5159       if (CVR) {
5160         Diag(From->getLocStart(),
5161              diag::err_member_function_call_bad_cvr)
5162           << Method->getDeclName() << FromRecordType << (CVR - 1)
5163           << From->getSourceRange();
5164         Diag(Method->getLocation(), diag::note_previous_decl)
5165           << Method->getDeclName();
5166         return ExprError();
5167       }
5168       break;
5169     }
5170 
5171     case BadConversionSequence::lvalue_ref_to_rvalue:
5172     case BadConversionSequence::rvalue_ref_to_lvalue: {
5173       bool IsRValueQualified =
5174         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5175       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5176         << Method->getDeclName() << FromClassification.isRValue()
5177         << IsRValueQualified;
5178       Diag(Method->getLocation(), diag::note_previous_decl)
5179         << Method->getDeclName();
5180       return ExprError();
5181     }
5182 
5183     case BadConversionSequence::no_conversion:
5184     case BadConversionSequence::unrelated_class:
5185       break;
5186     }
5187 
5188     return Diag(From->getLocStart(),
5189                 diag::err_member_function_call_bad_type)
5190        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5191   }
5192 
5193   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5194     ExprResult FromRes =
5195       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5196     if (FromRes.isInvalid())
5197       return ExprError();
5198     From = FromRes.get();
5199   }
5200 
5201   if (!Context.hasSameType(From->getType(), DestType))
5202     From = ImpCastExprToType(From, DestType, CK_NoOp,
5203                              From->getValueKind()).get();
5204   return From;
5205 }
5206 
5207 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5208 /// expression From to bool (C++0x [conv]p3).
5209 static ImplicitConversionSequence
5210 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5211   return TryImplicitConversion(S, From, S.Context.BoolTy,
5212                                /*SuppressUserConversions=*/false,
5213                                /*AllowExplicit=*/true,
5214                                /*InOverloadResolution=*/false,
5215                                /*CStyle=*/false,
5216                                /*AllowObjCWritebackConversion=*/false,
5217                                /*AllowObjCConversionOnExplicit=*/false);
5218 }
5219 
5220 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5221 /// of the expression From to bool (C++0x [conv]p3).
5222 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5223   if (checkPlaceholderForOverload(*this, From))
5224     return ExprError();
5225 
5226   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5227   if (!ICS.isBad())
5228     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5229 
5230   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5231     return Diag(From->getLocStart(),
5232                 diag::err_typecheck_bool_condition)
5233                   << From->getType() << From->getSourceRange();
5234   return ExprError();
5235 }
5236 
5237 /// Check that the specified conversion is permitted in a converted constant
5238 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5239 /// is acceptable.
5240 static bool CheckConvertedConstantConversions(Sema &S,
5241                                               StandardConversionSequence &SCS) {
5242   // Since we know that the target type is an integral or unscoped enumeration
5243   // type, most conversion kinds are impossible. All possible First and Third
5244   // conversions are fine.
5245   switch (SCS.Second) {
5246   case ICK_Identity:
5247   case ICK_Function_Conversion:
5248   case ICK_Integral_Promotion:
5249   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5250   case ICK_Zero_Queue_Conversion:
5251     return true;
5252 
5253   case ICK_Boolean_Conversion:
5254     // Conversion from an integral or unscoped enumeration type to bool is
5255     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5256     // conversion, so we allow it in a converted constant expression.
5257     //
5258     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5259     // a lot of popular code. We should at least add a warning for this
5260     // (non-conforming) extension.
5261     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5262            SCS.getToType(2)->isBooleanType();
5263 
5264   case ICK_Pointer_Conversion:
5265   case ICK_Pointer_Member:
5266     // C++1z: null pointer conversions and null member pointer conversions are
5267     // only permitted if the source type is std::nullptr_t.
5268     return SCS.getFromType()->isNullPtrType();
5269 
5270   case ICK_Floating_Promotion:
5271   case ICK_Complex_Promotion:
5272   case ICK_Floating_Conversion:
5273   case ICK_Complex_Conversion:
5274   case ICK_Floating_Integral:
5275   case ICK_Compatible_Conversion:
5276   case ICK_Derived_To_Base:
5277   case ICK_Vector_Conversion:
5278   case ICK_Vector_Splat:
5279   case ICK_Complex_Real:
5280   case ICK_Block_Pointer_Conversion:
5281   case ICK_TransparentUnionConversion:
5282   case ICK_Writeback_Conversion:
5283   case ICK_Zero_Event_Conversion:
5284   case ICK_C_Only_Conversion:
5285   case ICK_Incompatible_Pointer_Conversion:
5286     return false;
5287 
5288   case ICK_Lvalue_To_Rvalue:
5289   case ICK_Array_To_Pointer:
5290   case ICK_Function_To_Pointer:
5291     llvm_unreachable("found a first conversion kind in Second");
5292 
5293   case ICK_Qualification:
5294     llvm_unreachable("found a third conversion kind in Second");
5295 
5296   case ICK_Num_Conversion_Kinds:
5297     break;
5298   }
5299 
5300   llvm_unreachable("unknown conversion kind");
5301 }
5302 
5303 /// CheckConvertedConstantExpression - Check that the expression From is a
5304 /// converted constant expression of type T, perform the conversion and produce
5305 /// the converted expression, per C++11 [expr.const]p3.
5306 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5307                                                    QualType T, APValue &Value,
5308                                                    Sema::CCEKind CCE,
5309                                                    bool RequireInt) {
5310   assert(S.getLangOpts().CPlusPlus11 &&
5311          "converted constant expression outside C++11");
5312 
5313   if (checkPlaceholderForOverload(S, From))
5314     return ExprError();
5315 
5316   // C++1z [expr.const]p3:
5317   //  A converted constant expression of type T is an expression,
5318   //  implicitly converted to type T, where the converted
5319   //  expression is a constant expression and the implicit conversion
5320   //  sequence contains only [... list of conversions ...].
5321   // C++1z [stmt.if]p2:
5322   //  If the if statement is of the form if constexpr, the value of the
5323   //  condition shall be a contextually converted constant expression of type
5324   //  bool.
5325   ImplicitConversionSequence ICS =
5326       CCE == Sema::CCEK_ConstexprIf
5327           ? TryContextuallyConvertToBool(S, From)
5328           : TryCopyInitialization(S, From, T,
5329                                   /*SuppressUserConversions=*/false,
5330                                   /*InOverloadResolution=*/false,
5331                                   /*AllowObjcWritebackConversion=*/false,
5332                                   /*AllowExplicit=*/false);
5333   StandardConversionSequence *SCS = nullptr;
5334   switch (ICS.getKind()) {
5335   case ImplicitConversionSequence::StandardConversion:
5336     SCS = &ICS.Standard;
5337     break;
5338   case ImplicitConversionSequence::UserDefinedConversion:
5339     // We are converting to a non-class type, so the Before sequence
5340     // must be trivial.
5341     SCS = &ICS.UserDefined.After;
5342     break;
5343   case ImplicitConversionSequence::AmbiguousConversion:
5344   case ImplicitConversionSequence::BadConversion:
5345     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5346       return S.Diag(From->getLocStart(),
5347                     diag::err_typecheck_converted_constant_expression)
5348                 << From->getType() << From->getSourceRange() << T;
5349     return ExprError();
5350 
5351   case ImplicitConversionSequence::EllipsisConversion:
5352     llvm_unreachable("ellipsis conversion in converted constant expression");
5353   }
5354 
5355   // Check that we would only use permitted conversions.
5356   if (!CheckConvertedConstantConversions(S, *SCS)) {
5357     return S.Diag(From->getLocStart(),
5358                   diag::err_typecheck_converted_constant_expression_disallowed)
5359              << From->getType() << From->getSourceRange() << T;
5360   }
5361   // [...] and where the reference binding (if any) binds directly.
5362   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5363     return S.Diag(From->getLocStart(),
5364                   diag::err_typecheck_converted_constant_expression_indirect)
5365              << From->getType() << From->getSourceRange() << T;
5366   }
5367 
5368   ExprResult Result =
5369       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5370   if (Result.isInvalid())
5371     return Result;
5372 
5373   // Check for a narrowing implicit conversion.
5374   APValue PreNarrowingValue;
5375   QualType PreNarrowingType;
5376   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5377                                 PreNarrowingType)) {
5378   case NK_Dependent_Narrowing:
5379     // Implicit conversion to a narrower type, but the expression is
5380     // value-dependent so we can't tell whether it's actually narrowing.
5381   case NK_Variable_Narrowing:
5382     // Implicit conversion to a narrower type, and the value is not a constant
5383     // expression. We'll diagnose this in a moment.
5384   case NK_Not_Narrowing:
5385     break;
5386 
5387   case NK_Constant_Narrowing:
5388     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5389       << CCE << /*Constant*/1
5390       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5391     break;
5392 
5393   case NK_Type_Narrowing:
5394     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5395       << CCE << /*Constant*/0 << From->getType() << T;
5396     break;
5397   }
5398 
5399   if (Result.get()->isValueDependent()) {
5400     Value = APValue();
5401     return Result;
5402   }
5403 
5404   // Check the expression is a constant expression.
5405   SmallVector<PartialDiagnosticAt, 8> Notes;
5406   Expr::EvalResult Eval;
5407   Eval.Diag = &Notes;
5408 
5409   if ((T->isReferenceType()
5410            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5411            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5412       (RequireInt && !Eval.Val.isInt())) {
5413     // The expression can't be folded, so we can't keep it at this position in
5414     // the AST.
5415     Result = ExprError();
5416   } else {
5417     Value = Eval.Val;
5418 
5419     if (Notes.empty()) {
5420       // It's a constant expression.
5421       return Result;
5422     }
5423   }
5424 
5425   // It's not a constant expression. Produce an appropriate diagnostic.
5426   if (Notes.size() == 1 &&
5427       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5428     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5429   else {
5430     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5431       << CCE << From->getSourceRange();
5432     for (unsigned I = 0; I < Notes.size(); ++I)
5433       S.Diag(Notes[I].first, Notes[I].second);
5434   }
5435   return ExprError();
5436 }
5437 
5438 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5439                                                   APValue &Value, CCEKind CCE) {
5440   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5441 }
5442 
5443 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5444                                                   llvm::APSInt &Value,
5445                                                   CCEKind CCE) {
5446   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5447 
5448   APValue V;
5449   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5450   if (!R.isInvalid() && !R.get()->isValueDependent())
5451     Value = V.getInt();
5452   return R;
5453 }
5454 
5455 
5456 /// dropPointerConversions - If the given standard conversion sequence
5457 /// involves any pointer conversions, remove them.  This may change
5458 /// the result type of the conversion sequence.
5459 static void dropPointerConversion(StandardConversionSequence &SCS) {
5460   if (SCS.Second == ICK_Pointer_Conversion) {
5461     SCS.Second = ICK_Identity;
5462     SCS.Third = ICK_Identity;
5463     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5464   }
5465 }
5466 
5467 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5468 /// convert the expression From to an Objective-C pointer type.
5469 static ImplicitConversionSequence
5470 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5471   // Do an implicit conversion to 'id'.
5472   QualType Ty = S.Context.getObjCIdType();
5473   ImplicitConversionSequence ICS
5474     = TryImplicitConversion(S, From, Ty,
5475                             // FIXME: Are these flags correct?
5476                             /*SuppressUserConversions=*/false,
5477                             /*AllowExplicit=*/true,
5478                             /*InOverloadResolution=*/false,
5479                             /*CStyle=*/false,
5480                             /*AllowObjCWritebackConversion=*/false,
5481                             /*AllowObjCConversionOnExplicit=*/true);
5482 
5483   // Strip off any final conversions to 'id'.
5484   switch (ICS.getKind()) {
5485   case ImplicitConversionSequence::BadConversion:
5486   case ImplicitConversionSequence::AmbiguousConversion:
5487   case ImplicitConversionSequence::EllipsisConversion:
5488     break;
5489 
5490   case ImplicitConversionSequence::UserDefinedConversion:
5491     dropPointerConversion(ICS.UserDefined.After);
5492     break;
5493 
5494   case ImplicitConversionSequence::StandardConversion:
5495     dropPointerConversion(ICS.Standard);
5496     break;
5497   }
5498 
5499   return ICS;
5500 }
5501 
5502 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5503 /// conversion of the expression From to an Objective-C pointer type.
5504 /// Returns a valid but null ExprResult if no conversion sequence exists.
5505 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5506   if (checkPlaceholderForOverload(*this, From))
5507     return ExprError();
5508 
5509   QualType Ty = Context.getObjCIdType();
5510   ImplicitConversionSequence ICS =
5511     TryContextuallyConvertToObjCPointer(*this, From);
5512   if (!ICS.isBad())
5513     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5514   return ExprResult();
5515 }
5516 
5517 /// Determine whether the provided type is an integral type, or an enumeration
5518 /// type of a permitted flavor.
5519 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5520   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5521                                  : T->isIntegralOrUnscopedEnumerationType();
5522 }
5523 
5524 static ExprResult
5525 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5526                             Sema::ContextualImplicitConverter &Converter,
5527                             QualType T, UnresolvedSetImpl &ViableConversions) {
5528 
5529   if (Converter.Suppress)
5530     return ExprError();
5531 
5532   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5533   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5534     CXXConversionDecl *Conv =
5535         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5536     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5537     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5538   }
5539   return From;
5540 }
5541 
5542 static bool
5543 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5544                            Sema::ContextualImplicitConverter &Converter,
5545                            QualType T, bool HadMultipleCandidates,
5546                            UnresolvedSetImpl &ExplicitConversions) {
5547   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5548     DeclAccessPair Found = ExplicitConversions[0];
5549     CXXConversionDecl *Conversion =
5550         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5551 
5552     // The user probably meant to invoke the given explicit
5553     // conversion; use it.
5554     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5555     std::string TypeStr;
5556     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5557 
5558     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5559         << FixItHint::CreateInsertion(From->getLocStart(),
5560                                       "static_cast<" + TypeStr + ">(")
5561         << FixItHint::CreateInsertion(
5562                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5563     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5564 
5565     // If we aren't in a SFINAE context, build a call to the
5566     // explicit conversion function.
5567     if (SemaRef.isSFINAEContext())
5568       return true;
5569 
5570     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5571     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5572                                                        HadMultipleCandidates);
5573     if (Result.isInvalid())
5574       return true;
5575     // Record usage of conversion in an implicit cast.
5576     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5577                                     CK_UserDefinedConversion, Result.get(),
5578                                     nullptr, Result.get()->getValueKind());
5579   }
5580   return false;
5581 }
5582 
5583 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5584                              Sema::ContextualImplicitConverter &Converter,
5585                              QualType T, bool HadMultipleCandidates,
5586                              DeclAccessPair &Found) {
5587   CXXConversionDecl *Conversion =
5588       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5589   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5590 
5591   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5592   if (!Converter.SuppressConversion) {
5593     if (SemaRef.isSFINAEContext())
5594       return true;
5595 
5596     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5597         << From->getSourceRange();
5598   }
5599 
5600   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5601                                                      HadMultipleCandidates);
5602   if (Result.isInvalid())
5603     return true;
5604   // Record usage of conversion in an implicit cast.
5605   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5606                                   CK_UserDefinedConversion, Result.get(),
5607                                   nullptr, Result.get()->getValueKind());
5608   return false;
5609 }
5610 
5611 static ExprResult finishContextualImplicitConversion(
5612     Sema &SemaRef, SourceLocation Loc, Expr *From,
5613     Sema::ContextualImplicitConverter &Converter) {
5614   if (!Converter.match(From->getType()) && !Converter.Suppress)
5615     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5616         << From->getSourceRange();
5617 
5618   return SemaRef.DefaultLvalueConversion(From);
5619 }
5620 
5621 static void
5622 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5623                                   UnresolvedSetImpl &ViableConversions,
5624                                   OverloadCandidateSet &CandidateSet) {
5625   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5626     DeclAccessPair FoundDecl = ViableConversions[I];
5627     NamedDecl *D = FoundDecl.getDecl();
5628     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5629     if (isa<UsingShadowDecl>(D))
5630       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5631 
5632     CXXConversionDecl *Conv;
5633     FunctionTemplateDecl *ConvTemplate;
5634     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5635       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5636     else
5637       Conv = cast<CXXConversionDecl>(D);
5638 
5639     if (ConvTemplate)
5640       SemaRef.AddTemplateConversionCandidate(
5641         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5642         /*AllowObjCConversionOnExplicit=*/false);
5643     else
5644       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5645                                      ToType, CandidateSet,
5646                                      /*AllowObjCConversionOnExplicit=*/false);
5647   }
5648 }
5649 
5650 /// \brief Attempt to convert the given expression to a type which is accepted
5651 /// by the given converter.
5652 ///
5653 /// This routine will attempt to convert an expression of class type to a
5654 /// type accepted by the specified converter. In C++11 and before, the class
5655 /// must have a single non-explicit conversion function converting to a matching
5656 /// type. In C++1y, there can be multiple such conversion functions, but only
5657 /// one target type.
5658 ///
5659 /// \param Loc The source location of the construct that requires the
5660 /// conversion.
5661 ///
5662 /// \param From The expression we're converting from.
5663 ///
5664 /// \param Converter Used to control and diagnose the conversion process.
5665 ///
5666 /// \returns The expression, converted to an integral or enumeration type if
5667 /// successful.
5668 ExprResult Sema::PerformContextualImplicitConversion(
5669     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5670   // We can't perform any more checking for type-dependent expressions.
5671   if (From->isTypeDependent())
5672     return From;
5673 
5674   // Process placeholders immediately.
5675   if (From->hasPlaceholderType()) {
5676     ExprResult result = CheckPlaceholderExpr(From);
5677     if (result.isInvalid())
5678       return result;
5679     From = result.get();
5680   }
5681 
5682   // If the expression already has a matching type, we're golden.
5683   QualType T = From->getType();
5684   if (Converter.match(T))
5685     return DefaultLvalueConversion(From);
5686 
5687   // FIXME: Check for missing '()' if T is a function type?
5688 
5689   // We can only perform contextual implicit conversions on objects of class
5690   // type.
5691   const RecordType *RecordTy = T->getAs<RecordType>();
5692   if (!RecordTy || !getLangOpts().CPlusPlus) {
5693     if (!Converter.Suppress)
5694       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5695     return From;
5696   }
5697 
5698   // We must have a complete class type.
5699   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5700     ContextualImplicitConverter &Converter;
5701     Expr *From;
5702 
5703     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5704         : Converter(Converter), From(From) {}
5705 
5706     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5707       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5708     }
5709   } IncompleteDiagnoser(Converter, From);
5710 
5711   if (Converter.Suppress ? !isCompleteType(Loc, T)
5712                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5713     return From;
5714 
5715   // Look for a conversion to an integral or enumeration type.
5716   UnresolvedSet<4>
5717       ViableConversions; // These are *potentially* viable in C++1y.
5718   UnresolvedSet<4> ExplicitConversions;
5719   const auto &Conversions =
5720       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5721 
5722   bool HadMultipleCandidates =
5723       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5724 
5725   // To check that there is only one target type, in C++1y:
5726   QualType ToType;
5727   bool HasUniqueTargetType = true;
5728 
5729   // Collect explicit or viable (potentially in C++1y) conversions.
5730   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5731     NamedDecl *D = (*I)->getUnderlyingDecl();
5732     CXXConversionDecl *Conversion;
5733     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5734     if (ConvTemplate) {
5735       if (getLangOpts().CPlusPlus14)
5736         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5737       else
5738         continue; // C++11 does not consider conversion operator templates(?).
5739     } else
5740       Conversion = cast<CXXConversionDecl>(D);
5741 
5742     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5743            "Conversion operator templates are considered potentially "
5744            "viable in C++1y");
5745 
5746     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5747     if (Converter.match(CurToType) || ConvTemplate) {
5748 
5749       if (Conversion->isExplicit()) {
5750         // FIXME: For C++1y, do we need this restriction?
5751         // cf. diagnoseNoViableConversion()
5752         if (!ConvTemplate)
5753           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5754       } else {
5755         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5756           if (ToType.isNull())
5757             ToType = CurToType.getUnqualifiedType();
5758           else if (HasUniqueTargetType &&
5759                    (CurToType.getUnqualifiedType() != ToType))
5760             HasUniqueTargetType = false;
5761         }
5762         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5763       }
5764     }
5765   }
5766 
5767   if (getLangOpts().CPlusPlus14) {
5768     // C++1y [conv]p6:
5769     // ... An expression e of class type E appearing in such a context
5770     // is said to be contextually implicitly converted to a specified
5771     // type T and is well-formed if and only if e can be implicitly
5772     // converted to a type T that is determined as follows: E is searched
5773     // for conversion functions whose return type is cv T or reference to
5774     // cv T such that T is allowed by the context. There shall be
5775     // exactly one such T.
5776 
5777     // If no unique T is found:
5778     if (ToType.isNull()) {
5779       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5780                                      HadMultipleCandidates,
5781                                      ExplicitConversions))
5782         return ExprError();
5783       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5784     }
5785 
5786     // If more than one unique Ts are found:
5787     if (!HasUniqueTargetType)
5788       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5789                                          ViableConversions);
5790 
5791     // If one unique T is found:
5792     // First, build a candidate set from the previously recorded
5793     // potentially viable conversions.
5794     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5795     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5796                                       CandidateSet);
5797 
5798     // Then, perform overload resolution over the candidate set.
5799     OverloadCandidateSet::iterator Best;
5800     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5801     case OR_Success: {
5802       // Apply this conversion.
5803       DeclAccessPair Found =
5804           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5805       if (recordConversion(*this, Loc, From, Converter, T,
5806                            HadMultipleCandidates, Found))
5807         return ExprError();
5808       break;
5809     }
5810     case OR_Ambiguous:
5811       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5812                                          ViableConversions);
5813     case OR_No_Viable_Function:
5814       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5815                                      HadMultipleCandidates,
5816                                      ExplicitConversions))
5817         return ExprError();
5818       LLVM_FALLTHROUGH;
5819     case OR_Deleted:
5820       // We'll complain below about a non-integral condition type.
5821       break;
5822     }
5823   } else {
5824     switch (ViableConversions.size()) {
5825     case 0: {
5826       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5827                                      HadMultipleCandidates,
5828                                      ExplicitConversions))
5829         return ExprError();
5830 
5831       // We'll complain below about a non-integral condition type.
5832       break;
5833     }
5834     case 1: {
5835       // Apply this conversion.
5836       DeclAccessPair Found = ViableConversions[0];
5837       if (recordConversion(*this, Loc, From, Converter, T,
5838                            HadMultipleCandidates, Found))
5839         return ExprError();
5840       break;
5841     }
5842     default:
5843       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5844                                          ViableConversions);
5845     }
5846   }
5847 
5848   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5849 }
5850 
5851 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5852 /// an acceptable non-member overloaded operator for a call whose
5853 /// arguments have types T1 (and, if non-empty, T2). This routine
5854 /// implements the check in C++ [over.match.oper]p3b2 concerning
5855 /// enumeration types.
5856 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5857                                                    FunctionDecl *Fn,
5858                                                    ArrayRef<Expr *> Args) {
5859   QualType T1 = Args[0]->getType();
5860   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5861 
5862   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5863     return true;
5864 
5865   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5866     return true;
5867 
5868   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5869   if (Proto->getNumParams() < 1)
5870     return false;
5871 
5872   if (T1->isEnumeralType()) {
5873     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5874     if (Context.hasSameUnqualifiedType(T1, ArgType))
5875       return true;
5876   }
5877 
5878   if (Proto->getNumParams() < 2)
5879     return false;
5880 
5881   if (!T2.isNull() && T2->isEnumeralType()) {
5882     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5883     if (Context.hasSameUnqualifiedType(T2, ArgType))
5884       return true;
5885   }
5886 
5887   return false;
5888 }
5889 
5890 /// AddOverloadCandidate - Adds the given function to the set of
5891 /// candidate functions, using the given function call arguments.  If
5892 /// @p SuppressUserConversions, then don't allow user-defined
5893 /// conversions via constructors or conversion operators.
5894 ///
5895 /// \param PartialOverloading true if we are performing "partial" overloading
5896 /// based on an incomplete set of function arguments. This feature is used by
5897 /// code completion.
5898 void
5899 Sema::AddOverloadCandidate(FunctionDecl *Function,
5900                            DeclAccessPair FoundDecl,
5901                            ArrayRef<Expr *> Args,
5902                            OverloadCandidateSet &CandidateSet,
5903                            bool SuppressUserConversions,
5904                            bool PartialOverloading,
5905                            bool AllowExplicit,
5906                            ConversionSequenceList EarlyConversions) {
5907   const FunctionProtoType *Proto
5908     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5909   assert(Proto && "Functions without a prototype cannot be overloaded");
5910   assert(!Function->getDescribedFunctionTemplate() &&
5911          "Use AddTemplateOverloadCandidate for function templates");
5912 
5913   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5914     if (!isa<CXXConstructorDecl>(Method)) {
5915       // If we get here, it's because we're calling a member function
5916       // that is named without a member access expression (e.g.,
5917       // "this->f") that was either written explicitly or created
5918       // implicitly. This can happen with a qualified call to a member
5919       // function, e.g., X::f(). We use an empty type for the implied
5920       // object argument (C++ [over.call.func]p3), and the acting context
5921       // is irrelevant.
5922       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5923                          Expr::Classification::makeSimpleLValue(), Args,
5924                          CandidateSet, SuppressUserConversions,
5925                          PartialOverloading, EarlyConversions);
5926       return;
5927     }
5928     // We treat a constructor like a non-member function, since its object
5929     // argument doesn't participate in overload resolution.
5930   }
5931 
5932   if (!CandidateSet.isNewCandidate(Function))
5933     return;
5934 
5935   // C++ [over.match.oper]p3:
5936   //   if no operand has a class type, only those non-member functions in the
5937   //   lookup set that have a first parameter of type T1 or "reference to
5938   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5939   //   is a right operand) a second parameter of type T2 or "reference to
5940   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5941   //   candidate functions.
5942   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5943       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5944     return;
5945 
5946   // C++11 [class.copy]p11: [DR1402]
5947   //   A defaulted move constructor that is defined as deleted is ignored by
5948   //   overload resolution.
5949   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5950   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5951       Constructor->isMoveConstructor())
5952     return;
5953 
5954   // Overload resolution is always an unevaluated context.
5955   EnterExpressionEvaluationContext Unevaluated(
5956       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5957 
5958   // Add this candidate
5959   OverloadCandidate &Candidate =
5960       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5961   Candidate.FoundDecl = FoundDecl;
5962   Candidate.Function = Function;
5963   Candidate.Viable = true;
5964   Candidate.IsSurrogate = false;
5965   Candidate.IgnoreObjectArgument = false;
5966   Candidate.ExplicitCallArguments = Args.size();
5967 
5968   if (Function->isMultiVersion() &&
5969       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5970     Candidate.Viable = false;
5971     Candidate.FailureKind = ovl_non_default_multiversion_function;
5972     return;
5973   }
5974 
5975   if (Constructor) {
5976     // C++ [class.copy]p3:
5977     //   A member function template is never instantiated to perform the copy
5978     //   of a class object to an object of its class type.
5979     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5980     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5981         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5982          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5983                        ClassType))) {
5984       Candidate.Viable = false;
5985       Candidate.FailureKind = ovl_fail_illegal_constructor;
5986       return;
5987     }
5988 
5989     // C++ [over.match.funcs]p8: (proposed DR resolution)
5990     //   A constructor inherited from class type C that has a first parameter
5991     //   of type "reference to P" (including such a constructor instantiated
5992     //   from a template) is excluded from the set of candidate functions when
5993     //   constructing an object of type cv D if the argument list has exactly
5994     //   one argument and D is reference-related to P and P is reference-related
5995     //   to C.
5996     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5997     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5998         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5999       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6000       QualType C = Context.getRecordType(Constructor->getParent());
6001       QualType D = Context.getRecordType(Shadow->getParent());
6002       SourceLocation Loc = Args.front()->getExprLoc();
6003       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6004           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6005         Candidate.Viable = false;
6006         Candidate.FailureKind = ovl_fail_inhctor_slice;
6007         return;
6008       }
6009     }
6010   }
6011 
6012   unsigned NumParams = Proto->getNumParams();
6013 
6014   // (C++ 13.3.2p2): A candidate function having fewer than m
6015   // parameters is viable only if it has an ellipsis in its parameter
6016   // list (8.3.5).
6017   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6018       !Proto->isVariadic()) {
6019     Candidate.Viable = false;
6020     Candidate.FailureKind = ovl_fail_too_many_arguments;
6021     return;
6022   }
6023 
6024   // (C++ 13.3.2p2): A candidate function having more than m parameters
6025   // is viable only if the (m+1)st parameter has a default argument
6026   // (8.3.6). For the purposes of overload resolution, the
6027   // parameter list is truncated on the right, so that there are
6028   // exactly m parameters.
6029   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6030   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6031     // Not enough arguments.
6032     Candidate.Viable = false;
6033     Candidate.FailureKind = ovl_fail_too_few_arguments;
6034     return;
6035   }
6036 
6037   // (CUDA B.1): Check for invalid calls between targets.
6038   if (getLangOpts().CUDA)
6039     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6040       // Skip the check for callers that are implicit members, because in this
6041       // case we may not yet know what the member's target is; the target is
6042       // inferred for the member automatically, based on the bases and fields of
6043       // the class.
6044       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6045         Candidate.Viable = false;
6046         Candidate.FailureKind = ovl_fail_bad_target;
6047         return;
6048       }
6049 
6050   // Determine the implicit conversion sequences for each of the
6051   // arguments.
6052   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6053     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6054       // We already formed a conversion sequence for this parameter during
6055       // template argument deduction.
6056     } else if (ArgIdx < NumParams) {
6057       // (C++ 13.3.2p3): for F to be a viable function, there shall
6058       // exist for each argument an implicit conversion sequence
6059       // (13.3.3.1) that converts that argument to the corresponding
6060       // parameter of F.
6061       QualType ParamType = Proto->getParamType(ArgIdx);
6062       Candidate.Conversions[ArgIdx]
6063         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6064                                 SuppressUserConversions,
6065                                 /*InOverloadResolution=*/true,
6066                                 /*AllowObjCWritebackConversion=*/
6067                                   getLangOpts().ObjCAutoRefCount,
6068                                 AllowExplicit);
6069       if (Candidate.Conversions[ArgIdx].isBad()) {
6070         Candidate.Viable = false;
6071         Candidate.FailureKind = ovl_fail_bad_conversion;
6072         return;
6073       }
6074     } else {
6075       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6076       // argument for which there is no corresponding parameter is
6077       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6078       Candidate.Conversions[ArgIdx].setEllipsis();
6079     }
6080   }
6081 
6082   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6083     Candidate.Viable = false;
6084     Candidate.FailureKind = ovl_fail_enable_if;
6085     Candidate.DeductionFailure.Data = FailedAttr;
6086     return;
6087   }
6088 
6089   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6090     Candidate.Viable = false;
6091     Candidate.FailureKind = ovl_fail_ext_disabled;
6092     return;
6093   }
6094 }
6095 
6096 ObjCMethodDecl *
6097 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6098                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6099   if (Methods.size() <= 1)
6100     return nullptr;
6101 
6102   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6103     bool Match = true;
6104     ObjCMethodDecl *Method = Methods[b];
6105     unsigned NumNamedArgs = Sel.getNumArgs();
6106     // Method might have more arguments than selector indicates. This is due
6107     // to addition of c-style arguments in method.
6108     if (Method->param_size() > NumNamedArgs)
6109       NumNamedArgs = Method->param_size();
6110     if (Args.size() < NumNamedArgs)
6111       continue;
6112 
6113     for (unsigned i = 0; i < NumNamedArgs; i++) {
6114       // We can't do any type-checking on a type-dependent argument.
6115       if (Args[i]->isTypeDependent()) {
6116         Match = false;
6117         break;
6118       }
6119 
6120       ParmVarDecl *param = Method->parameters()[i];
6121       Expr *argExpr = Args[i];
6122       assert(argExpr && "SelectBestMethod(): missing expression");
6123 
6124       // Strip the unbridged-cast placeholder expression off unless it's
6125       // a consumed argument.
6126       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6127           !param->hasAttr<CFConsumedAttr>())
6128         argExpr = stripARCUnbridgedCast(argExpr);
6129 
6130       // If the parameter is __unknown_anytype, move on to the next method.
6131       if (param->getType() == Context.UnknownAnyTy) {
6132         Match = false;
6133         break;
6134       }
6135 
6136       ImplicitConversionSequence ConversionState
6137         = TryCopyInitialization(*this, argExpr, param->getType(),
6138                                 /*SuppressUserConversions*/false,
6139                                 /*InOverloadResolution=*/true,
6140                                 /*AllowObjCWritebackConversion=*/
6141                                 getLangOpts().ObjCAutoRefCount,
6142                                 /*AllowExplicit*/false);
6143       // This function looks for a reasonably-exact match, so we consider
6144       // incompatible pointer conversions to be a failure here.
6145       if (ConversionState.isBad() ||
6146           (ConversionState.isStandard() &&
6147            ConversionState.Standard.Second ==
6148                ICK_Incompatible_Pointer_Conversion)) {
6149         Match = false;
6150         break;
6151       }
6152     }
6153     // Promote additional arguments to variadic methods.
6154     if (Match && Method->isVariadic()) {
6155       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6156         if (Args[i]->isTypeDependent()) {
6157           Match = false;
6158           break;
6159         }
6160         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6161                                                           nullptr);
6162         if (Arg.isInvalid()) {
6163           Match = false;
6164           break;
6165         }
6166       }
6167     } else {
6168       // Check for extra arguments to non-variadic methods.
6169       if (Args.size() != NumNamedArgs)
6170         Match = false;
6171       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6172         // Special case when selectors have no argument. In this case, select
6173         // one with the most general result type of 'id'.
6174         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6175           QualType ReturnT = Methods[b]->getReturnType();
6176           if (ReturnT->isObjCIdType())
6177             return Methods[b];
6178         }
6179       }
6180     }
6181 
6182     if (Match)
6183       return Method;
6184   }
6185   return nullptr;
6186 }
6187 
6188 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6189 // enable_if is order-sensitive. As a result, we need to reverse things
6190 // sometimes. Size of 4 elements is arbitrary.
6191 static SmallVector<EnableIfAttr *, 4>
6192 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6193   SmallVector<EnableIfAttr *, 4> Result;
6194   if (!Function->hasAttrs())
6195     return Result;
6196 
6197   const auto &FuncAttrs = Function->getAttrs();
6198   for (Attr *Attr : FuncAttrs)
6199     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6200       Result.push_back(EnableIf);
6201 
6202   std::reverse(Result.begin(), Result.end());
6203   return Result;
6204 }
6205 
6206 static bool
6207 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6208                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6209                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6210                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6211   if (ThisArg) {
6212     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6213     assert(!isa<CXXConstructorDecl>(Method) &&
6214            "Shouldn't have `this` for ctors!");
6215     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6216     ExprResult R = S.PerformObjectArgumentInitialization(
6217         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6218     if (R.isInvalid())
6219       return false;
6220     ConvertedThis = R.get();
6221   } else {
6222     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6223       (void)MD;
6224       assert((MissingImplicitThis || MD->isStatic() ||
6225               isa<CXXConstructorDecl>(MD)) &&
6226              "Expected `this` for non-ctor instance methods");
6227     }
6228     ConvertedThis = nullptr;
6229   }
6230 
6231   // Ignore any variadic arguments. Converting them is pointless, since the
6232   // user can't refer to them in the function condition.
6233   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6234 
6235   // Convert the arguments.
6236   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6237     ExprResult R;
6238     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6239                                         S.Context, Function->getParamDecl(I)),
6240                                     SourceLocation(), Args[I]);
6241 
6242     if (R.isInvalid())
6243       return false;
6244 
6245     ConvertedArgs.push_back(R.get());
6246   }
6247 
6248   if (Trap.hasErrorOccurred())
6249     return false;
6250 
6251   // Push default arguments if needed.
6252   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6253     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6254       ParmVarDecl *P = Function->getParamDecl(i);
6255       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6256                          ? P->getUninstantiatedDefaultArg()
6257                          : P->getDefaultArg();
6258       // This can only happen in code completion, i.e. when PartialOverloading
6259       // is true.
6260       if (!DefArg)
6261         return false;
6262       ExprResult R =
6263           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6264                                           S.Context, Function->getParamDecl(i)),
6265                                       SourceLocation(), DefArg);
6266       if (R.isInvalid())
6267         return false;
6268       ConvertedArgs.push_back(R.get());
6269     }
6270 
6271     if (Trap.hasErrorOccurred())
6272       return false;
6273   }
6274   return true;
6275 }
6276 
6277 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6278                                   bool MissingImplicitThis) {
6279   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6280       getOrderedEnableIfAttrs(Function);
6281   if (EnableIfAttrs.empty())
6282     return nullptr;
6283 
6284   SFINAETrap Trap(*this);
6285   SmallVector<Expr *, 16> ConvertedArgs;
6286   // FIXME: We should look into making enable_if late-parsed.
6287   Expr *DiscardedThis;
6288   if (!convertArgsForAvailabilityChecks(
6289           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6290           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6291     return EnableIfAttrs[0];
6292 
6293   for (auto *EIA : EnableIfAttrs) {
6294     APValue Result;
6295     // FIXME: This doesn't consider value-dependent cases, because doing so is
6296     // very difficult. Ideally, we should handle them more gracefully.
6297     if (!EIA->getCond()->EvaluateWithSubstitution(
6298             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6299       return EIA;
6300 
6301     if (!Result.isInt() || !Result.getInt().getBoolValue())
6302       return EIA;
6303   }
6304   return nullptr;
6305 }
6306 
6307 template <typename CheckFn>
6308 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6309                                         bool ArgDependent, SourceLocation Loc,
6310                                         CheckFn &&IsSuccessful) {
6311   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6312   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6313     if (ArgDependent == DIA->getArgDependent())
6314       Attrs.push_back(DIA);
6315   }
6316 
6317   // Common case: No diagnose_if attributes, so we can quit early.
6318   if (Attrs.empty())
6319     return false;
6320 
6321   auto WarningBegin = std::stable_partition(
6322       Attrs.begin(), Attrs.end(),
6323       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6324 
6325   // Note that diagnose_if attributes are late-parsed, so they appear in the
6326   // correct order (unlike enable_if attributes).
6327   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6328                                IsSuccessful);
6329   if (ErrAttr != WarningBegin) {
6330     const DiagnoseIfAttr *DIA = *ErrAttr;
6331     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6332     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6333         << DIA->getParent() << DIA->getCond()->getSourceRange();
6334     return true;
6335   }
6336 
6337   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6338     if (IsSuccessful(DIA)) {
6339       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6340       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6341           << DIA->getParent() << DIA->getCond()->getSourceRange();
6342     }
6343 
6344   return false;
6345 }
6346 
6347 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6348                                                const Expr *ThisArg,
6349                                                ArrayRef<const Expr *> Args,
6350                                                SourceLocation Loc) {
6351   return diagnoseDiagnoseIfAttrsWith(
6352       *this, Function, /*ArgDependent=*/true, Loc,
6353       [&](const DiagnoseIfAttr *DIA) {
6354         APValue Result;
6355         // It's sane to use the same Args for any redecl of this function, since
6356         // EvaluateWithSubstitution only cares about the position of each
6357         // argument in the arg list, not the ParmVarDecl* it maps to.
6358         if (!DIA->getCond()->EvaluateWithSubstitution(
6359                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6360           return false;
6361         return Result.isInt() && Result.getInt().getBoolValue();
6362       });
6363 }
6364 
6365 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6366                                                  SourceLocation Loc) {
6367   return diagnoseDiagnoseIfAttrsWith(
6368       *this, ND, /*ArgDependent=*/false, Loc,
6369       [&](const DiagnoseIfAttr *DIA) {
6370         bool Result;
6371         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6372                Result;
6373       });
6374 }
6375 
6376 /// \brief Add all of the function declarations in the given function set to
6377 /// the overload candidate set.
6378 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6379                                  ArrayRef<Expr *> Args,
6380                                  OverloadCandidateSet& CandidateSet,
6381                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6382                                  bool SuppressUserConversions,
6383                                  bool PartialOverloading,
6384                                  bool FirstArgumentIsBase) {
6385   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6386     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6387     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6388       ArrayRef<Expr *> FunctionArgs = Args;
6389       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6390         QualType ObjectType;
6391         Expr::Classification ObjectClassification;
6392         if (Args.size() > 0) {
6393           if (Expr *E = Args[0]) {
6394             // Use the explicit base to restrict the lookup:
6395             ObjectType = E->getType();
6396             ObjectClassification = E->Classify(Context);
6397           } // .. else there is an implit base.
6398           FunctionArgs = Args.slice(1);
6399         }
6400         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6401                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6402                            ObjectClassification, FunctionArgs, CandidateSet,
6403                            SuppressUserConversions, PartialOverloading);
6404       } else {
6405         // Slice the first argument (which is the base) when we access
6406         // static method as non-static
6407         if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6408                                              !isa<CXXConstructorDecl>(FD)))) {
6409           assert(cast<CXXMethodDecl>(FD)->isStatic());
6410           FunctionArgs = Args.slice(1);
6411         }
6412         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6413                              SuppressUserConversions, PartialOverloading);
6414       }
6415     } else {
6416       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6417       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6418           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6419         QualType ObjectType;
6420         Expr::Classification ObjectClassification;
6421         if (Expr *E = Args[0]) {
6422           // Use the explicit base to restrict the lookup:
6423           ObjectType = E->getType();
6424           ObjectClassification = E->Classify(Context);
6425         } // .. else there is an implit base.
6426         AddMethodTemplateCandidate(
6427             FunTmpl, F.getPair(),
6428             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6429             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6430             Args.slice(1), CandidateSet, SuppressUserConversions,
6431             PartialOverloading);
6432       } else {
6433         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6434                                      ExplicitTemplateArgs, Args,
6435                                      CandidateSet, SuppressUserConversions,
6436                                      PartialOverloading);
6437       }
6438     }
6439   }
6440 }
6441 
6442 /// AddMethodCandidate - Adds a named decl (which is some kind of
6443 /// method) as a method candidate to the given overload set.
6444 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6445                               QualType ObjectType,
6446                               Expr::Classification ObjectClassification,
6447                               ArrayRef<Expr *> Args,
6448                               OverloadCandidateSet& CandidateSet,
6449                               bool SuppressUserConversions) {
6450   NamedDecl *Decl = FoundDecl.getDecl();
6451   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6452 
6453   if (isa<UsingShadowDecl>(Decl))
6454     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6455 
6456   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6457     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6458            "Expected a member function template");
6459     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6460                                /*ExplicitArgs*/ nullptr, ObjectType,
6461                                ObjectClassification, Args, CandidateSet,
6462                                SuppressUserConversions);
6463   } else {
6464     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6465                        ObjectType, ObjectClassification, Args, CandidateSet,
6466                        SuppressUserConversions);
6467   }
6468 }
6469 
6470 /// AddMethodCandidate - Adds the given C++ member function to the set
6471 /// of candidate functions, using the given function call arguments
6472 /// and the object argument (@c Object). For example, in a call
6473 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6474 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6475 /// allow user-defined conversions via constructors or conversion
6476 /// operators.
6477 void
6478 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6479                          CXXRecordDecl *ActingContext, QualType ObjectType,
6480                          Expr::Classification ObjectClassification,
6481                          ArrayRef<Expr *> Args,
6482                          OverloadCandidateSet &CandidateSet,
6483                          bool SuppressUserConversions,
6484                          bool PartialOverloading,
6485                          ConversionSequenceList EarlyConversions) {
6486   const FunctionProtoType *Proto
6487     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6488   assert(Proto && "Methods without a prototype cannot be overloaded");
6489   assert(!isa<CXXConstructorDecl>(Method) &&
6490          "Use AddOverloadCandidate for constructors");
6491 
6492   if (!CandidateSet.isNewCandidate(Method))
6493     return;
6494 
6495   // C++11 [class.copy]p23: [DR1402]
6496   //   A defaulted move assignment operator that is defined as deleted is
6497   //   ignored by overload resolution.
6498   if (Method->isDefaulted() && Method->isDeleted() &&
6499       Method->isMoveAssignmentOperator())
6500     return;
6501 
6502   // Overload resolution is always an unevaluated context.
6503   EnterExpressionEvaluationContext Unevaluated(
6504       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6505 
6506   // Add this candidate
6507   OverloadCandidate &Candidate =
6508       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6509   Candidate.FoundDecl = FoundDecl;
6510   Candidate.Function = Method;
6511   Candidate.IsSurrogate = false;
6512   Candidate.IgnoreObjectArgument = false;
6513   Candidate.ExplicitCallArguments = Args.size();
6514 
6515   unsigned NumParams = Proto->getNumParams();
6516 
6517   // (C++ 13.3.2p2): A candidate function having fewer than m
6518   // parameters is viable only if it has an ellipsis in its parameter
6519   // list (8.3.5).
6520   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6521       !Proto->isVariadic()) {
6522     Candidate.Viable = false;
6523     Candidate.FailureKind = ovl_fail_too_many_arguments;
6524     return;
6525   }
6526 
6527   // (C++ 13.3.2p2): A candidate function having more than m parameters
6528   // is viable only if the (m+1)st parameter has a default argument
6529   // (8.3.6). For the purposes of overload resolution, the
6530   // parameter list is truncated on the right, so that there are
6531   // exactly m parameters.
6532   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6533   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6534     // Not enough arguments.
6535     Candidate.Viable = false;
6536     Candidate.FailureKind = ovl_fail_too_few_arguments;
6537     return;
6538   }
6539 
6540   Candidate.Viable = true;
6541 
6542   if (Method->isStatic() || ObjectType.isNull())
6543     // The implicit object argument is ignored.
6544     Candidate.IgnoreObjectArgument = true;
6545   else {
6546     // Determine the implicit conversion sequence for the object
6547     // parameter.
6548     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6549         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6550         Method, ActingContext);
6551     if (Candidate.Conversions[0].isBad()) {
6552       Candidate.Viable = false;
6553       Candidate.FailureKind = ovl_fail_bad_conversion;
6554       return;
6555     }
6556   }
6557 
6558   // (CUDA B.1): Check for invalid calls between targets.
6559   if (getLangOpts().CUDA)
6560     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6561       if (!IsAllowedCUDACall(Caller, Method)) {
6562         Candidate.Viable = false;
6563         Candidate.FailureKind = ovl_fail_bad_target;
6564         return;
6565       }
6566 
6567   // Determine the implicit conversion sequences for each of the
6568   // arguments.
6569   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6570     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6571       // We already formed a conversion sequence for this parameter during
6572       // template argument deduction.
6573     } else if (ArgIdx < NumParams) {
6574       // (C++ 13.3.2p3): for F to be a viable function, there shall
6575       // exist for each argument an implicit conversion sequence
6576       // (13.3.3.1) that converts that argument to the corresponding
6577       // parameter of F.
6578       QualType ParamType = Proto->getParamType(ArgIdx);
6579       Candidate.Conversions[ArgIdx + 1]
6580         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6581                                 SuppressUserConversions,
6582                                 /*InOverloadResolution=*/true,
6583                                 /*AllowObjCWritebackConversion=*/
6584                                   getLangOpts().ObjCAutoRefCount);
6585       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6586         Candidate.Viable = false;
6587         Candidate.FailureKind = ovl_fail_bad_conversion;
6588         return;
6589       }
6590     } else {
6591       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6592       // argument for which there is no corresponding parameter is
6593       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6594       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6595     }
6596   }
6597 
6598   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6599     Candidate.Viable = false;
6600     Candidate.FailureKind = ovl_fail_enable_if;
6601     Candidate.DeductionFailure.Data = FailedAttr;
6602     return;
6603   }
6604 
6605   if (Method->isMultiVersion() &&
6606       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6607     Candidate.Viable = false;
6608     Candidate.FailureKind = ovl_non_default_multiversion_function;
6609   }
6610 }
6611 
6612 /// \brief Add a C++ member function template as a candidate to the candidate
6613 /// set, using template argument deduction to produce an appropriate member
6614 /// function template specialization.
6615 void
6616 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6617                                  DeclAccessPair FoundDecl,
6618                                  CXXRecordDecl *ActingContext,
6619                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6620                                  QualType ObjectType,
6621                                  Expr::Classification ObjectClassification,
6622                                  ArrayRef<Expr *> Args,
6623                                  OverloadCandidateSet& CandidateSet,
6624                                  bool SuppressUserConversions,
6625                                  bool PartialOverloading) {
6626   if (!CandidateSet.isNewCandidate(MethodTmpl))
6627     return;
6628 
6629   // C++ [over.match.funcs]p7:
6630   //   In each case where a candidate is a function template, candidate
6631   //   function template specializations are generated using template argument
6632   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6633   //   candidate functions in the usual way.113) A given name can refer to one
6634   //   or more function templates and also to a set of overloaded non-template
6635   //   functions. In such a case, the candidate functions generated from each
6636   //   function template are combined with the set of non-template candidate
6637   //   functions.
6638   TemplateDeductionInfo Info(CandidateSet.getLocation());
6639   FunctionDecl *Specialization = nullptr;
6640   ConversionSequenceList Conversions;
6641   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6642           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6643           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6644             return CheckNonDependentConversions(
6645                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6646                 SuppressUserConversions, ActingContext, ObjectType,
6647                 ObjectClassification);
6648           })) {
6649     OverloadCandidate &Candidate =
6650         CandidateSet.addCandidate(Conversions.size(), Conversions);
6651     Candidate.FoundDecl = FoundDecl;
6652     Candidate.Function = MethodTmpl->getTemplatedDecl();
6653     Candidate.Viable = false;
6654     Candidate.IsSurrogate = false;
6655     Candidate.IgnoreObjectArgument =
6656         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6657         ObjectType.isNull();
6658     Candidate.ExplicitCallArguments = Args.size();
6659     if (Result == TDK_NonDependentConversionFailure)
6660       Candidate.FailureKind = ovl_fail_bad_conversion;
6661     else {
6662       Candidate.FailureKind = ovl_fail_bad_deduction;
6663       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6664                                                             Info);
6665     }
6666     return;
6667   }
6668 
6669   // Add the function template specialization produced by template argument
6670   // deduction as a candidate.
6671   assert(Specialization && "Missing member function template specialization?");
6672   assert(isa<CXXMethodDecl>(Specialization) &&
6673          "Specialization is not a member function?");
6674   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6675                      ActingContext, ObjectType, ObjectClassification, Args,
6676                      CandidateSet, SuppressUserConversions, PartialOverloading,
6677                      Conversions);
6678 }
6679 
6680 /// \brief Add a C++ function template specialization as a candidate
6681 /// in the candidate set, using template argument deduction to produce
6682 /// an appropriate function template specialization.
6683 void
6684 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6685                                    DeclAccessPair FoundDecl,
6686                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6687                                    ArrayRef<Expr *> Args,
6688                                    OverloadCandidateSet& CandidateSet,
6689                                    bool SuppressUserConversions,
6690                                    bool PartialOverloading) {
6691   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6692     return;
6693 
6694   // C++ [over.match.funcs]p7:
6695   //   In each case where a candidate is a function template, candidate
6696   //   function template specializations are generated using template argument
6697   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6698   //   candidate functions in the usual way.113) A given name can refer to one
6699   //   or more function templates and also to a set of overloaded non-template
6700   //   functions. In such a case, the candidate functions generated from each
6701   //   function template are combined with the set of non-template candidate
6702   //   functions.
6703   TemplateDeductionInfo Info(CandidateSet.getLocation());
6704   FunctionDecl *Specialization = nullptr;
6705   ConversionSequenceList Conversions;
6706   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6707           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6708           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6709             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6710                                                 Args, CandidateSet, Conversions,
6711                                                 SuppressUserConversions);
6712           })) {
6713     OverloadCandidate &Candidate =
6714         CandidateSet.addCandidate(Conversions.size(), Conversions);
6715     Candidate.FoundDecl = FoundDecl;
6716     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6717     Candidate.Viable = false;
6718     Candidate.IsSurrogate = false;
6719     // Ignore the object argument if there is one, since we don't have an object
6720     // type.
6721     Candidate.IgnoreObjectArgument =
6722         isa<CXXMethodDecl>(Candidate.Function) &&
6723         !isa<CXXConstructorDecl>(Candidate.Function);
6724     Candidate.ExplicitCallArguments = Args.size();
6725     if (Result == TDK_NonDependentConversionFailure)
6726       Candidate.FailureKind = ovl_fail_bad_conversion;
6727     else {
6728       Candidate.FailureKind = ovl_fail_bad_deduction;
6729       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6730                                                             Info);
6731     }
6732     return;
6733   }
6734 
6735   // Add the function template specialization produced by template argument
6736   // deduction as a candidate.
6737   assert(Specialization && "Missing function template specialization?");
6738   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6739                        SuppressUserConversions, PartialOverloading,
6740                        /*AllowExplicit*/false, Conversions);
6741 }
6742 
6743 /// Check that implicit conversion sequences can be formed for each argument
6744 /// whose corresponding parameter has a non-dependent type, per DR1391's
6745 /// [temp.deduct.call]p10.
6746 bool Sema::CheckNonDependentConversions(
6747     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6748     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6749     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6750     CXXRecordDecl *ActingContext, QualType ObjectType,
6751     Expr::Classification ObjectClassification) {
6752   // FIXME: The cases in which we allow explicit conversions for constructor
6753   // arguments never consider calling a constructor template. It's not clear
6754   // that is correct.
6755   const bool AllowExplicit = false;
6756 
6757   auto *FD = FunctionTemplate->getTemplatedDecl();
6758   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6759   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6760   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6761 
6762   Conversions =
6763       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6764 
6765   // Overload resolution is always an unevaluated context.
6766   EnterExpressionEvaluationContext Unevaluated(
6767       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6768 
6769   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6770   // require that, but this check should never result in a hard error, and
6771   // overload resolution is permitted to sidestep instantiations.
6772   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6773       !ObjectType.isNull()) {
6774     Conversions[0] = TryObjectArgumentInitialization(
6775         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6776         Method, ActingContext);
6777     if (Conversions[0].isBad())
6778       return true;
6779   }
6780 
6781   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6782        ++I) {
6783     QualType ParamType = ParamTypes[I];
6784     if (!ParamType->isDependentType()) {
6785       Conversions[ThisConversions + I]
6786         = TryCopyInitialization(*this, Args[I], ParamType,
6787                                 SuppressUserConversions,
6788                                 /*InOverloadResolution=*/true,
6789                                 /*AllowObjCWritebackConversion=*/
6790                                   getLangOpts().ObjCAutoRefCount,
6791                                 AllowExplicit);
6792       if (Conversions[ThisConversions + I].isBad())
6793         return true;
6794     }
6795   }
6796 
6797   return false;
6798 }
6799 
6800 /// Determine whether this is an allowable conversion from the result
6801 /// of an explicit conversion operator to the expected type, per C++
6802 /// [over.match.conv]p1 and [over.match.ref]p1.
6803 ///
6804 /// \param ConvType The return type of the conversion function.
6805 ///
6806 /// \param ToType The type we are converting to.
6807 ///
6808 /// \param AllowObjCPointerConversion Allow a conversion from one
6809 /// Objective-C pointer to another.
6810 ///
6811 /// \returns true if the conversion is allowable, false otherwise.
6812 static bool isAllowableExplicitConversion(Sema &S,
6813                                           QualType ConvType, QualType ToType,
6814                                           bool AllowObjCPointerConversion) {
6815   QualType ToNonRefType = ToType.getNonReferenceType();
6816 
6817   // Easy case: the types are the same.
6818   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6819     return true;
6820 
6821   // Allow qualification conversions.
6822   bool ObjCLifetimeConversion;
6823   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6824                                   ObjCLifetimeConversion))
6825     return true;
6826 
6827   // If we're not allowed to consider Objective-C pointer conversions,
6828   // we're done.
6829   if (!AllowObjCPointerConversion)
6830     return false;
6831 
6832   // Is this an Objective-C pointer conversion?
6833   bool IncompatibleObjC = false;
6834   QualType ConvertedType;
6835   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6836                                    IncompatibleObjC);
6837 }
6838 
6839 /// AddConversionCandidate - Add a C++ conversion function as a
6840 /// candidate in the candidate set (C++ [over.match.conv],
6841 /// C++ [over.match.copy]). From is the expression we're converting from,
6842 /// and ToType is the type that we're eventually trying to convert to
6843 /// (which may or may not be the same type as the type that the
6844 /// conversion function produces).
6845 void
6846 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6847                              DeclAccessPair FoundDecl,
6848                              CXXRecordDecl *ActingContext,
6849                              Expr *From, QualType ToType,
6850                              OverloadCandidateSet& CandidateSet,
6851                              bool AllowObjCConversionOnExplicit,
6852                              bool AllowResultConversion) {
6853   assert(!Conversion->getDescribedFunctionTemplate() &&
6854          "Conversion function templates use AddTemplateConversionCandidate");
6855   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6856   if (!CandidateSet.isNewCandidate(Conversion))
6857     return;
6858 
6859   // If the conversion function has an undeduced return type, trigger its
6860   // deduction now.
6861   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6862     if (DeduceReturnType(Conversion, From->getExprLoc()))
6863       return;
6864     ConvType = Conversion->getConversionType().getNonReferenceType();
6865   }
6866 
6867   // If we don't allow any conversion of the result type, ignore conversion
6868   // functions that don't convert to exactly (possibly cv-qualified) T.
6869   if (!AllowResultConversion &&
6870       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6871     return;
6872 
6873   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6874   // operator is only a candidate if its return type is the target type or
6875   // can be converted to the target type with a qualification conversion.
6876   if (Conversion->isExplicit() &&
6877       !isAllowableExplicitConversion(*this, ConvType, ToType,
6878                                      AllowObjCConversionOnExplicit))
6879     return;
6880 
6881   // Overload resolution is always an unevaluated context.
6882   EnterExpressionEvaluationContext Unevaluated(
6883       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6884 
6885   // Add this candidate
6886   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6887   Candidate.FoundDecl = FoundDecl;
6888   Candidate.Function = Conversion;
6889   Candidate.IsSurrogate = false;
6890   Candidate.IgnoreObjectArgument = false;
6891   Candidate.FinalConversion.setAsIdentityConversion();
6892   Candidate.FinalConversion.setFromType(ConvType);
6893   Candidate.FinalConversion.setAllToTypes(ToType);
6894   Candidate.Viable = true;
6895   Candidate.ExplicitCallArguments = 1;
6896 
6897   // C++ [over.match.funcs]p4:
6898   //   For conversion functions, the function is considered to be a member of
6899   //   the class of the implicit implied object argument for the purpose of
6900   //   defining the type of the implicit object parameter.
6901   //
6902   // Determine the implicit conversion sequence for the implicit
6903   // object parameter.
6904   QualType ImplicitParamType = From->getType();
6905   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6906     ImplicitParamType = FromPtrType->getPointeeType();
6907   CXXRecordDecl *ConversionContext
6908     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6909 
6910   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6911       *this, CandidateSet.getLocation(), From->getType(),
6912       From->Classify(Context), Conversion, ConversionContext);
6913 
6914   if (Candidate.Conversions[0].isBad()) {
6915     Candidate.Viable = false;
6916     Candidate.FailureKind = ovl_fail_bad_conversion;
6917     return;
6918   }
6919 
6920   // We won't go through a user-defined type conversion function to convert a
6921   // derived to base as such conversions are given Conversion Rank. They only
6922   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6923   QualType FromCanon
6924     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6925   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6926   if (FromCanon == ToCanon ||
6927       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6928     Candidate.Viable = false;
6929     Candidate.FailureKind = ovl_fail_trivial_conversion;
6930     return;
6931   }
6932 
6933   // To determine what the conversion from the result of calling the
6934   // conversion function to the type we're eventually trying to
6935   // convert to (ToType), we need to synthesize a call to the
6936   // conversion function and attempt copy initialization from it. This
6937   // makes sure that we get the right semantics with respect to
6938   // lvalues/rvalues and the type. Fortunately, we can allocate this
6939   // call on the stack and we don't need its arguments to be
6940   // well-formed.
6941   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6942                             VK_LValue, From->getLocStart());
6943   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6944                                 Context.getPointerType(Conversion->getType()),
6945                                 CK_FunctionToPointerDecay,
6946                                 &ConversionRef, VK_RValue);
6947 
6948   QualType ConversionType = Conversion->getConversionType();
6949   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6950     Candidate.Viable = false;
6951     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6952     return;
6953   }
6954 
6955   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6956 
6957   // Note that it is safe to allocate CallExpr on the stack here because
6958   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6959   // allocator).
6960   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6961   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6962                 From->getLocStart());
6963   ImplicitConversionSequence ICS =
6964     TryCopyInitialization(*this, &Call, ToType,
6965                           /*SuppressUserConversions=*/true,
6966                           /*InOverloadResolution=*/false,
6967                           /*AllowObjCWritebackConversion=*/false);
6968 
6969   switch (ICS.getKind()) {
6970   case ImplicitConversionSequence::StandardConversion:
6971     Candidate.FinalConversion = ICS.Standard;
6972 
6973     // C++ [over.ics.user]p3:
6974     //   If the user-defined conversion is specified by a specialization of a
6975     //   conversion function template, the second standard conversion sequence
6976     //   shall have exact match rank.
6977     if (Conversion->getPrimaryTemplate() &&
6978         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6979       Candidate.Viable = false;
6980       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6981       return;
6982     }
6983 
6984     // C++0x [dcl.init.ref]p5:
6985     //    In the second case, if the reference is an rvalue reference and
6986     //    the second standard conversion sequence of the user-defined
6987     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6988     //    program is ill-formed.
6989     if (ToType->isRValueReferenceType() &&
6990         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6991       Candidate.Viable = false;
6992       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6993       return;
6994     }
6995     break;
6996 
6997   case ImplicitConversionSequence::BadConversion:
6998     Candidate.Viable = false;
6999     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7000     return;
7001 
7002   default:
7003     llvm_unreachable(
7004            "Can only end up with a standard conversion sequence or failure");
7005   }
7006 
7007   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7008     Candidate.Viable = false;
7009     Candidate.FailureKind = ovl_fail_enable_if;
7010     Candidate.DeductionFailure.Data = FailedAttr;
7011     return;
7012   }
7013 
7014   if (Conversion->isMultiVersion() &&
7015       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7016     Candidate.Viable = false;
7017     Candidate.FailureKind = ovl_non_default_multiversion_function;
7018   }
7019 }
7020 
7021 /// \brief Adds a conversion function template specialization
7022 /// candidate to the overload set, using template argument deduction
7023 /// to deduce the template arguments of the conversion function
7024 /// template from the type that we are converting to (C++
7025 /// [temp.deduct.conv]).
7026 void
7027 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7028                                      DeclAccessPair FoundDecl,
7029                                      CXXRecordDecl *ActingDC,
7030                                      Expr *From, QualType ToType,
7031                                      OverloadCandidateSet &CandidateSet,
7032                                      bool AllowObjCConversionOnExplicit,
7033                                      bool AllowResultConversion) {
7034   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7035          "Only conversion function templates permitted here");
7036 
7037   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7038     return;
7039 
7040   TemplateDeductionInfo Info(CandidateSet.getLocation());
7041   CXXConversionDecl *Specialization = nullptr;
7042   if (TemplateDeductionResult Result
7043         = DeduceTemplateArguments(FunctionTemplate, ToType,
7044                                   Specialization, Info)) {
7045     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7046     Candidate.FoundDecl = FoundDecl;
7047     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7048     Candidate.Viable = false;
7049     Candidate.FailureKind = ovl_fail_bad_deduction;
7050     Candidate.IsSurrogate = false;
7051     Candidate.IgnoreObjectArgument = false;
7052     Candidate.ExplicitCallArguments = 1;
7053     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7054                                                           Info);
7055     return;
7056   }
7057 
7058   // Add the conversion function template specialization produced by
7059   // template argument deduction as a candidate.
7060   assert(Specialization && "Missing function template specialization?");
7061   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7062                          CandidateSet, AllowObjCConversionOnExplicit,
7063                          AllowResultConversion);
7064 }
7065 
7066 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7067 /// converts the given @c Object to a function pointer via the
7068 /// conversion function @c Conversion, and then attempts to call it
7069 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7070 /// the type of function that we'll eventually be calling.
7071 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7072                                  DeclAccessPair FoundDecl,
7073                                  CXXRecordDecl *ActingContext,
7074                                  const FunctionProtoType *Proto,
7075                                  Expr *Object,
7076                                  ArrayRef<Expr *> Args,
7077                                  OverloadCandidateSet& CandidateSet) {
7078   if (!CandidateSet.isNewCandidate(Conversion))
7079     return;
7080 
7081   // Overload resolution is always an unevaluated context.
7082   EnterExpressionEvaluationContext Unevaluated(
7083       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7084 
7085   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7086   Candidate.FoundDecl = FoundDecl;
7087   Candidate.Function = nullptr;
7088   Candidate.Surrogate = Conversion;
7089   Candidate.Viable = true;
7090   Candidate.IsSurrogate = true;
7091   Candidate.IgnoreObjectArgument = false;
7092   Candidate.ExplicitCallArguments = Args.size();
7093 
7094   // Determine the implicit conversion sequence for the implicit
7095   // object parameter.
7096   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7097       *this, CandidateSet.getLocation(), Object->getType(),
7098       Object->Classify(Context), Conversion, ActingContext);
7099   if (ObjectInit.isBad()) {
7100     Candidate.Viable = false;
7101     Candidate.FailureKind = ovl_fail_bad_conversion;
7102     Candidate.Conversions[0] = ObjectInit;
7103     return;
7104   }
7105 
7106   // The first conversion is actually a user-defined conversion whose
7107   // first conversion is ObjectInit's standard conversion (which is
7108   // effectively a reference binding). Record it as such.
7109   Candidate.Conversions[0].setUserDefined();
7110   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7111   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7112   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7113   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7114   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7115   Candidate.Conversions[0].UserDefined.After
7116     = Candidate.Conversions[0].UserDefined.Before;
7117   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7118 
7119   // Find the
7120   unsigned NumParams = Proto->getNumParams();
7121 
7122   // (C++ 13.3.2p2): A candidate function having fewer than m
7123   // parameters is viable only if it has an ellipsis in its parameter
7124   // list (8.3.5).
7125   if (Args.size() > NumParams && !Proto->isVariadic()) {
7126     Candidate.Viable = false;
7127     Candidate.FailureKind = ovl_fail_too_many_arguments;
7128     return;
7129   }
7130 
7131   // Function types don't have any default arguments, so just check if
7132   // we have enough arguments.
7133   if (Args.size() < NumParams) {
7134     // Not enough arguments.
7135     Candidate.Viable = false;
7136     Candidate.FailureKind = ovl_fail_too_few_arguments;
7137     return;
7138   }
7139 
7140   // Determine the implicit conversion sequences for each of the
7141   // arguments.
7142   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7143     if (ArgIdx < NumParams) {
7144       // (C++ 13.3.2p3): for F to be a viable function, there shall
7145       // exist for each argument an implicit conversion sequence
7146       // (13.3.3.1) that converts that argument to the corresponding
7147       // parameter of F.
7148       QualType ParamType = Proto->getParamType(ArgIdx);
7149       Candidate.Conversions[ArgIdx + 1]
7150         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7151                                 /*SuppressUserConversions=*/false,
7152                                 /*InOverloadResolution=*/false,
7153                                 /*AllowObjCWritebackConversion=*/
7154                                   getLangOpts().ObjCAutoRefCount);
7155       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7156         Candidate.Viable = false;
7157         Candidate.FailureKind = ovl_fail_bad_conversion;
7158         return;
7159       }
7160     } else {
7161       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7162       // argument for which there is no corresponding parameter is
7163       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7164       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7165     }
7166   }
7167 
7168   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7169     Candidate.Viable = false;
7170     Candidate.FailureKind = ovl_fail_enable_if;
7171     Candidate.DeductionFailure.Data = FailedAttr;
7172     return;
7173   }
7174 }
7175 
7176 /// \brief Add overload candidates for overloaded operators that are
7177 /// member functions.
7178 ///
7179 /// Add the overloaded operator candidates that are member functions
7180 /// for the operator Op that was used in an operator expression such
7181 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7182 /// CandidateSet will store the added overload candidates. (C++
7183 /// [over.match.oper]).
7184 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7185                                        SourceLocation OpLoc,
7186                                        ArrayRef<Expr *> Args,
7187                                        OverloadCandidateSet& CandidateSet,
7188                                        SourceRange OpRange) {
7189   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7190 
7191   // C++ [over.match.oper]p3:
7192   //   For a unary operator @ with an operand of a type whose
7193   //   cv-unqualified version is T1, and for a binary operator @ with
7194   //   a left operand of a type whose cv-unqualified version is T1 and
7195   //   a right operand of a type whose cv-unqualified version is T2,
7196   //   three sets of candidate functions, designated member
7197   //   candidates, non-member candidates and built-in candidates, are
7198   //   constructed as follows:
7199   QualType T1 = Args[0]->getType();
7200 
7201   //     -- If T1 is a complete class type or a class currently being
7202   //        defined, the set of member candidates is the result of the
7203   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7204   //        the set of member candidates is empty.
7205   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7206     // Complete the type if it can be completed.
7207     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7208       return;
7209     // If the type is neither complete nor being defined, bail out now.
7210     if (!T1Rec->getDecl()->getDefinition())
7211       return;
7212 
7213     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7214     LookupQualifiedName(Operators, T1Rec->getDecl());
7215     Operators.suppressDiagnostics();
7216 
7217     for (LookupResult::iterator Oper = Operators.begin(),
7218                              OperEnd = Operators.end();
7219          Oper != OperEnd;
7220          ++Oper)
7221       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7222                          Args[0]->Classify(Context), Args.slice(1),
7223                          CandidateSet, /*SuppressUserConversions=*/false);
7224   }
7225 }
7226 
7227 /// AddBuiltinCandidate - Add a candidate for a built-in
7228 /// operator. ResultTy and ParamTys are the result and parameter types
7229 /// of the built-in candidate, respectively. Args and NumArgs are the
7230 /// arguments being passed to the candidate. IsAssignmentOperator
7231 /// should be true when this built-in candidate is an assignment
7232 /// operator. NumContextualBoolArguments is the number of arguments
7233 /// (at the beginning of the argument list) that will be contextually
7234 /// converted to bool.
7235 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7236                                OverloadCandidateSet& CandidateSet,
7237                                bool IsAssignmentOperator,
7238                                unsigned NumContextualBoolArguments) {
7239   // Overload resolution is always an unevaluated context.
7240   EnterExpressionEvaluationContext Unevaluated(
7241       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7242 
7243   // Add this candidate
7244   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7245   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7246   Candidate.Function = nullptr;
7247   Candidate.IsSurrogate = false;
7248   Candidate.IgnoreObjectArgument = false;
7249   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7250 
7251   // Determine the implicit conversion sequences for each of the
7252   // arguments.
7253   Candidate.Viable = true;
7254   Candidate.ExplicitCallArguments = Args.size();
7255   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7256     // C++ [over.match.oper]p4:
7257     //   For the built-in assignment operators, conversions of the
7258     //   left operand are restricted as follows:
7259     //     -- no temporaries are introduced to hold the left operand, and
7260     //     -- no user-defined conversions are applied to the left
7261     //        operand to achieve a type match with the left-most
7262     //        parameter of a built-in candidate.
7263     //
7264     // We block these conversions by turning off user-defined
7265     // conversions, since that is the only way that initialization of
7266     // a reference to a non-class type can occur from something that
7267     // is not of the same type.
7268     if (ArgIdx < NumContextualBoolArguments) {
7269       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7270              "Contextual conversion to bool requires bool type");
7271       Candidate.Conversions[ArgIdx]
7272         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7273     } else {
7274       Candidate.Conversions[ArgIdx]
7275         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7276                                 ArgIdx == 0 && IsAssignmentOperator,
7277                                 /*InOverloadResolution=*/false,
7278                                 /*AllowObjCWritebackConversion=*/
7279                                   getLangOpts().ObjCAutoRefCount);
7280     }
7281     if (Candidate.Conversions[ArgIdx].isBad()) {
7282       Candidate.Viable = false;
7283       Candidate.FailureKind = ovl_fail_bad_conversion;
7284       break;
7285     }
7286   }
7287 }
7288 
7289 namespace {
7290 
7291 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7292 /// candidate operator functions for built-in operators (C++
7293 /// [over.built]). The types are separated into pointer types and
7294 /// enumeration types.
7295 class BuiltinCandidateTypeSet  {
7296   /// TypeSet - A set of types.
7297   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7298                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7299 
7300   /// PointerTypes - The set of pointer types that will be used in the
7301   /// built-in candidates.
7302   TypeSet PointerTypes;
7303 
7304   /// MemberPointerTypes - The set of member pointer types that will be
7305   /// used in the built-in candidates.
7306   TypeSet MemberPointerTypes;
7307 
7308   /// EnumerationTypes - The set of enumeration types that will be
7309   /// used in the built-in candidates.
7310   TypeSet EnumerationTypes;
7311 
7312   /// \brief The set of vector types that will be used in the built-in
7313   /// candidates.
7314   TypeSet VectorTypes;
7315 
7316   /// \brief A flag indicating non-record types are viable candidates
7317   bool HasNonRecordTypes;
7318 
7319   /// \brief A flag indicating whether either arithmetic or enumeration types
7320   /// were present in the candidate set.
7321   bool HasArithmeticOrEnumeralTypes;
7322 
7323   /// \brief A flag indicating whether the nullptr type was present in the
7324   /// candidate set.
7325   bool HasNullPtrType;
7326 
7327   /// Sema - The semantic analysis instance where we are building the
7328   /// candidate type set.
7329   Sema &SemaRef;
7330 
7331   /// Context - The AST context in which we will build the type sets.
7332   ASTContext &Context;
7333 
7334   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7335                                                const Qualifiers &VisibleQuals);
7336   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7337 
7338 public:
7339   /// iterator - Iterates through the types that are part of the set.
7340   typedef TypeSet::iterator iterator;
7341 
7342   BuiltinCandidateTypeSet(Sema &SemaRef)
7343     : HasNonRecordTypes(false),
7344       HasArithmeticOrEnumeralTypes(false),
7345       HasNullPtrType(false),
7346       SemaRef(SemaRef),
7347       Context(SemaRef.Context) { }
7348 
7349   void AddTypesConvertedFrom(QualType Ty,
7350                              SourceLocation Loc,
7351                              bool AllowUserConversions,
7352                              bool AllowExplicitConversions,
7353                              const Qualifiers &VisibleTypeConversionsQuals);
7354 
7355   /// pointer_begin - First pointer type found;
7356   iterator pointer_begin() { return PointerTypes.begin(); }
7357 
7358   /// pointer_end - Past the last pointer type found;
7359   iterator pointer_end() { return PointerTypes.end(); }
7360 
7361   /// member_pointer_begin - First member pointer type found;
7362   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7363 
7364   /// member_pointer_end - Past the last member pointer type found;
7365   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7366 
7367   /// enumeration_begin - First enumeration type found;
7368   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7369 
7370   /// enumeration_end - Past the last enumeration type found;
7371   iterator enumeration_end() { return EnumerationTypes.end(); }
7372 
7373   iterator vector_begin() { return VectorTypes.begin(); }
7374   iterator vector_end() { return VectorTypes.end(); }
7375 
7376   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7377   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7378   bool hasNullPtrType() const { return HasNullPtrType; }
7379 };
7380 
7381 } // end anonymous namespace
7382 
7383 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7384 /// the set of pointer types along with any more-qualified variants of
7385 /// that type. For example, if @p Ty is "int const *", this routine
7386 /// will add "int const *", "int const volatile *", "int const
7387 /// restrict *", and "int const volatile restrict *" to the set of
7388 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7389 /// false otherwise.
7390 ///
7391 /// FIXME: what to do about extended qualifiers?
7392 bool
7393 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7394                                              const Qualifiers &VisibleQuals) {
7395 
7396   // Insert this type.
7397   if (!PointerTypes.insert(Ty))
7398     return false;
7399 
7400   QualType PointeeTy;
7401   const PointerType *PointerTy = Ty->getAs<PointerType>();
7402   bool buildObjCPtr = false;
7403   if (!PointerTy) {
7404     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7405     PointeeTy = PTy->getPointeeType();
7406     buildObjCPtr = true;
7407   } else {
7408     PointeeTy = PointerTy->getPointeeType();
7409   }
7410 
7411   // Don't add qualified variants of arrays. For one, they're not allowed
7412   // (the qualifier would sink to the element type), and for another, the
7413   // only overload situation where it matters is subscript or pointer +- int,
7414   // and those shouldn't have qualifier variants anyway.
7415   if (PointeeTy->isArrayType())
7416     return true;
7417 
7418   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7419   bool hasVolatile = VisibleQuals.hasVolatile();
7420   bool hasRestrict = VisibleQuals.hasRestrict();
7421 
7422   // Iterate through all strict supersets of BaseCVR.
7423   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7424     if ((CVR | BaseCVR) != CVR) continue;
7425     // Skip over volatile if no volatile found anywhere in the types.
7426     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7427 
7428     // Skip over restrict if no restrict found anywhere in the types, or if
7429     // the type cannot be restrict-qualified.
7430     if ((CVR & Qualifiers::Restrict) &&
7431         (!hasRestrict ||
7432          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7433       continue;
7434 
7435     // Build qualified pointee type.
7436     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7437 
7438     // Build qualified pointer type.
7439     QualType QPointerTy;
7440     if (!buildObjCPtr)
7441       QPointerTy = Context.getPointerType(QPointeeTy);
7442     else
7443       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7444 
7445     // Insert qualified pointer type.
7446     PointerTypes.insert(QPointerTy);
7447   }
7448 
7449   return true;
7450 }
7451 
7452 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7453 /// to the set of pointer types along with any more-qualified variants of
7454 /// that type. For example, if @p Ty is "int const *", this routine
7455 /// will add "int const *", "int const volatile *", "int const
7456 /// restrict *", and "int const volatile restrict *" to the set of
7457 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7458 /// false otherwise.
7459 ///
7460 /// FIXME: what to do about extended qualifiers?
7461 bool
7462 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7463     QualType Ty) {
7464   // Insert this type.
7465   if (!MemberPointerTypes.insert(Ty))
7466     return false;
7467 
7468   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7469   assert(PointerTy && "type was not a member pointer type!");
7470 
7471   QualType PointeeTy = PointerTy->getPointeeType();
7472   // Don't add qualified variants of arrays. For one, they're not allowed
7473   // (the qualifier would sink to the element type), and for another, the
7474   // only overload situation where it matters is subscript or pointer +- int,
7475   // and those shouldn't have qualifier variants anyway.
7476   if (PointeeTy->isArrayType())
7477     return true;
7478   const Type *ClassTy = PointerTy->getClass();
7479 
7480   // Iterate through all strict supersets of the pointee type's CVR
7481   // qualifiers.
7482   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7483   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7484     if ((CVR | BaseCVR) != CVR) continue;
7485 
7486     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7487     MemberPointerTypes.insert(
7488       Context.getMemberPointerType(QPointeeTy, ClassTy));
7489   }
7490 
7491   return true;
7492 }
7493 
7494 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7495 /// Ty can be implicit converted to the given set of @p Types. We're
7496 /// primarily interested in pointer types and enumeration types. We also
7497 /// take member pointer types, for the conditional operator.
7498 /// AllowUserConversions is true if we should look at the conversion
7499 /// functions of a class type, and AllowExplicitConversions if we
7500 /// should also include the explicit conversion functions of a class
7501 /// type.
7502 void
7503 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7504                                                SourceLocation Loc,
7505                                                bool AllowUserConversions,
7506                                                bool AllowExplicitConversions,
7507                                                const Qualifiers &VisibleQuals) {
7508   // Only deal with canonical types.
7509   Ty = Context.getCanonicalType(Ty);
7510 
7511   // Look through reference types; they aren't part of the type of an
7512   // expression for the purposes of conversions.
7513   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7514     Ty = RefTy->getPointeeType();
7515 
7516   // If we're dealing with an array type, decay to the pointer.
7517   if (Ty->isArrayType())
7518     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7519 
7520   // Otherwise, we don't care about qualifiers on the type.
7521   Ty = Ty.getLocalUnqualifiedType();
7522 
7523   // Flag if we ever add a non-record type.
7524   const RecordType *TyRec = Ty->getAs<RecordType>();
7525   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7526 
7527   // Flag if we encounter an arithmetic type.
7528   HasArithmeticOrEnumeralTypes =
7529     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7530 
7531   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7532     PointerTypes.insert(Ty);
7533   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7534     // Insert our type, and its more-qualified variants, into the set
7535     // of types.
7536     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7537       return;
7538   } else if (Ty->isMemberPointerType()) {
7539     // Member pointers are far easier, since the pointee can't be converted.
7540     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7541       return;
7542   } else if (Ty->isEnumeralType()) {
7543     HasArithmeticOrEnumeralTypes = true;
7544     EnumerationTypes.insert(Ty);
7545   } else if (Ty->isVectorType()) {
7546     // We treat vector types as arithmetic types in many contexts as an
7547     // extension.
7548     HasArithmeticOrEnumeralTypes = true;
7549     VectorTypes.insert(Ty);
7550   } else if (Ty->isNullPtrType()) {
7551     HasNullPtrType = true;
7552   } else if (AllowUserConversions && TyRec) {
7553     // No conversion functions in incomplete types.
7554     if (!SemaRef.isCompleteType(Loc, Ty))
7555       return;
7556 
7557     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7558     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7559       if (isa<UsingShadowDecl>(D))
7560         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7561 
7562       // Skip conversion function templates; they don't tell us anything
7563       // about which builtin types we can convert to.
7564       if (isa<FunctionTemplateDecl>(D))
7565         continue;
7566 
7567       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7568       if (AllowExplicitConversions || !Conv->isExplicit()) {
7569         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7570                               VisibleQuals);
7571       }
7572     }
7573   }
7574 }
7575 
7576 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7577 /// the volatile- and non-volatile-qualified assignment operators for the
7578 /// given type to the candidate set.
7579 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7580                                                    QualType T,
7581                                                    ArrayRef<Expr *> Args,
7582                                     OverloadCandidateSet &CandidateSet) {
7583   QualType ParamTypes[2];
7584 
7585   // T& operator=(T&, T)
7586   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7587   ParamTypes[1] = T;
7588   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7589                         /*IsAssignmentOperator=*/true);
7590 
7591   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7592     // volatile T& operator=(volatile T&, T)
7593     ParamTypes[0]
7594       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7595     ParamTypes[1] = T;
7596     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7597                           /*IsAssignmentOperator=*/true);
7598   }
7599 }
7600 
7601 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7602 /// if any, found in visible type conversion functions found in ArgExpr's type.
7603 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7604     Qualifiers VRQuals;
7605     const RecordType *TyRec;
7606     if (const MemberPointerType *RHSMPType =
7607         ArgExpr->getType()->getAs<MemberPointerType>())
7608       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7609     else
7610       TyRec = ArgExpr->getType()->getAs<RecordType>();
7611     if (!TyRec) {
7612       // Just to be safe, assume the worst case.
7613       VRQuals.addVolatile();
7614       VRQuals.addRestrict();
7615       return VRQuals;
7616     }
7617 
7618     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7619     if (!ClassDecl->hasDefinition())
7620       return VRQuals;
7621 
7622     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7623       if (isa<UsingShadowDecl>(D))
7624         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7625       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7626         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7627         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7628           CanTy = ResTypeRef->getPointeeType();
7629         // Need to go down the pointer/mempointer chain and add qualifiers
7630         // as see them.
7631         bool done = false;
7632         while (!done) {
7633           if (CanTy.isRestrictQualified())
7634             VRQuals.addRestrict();
7635           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7636             CanTy = ResTypePtr->getPointeeType();
7637           else if (const MemberPointerType *ResTypeMPtr =
7638                 CanTy->getAs<MemberPointerType>())
7639             CanTy = ResTypeMPtr->getPointeeType();
7640           else
7641             done = true;
7642           if (CanTy.isVolatileQualified())
7643             VRQuals.addVolatile();
7644           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7645             return VRQuals;
7646         }
7647       }
7648     }
7649     return VRQuals;
7650 }
7651 
7652 namespace {
7653 
7654 /// \brief Helper class to manage the addition of builtin operator overload
7655 /// candidates. It provides shared state and utility methods used throughout
7656 /// the process, as well as a helper method to add each group of builtin
7657 /// operator overloads from the standard to a candidate set.
7658 class BuiltinOperatorOverloadBuilder {
7659   // Common instance state available to all overload candidate addition methods.
7660   Sema &S;
7661   ArrayRef<Expr *> Args;
7662   Qualifiers VisibleTypeConversionsQuals;
7663   bool HasArithmeticOrEnumeralCandidateType;
7664   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7665   OverloadCandidateSet &CandidateSet;
7666 
7667   static constexpr int ArithmeticTypesCap = 24;
7668   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7669 
7670   // Define some indices used to iterate over the arithemetic types in
7671   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7672   // types are that preserved by promotion (C++ [over.built]p2).
7673   unsigned FirstIntegralType,
7674            LastIntegralType;
7675   unsigned FirstPromotedIntegralType,
7676            LastPromotedIntegralType;
7677   unsigned FirstPromotedArithmeticType,
7678            LastPromotedArithmeticType;
7679   unsigned NumArithmeticTypes;
7680 
7681   void InitArithmeticTypes() {
7682     // Start of promoted types.
7683     FirstPromotedArithmeticType = 0;
7684     ArithmeticTypes.push_back(S.Context.FloatTy);
7685     ArithmeticTypes.push_back(S.Context.DoubleTy);
7686     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7687     if (S.Context.getTargetInfo().hasFloat128Type())
7688       ArithmeticTypes.push_back(S.Context.Float128Ty);
7689 
7690     // Start of integral types.
7691     FirstIntegralType = ArithmeticTypes.size();
7692     FirstPromotedIntegralType = ArithmeticTypes.size();
7693     ArithmeticTypes.push_back(S.Context.IntTy);
7694     ArithmeticTypes.push_back(S.Context.LongTy);
7695     ArithmeticTypes.push_back(S.Context.LongLongTy);
7696     if (S.Context.getTargetInfo().hasInt128Type())
7697       ArithmeticTypes.push_back(S.Context.Int128Ty);
7698     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7699     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7700     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7701     if (S.Context.getTargetInfo().hasInt128Type())
7702       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7703     LastPromotedIntegralType = ArithmeticTypes.size();
7704     LastPromotedArithmeticType = ArithmeticTypes.size();
7705     // End of promoted types.
7706 
7707     ArithmeticTypes.push_back(S.Context.BoolTy);
7708     ArithmeticTypes.push_back(S.Context.CharTy);
7709     ArithmeticTypes.push_back(S.Context.WCharTy);
7710     if (S.Context.getLangOpts().Char8)
7711       ArithmeticTypes.push_back(S.Context.Char8Ty);
7712     ArithmeticTypes.push_back(S.Context.Char16Ty);
7713     ArithmeticTypes.push_back(S.Context.Char32Ty);
7714     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7715     ArithmeticTypes.push_back(S.Context.ShortTy);
7716     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7717     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7718     LastIntegralType = ArithmeticTypes.size();
7719     NumArithmeticTypes = ArithmeticTypes.size();
7720     // End of integral types.
7721     // FIXME: What about complex? What about half?
7722 
7723     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7724            "Enough inline storage for all arithmetic types.");
7725   }
7726 
7727   /// \brief Helper method to factor out the common pattern of adding overloads
7728   /// for '++' and '--' builtin operators.
7729   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7730                                            bool HasVolatile,
7731                                            bool HasRestrict) {
7732     QualType ParamTypes[2] = {
7733       S.Context.getLValueReferenceType(CandidateTy),
7734       S.Context.IntTy
7735     };
7736 
7737     // Non-volatile version.
7738     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7739 
7740     // Use a heuristic to reduce number of builtin candidates in the set:
7741     // add volatile version only if there are conversions to a volatile type.
7742     if (HasVolatile) {
7743       ParamTypes[0] =
7744         S.Context.getLValueReferenceType(
7745           S.Context.getVolatileType(CandidateTy));
7746       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7747     }
7748 
7749     // Add restrict version only if there are conversions to a restrict type
7750     // and our candidate type is a non-restrict-qualified pointer.
7751     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7752         !CandidateTy.isRestrictQualified()) {
7753       ParamTypes[0]
7754         = S.Context.getLValueReferenceType(
7755             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7756       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7757 
7758       if (HasVolatile) {
7759         ParamTypes[0]
7760           = S.Context.getLValueReferenceType(
7761               S.Context.getCVRQualifiedType(CandidateTy,
7762                                             (Qualifiers::Volatile |
7763                                              Qualifiers::Restrict)));
7764         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7765       }
7766     }
7767 
7768   }
7769 
7770 public:
7771   BuiltinOperatorOverloadBuilder(
7772     Sema &S, ArrayRef<Expr *> Args,
7773     Qualifiers VisibleTypeConversionsQuals,
7774     bool HasArithmeticOrEnumeralCandidateType,
7775     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7776     OverloadCandidateSet &CandidateSet)
7777     : S(S), Args(Args),
7778       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7779       HasArithmeticOrEnumeralCandidateType(
7780         HasArithmeticOrEnumeralCandidateType),
7781       CandidateTypes(CandidateTypes),
7782       CandidateSet(CandidateSet) {
7783 
7784     InitArithmeticTypes();
7785   }
7786 
7787   // Increment is deprecated for bool since C++17.
7788   //
7789   // C++ [over.built]p3:
7790   //
7791   //   For every pair (T, VQ), where T is an arithmetic type other
7792   //   than bool, and VQ is either volatile or empty, there exist
7793   //   candidate operator functions of the form
7794   //
7795   //       VQ T&      operator++(VQ T&);
7796   //       T          operator++(VQ T&, int);
7797   //
7798   // C++ [over.built]p4:
7799   //
7800   //   For every pair (T, VQ), where T is an arithmetic type other
7801   //   than bool, and VQ is either volatile or empty, there exist
7802   //   candidate operator functions of the form
7803   //
7804   //       VQ T&      operator--(VQ T&);
7805   //       T          operator--(VQ T&, int);
7806   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7807     if (!HasArithmeticOrEnumeralCandidateType)
7808       return;
7809 
7810     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7811       const auto TypeOfT = ArithmeticTypes[Arith];
7812       if (TypeOfT == S.Context.BoolTy) {
7813         if (Op == OO_MinusMinus)
7814           continue;
7815         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7816           continue;
7817       }
7818       addPlusPlusMinusMinusStyleOverloads(
7819         TypeOfT,
7820         VisibleTypeConversionsQuals.hasVolatile(),
7821         VisibleTypeConversionsQuals.hasRestrict());
7822     }
7823   }
7824 
7825   // C++ [over.built]p5:
7826   //
7827   //   For every pair (T, VQ), where T is a cv-qualified or
7828   //   cv-unqualified object type, and VQ is either volatile or
7829   //   empty, there exist candidate operator functions of the form
7830   //
7831   //       T*VQ&      operator++(T*VQ&);
7832   //       T*VQ&      operator--(T*VQ&);
7833   //       T*         operator++(T*VQ&, int);
7834   //       T*         operator--(T*VQ&, int);
7835   void addPlusPlusMinusMinusPointerOverloads() {
7836     for (BuiltinCandidateTypeSet::iterator
7837               Ptr = CandidateTypes[0].pointer_begin(),
7838            PtrEnd = CandidateTypes[0].pointer_end();
7839          Ptr != PtrEnd; ++Ptr) {
7840       // Skip pointer types that aren't pointers to object types.
7841       if (!(*Ptr)->getPointeeType()->isObjectType())
7842         continue;
7843 
7844       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7845         (!(*Ptr).isVolatileQualified() &&
7846          VisibleTypeConversionsQuals.hasVolatile()),
7847         (!(*Ptr).isRestrictQualified() &&
7848          VisibleTypeConversionsQuals.hasRestrict()));
7849     }
7850   }
7851 
7852   // C++ [over.built]p6:
7853   //   For every cv-qualified or cv-unqualified object type T, there
7854   //   exist candidate operator functions of the form
7855   //
7856   //       T&         operator*(T*);
7857   //
7858   // C++ [over.built]p7:
7859   //   For every function type T that does not have cv-qualifiers or a
7860   //   ref-qualifier, there exist candidate operator functions of the form
7861   //       T&         operator*(T*);
7862   void addUnaryStarPointerOverloads() {
7863     for (BuiltinCandidateTypeSet::iterator
7864               Ptr = CandidateTypes[0].pointer_begin(),
7865            PtrEnd = CandidateTypes[0].pointer_end();
7866          Ptr != PtrEnd; ++Ptr) {
7867       QualType ParamTy = *Ptr;
7868       QualType PointeeTy = ParamTy->getPointeeType();
7869       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7870         continue;
7871 
7872       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7873         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7874           continue;
7875 
7876       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7877     }
7878   }
7879 
7880   // C++ [over.built]p9:
7881   //  For every promoted arithmetic type T, there exist candidate
7882   //  operator functions of the form
7883   //
7884   //       T         operator+(T);
7885   //       T         operator-(T);
7886   void addUnaryPlusOrMinusArithmeticOverloads() {
7887     if (!HasArithmeticOrEnumeralCandidateType)
7888       return;
7889 
7890     for (unsigned Arith = FirstPromotedArithmeticType;
7891          Arith < LastPromotedArithmeticType; ++Arith) {
7892       QualType ArithTy = ArithmeticTypes[Arith];
7893       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7894     }
7895 
7896     // Extension: We also add these operators for vector types.
7897     for (BuiltinCandidateTypeSet::iterator
7898               Vec = CandidateTypes[0].vector_begin(),
7899            VecEnd = CandidateTypes[0].vector_end();
7900          Vec != VecEnd; ++Vec) {
7901       QualType VecTy = *Vec;
7902       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7903     }
7904   }
7905 
7906   // C++ [over.built]p8:
7907   //   For every type T, there exist candidate operator functions of
7908   //   the form
7909   //
7910   //       T*         operator+(T*);
7911   void addUnaryPlusPointerOverloads() {
7912     for (BuiltinCandidateTypeSet::iterator
7913               Ptr = CandidateTypes[0].pointer_begin(),
7914            PtrEnd = CandidateTypes[0].pointer_end();
7915          Ptr != PtrEnd; ++Ptr) {
7916       QualType ParamTy = *Ptr;
7917       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7918     }
7919   }
7920 
7921   // C++ [over.built]p10:
7922   //   For every promoted integral type T, there exist candidate
7923   //   operator functions of the form
7924   //
7925   //        T         operator~(T);
7926   void addUnaryTildePromotedIntegralOverloads() {
7927     if (!HasArithmeticOrEnumeralCandidateType)
7928       return;
7929 
7930     for (unsigned Int = FirstPromotedIntegralType;
7931          Int < LastPromotedIntegralType; ++Int) {
7932       QualType IntTy = ArithmeticTypes[Int];
7933       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7934     }
7935 
7936     // Extension: We also add this operator for vector types.
7937     for (BuiltinCandidateTypeSet::iterator
7938               Vec = CandidateTypes[0].vector_begin(),
7939            VecEnd = CandidateTypes[0].vector_end();
7940          Vec != VecEnd; ++Vec) {
7941       QualType VecTy = *Vec;
7942       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7943     }
7944   }
7945 
7946   // C++ [over.match.oper]p16:
7947   //   For every pointer to member type T or type std::nullptr_t, there
7948   //   exist candidate operator functions of the form
7949   //
7950   //        bool operator==(T,T);
7951   //        bool operator!=(T,T);
7952   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7953     /// Set of (canonical) types that we've already handled.
7954     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7955 
7956     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7957       for (BuiltinCandidateTypeSet::iterator
7958                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7959              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7960            MemPtr != MemPtrEnd;
7961            ++MemPtr) {
7962         // Don't add the same builtin candidate twice.
7963         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7964           continue;
7965 
7966         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7967         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7968       }
7969 
7970       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7971         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7972         if (AddedTypes.insert(NullPtrTy).second) {
7973           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7974           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7975         }
7976       }
7977     }
7978   }
7979 
7980   // C++ [over.built]p15:
7981   //
7982   //   For every T, where T is an enumeration type or a pointer type,
7983   //   there exist candidate operator functions of the form
7984   //
7985   //        bool       operator<(T, T);
7986   //        bool       operator>(T, T);
7987   //        bool       operator<=(T, T);
7988   //        bool       operator>=(T, T);
7989   //        bool       operator==(T, T);
7990   //        bool       operator!=(T, T);
7991   void addRelationalPointerOrEnumeralOverloads() {
7992     // C++ [over.match.oper]p3:
7993     //   [...]the built-in candidates include all of the candidate operator
7994     //   functions defined in 13.6 that, compared to the given operator, [...]
7995     //   do not have the same parameter-type-list as any non-template non-member
7996     //   candidate.
7997     //
7998     // Note that in practice, this only affects enumeration types because there
7999     // aren't any built-in candidates of record type, and a user-defined operator
8000     // must have an operand of record or enumeration type. Also, the only other
8001     // overloaded operator with enumeration arguments, operator=,
8002     // cannot be overloaded for enumeration types, so this is the only place
8003     // where we must suppress candidates like this.
8004     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8005       UserDefinedBinaryOperators;
8006 
8007     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8008       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8009           CandidateTypes[ArgIdx].enumeration_end()) {
8010         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8011                                          CEnd = CandidateSet.end();
8012              C != CEnd; ++C) {
8013           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8014             continue;
8015 
8016           if (C->Function->isFunctionTemplateSpecialization())
8017             continue;
8018 
8019           QualType FirstParamType =
8020             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8021           QualType SecondParamType =
8022             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8023 
8024           // Skip if either parameter isn't of enumeral type.
8025           if (!FirstParamType->isEnumeralType() ||
8026               !SecondParamType->isEnumeralType())
8027             continue;
8028 
8029           // Add this operator to the set of known user-defined operators.
8030           UserDefinedBinaryOperators.insert(
8031             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8032                            S.Context.getCanonicalType(SecondParamType)));
8033         }
8034       }
8035     }
8036 
8037     /// Set of (canonical) types that we've already handled.
8038     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8039 
8040     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8041       for (BuiltinCandidateTypeSet::iterator
8042                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8043              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8044            Ptr != PtrEnd; ++Ptr) {
8045         // Don't add the same builtin candidate twice.
8046         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8047           continue;
8048 
8049         QualType ParamTypes[2] = { *Ptr, *Ptr };
8050         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8051       }
8052       for (BuiltinCandidateTypeSet::iterator
8053                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8054              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8055            Enum != EnumEnd; ++Enum) {
8056         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8057 
8058         // Don't add the same builtin candidate twice, or if a user defined
8059         // candidate exists.
8060         if (!AddedTypes.insert(CanonType).second ||
8061             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8062                                                             CanonType)))
8063           continue;
8064 
8065         QualType ParamTypes[2] = { *Enum, *Enum };
8066         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8067       }
8068     }
8069   }
8070 
8071   // C++ [over.built]p13:
8072   //
8073   //   For every cv-qualified or cv-unqualified object type T
8074   //   there exist candidate operator functions of the form
8075   //
8076   //      T*         operator+(T*, ptrdiff_t);
8077   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8078   //      T*         operator-(T*, ptrdiff_t);
8079   //      T*         operator+(ptrdiff_t, T*);
8080   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8081   //
8082   // C++ [over.built]p14:
8083   //
8084   //   For every T, where T is a pointer to object type, there
8085   //   exist candidate operator functions of the form
8086   //
8087   //      ptrdiff_t  operator-(T, T);
8088   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8089     /// Set of (canonical) types that we've already handled.
8090     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8091 
8092     for (int Arg = 0; Arg < 2; ++Arg) {
8093       QualType AsymmetricParamTypes[2] = {
8094         S.Context.getPointerDiffType(),
8095         S.Context.getPointerDiffType(),
8096       };
8097       for (BuiltinCandidateTypeSet::iterator
8098                 Ptr = CandidateTypes[Arg].pointer_begin(),
8099              PtrEnd = CandidateTypes[Arg].pointer_end();
8100            Ptr != PtrEnd; ++Ptr) {
8101         QualType PointeeTy = (*Ptr)->getPointeeType();
8102         if (!PointeeTy->isObjectType())
8103           continue;
8104 
8105         AsymmetricParamTypes[Arg] = *Ptr;
8106         if (Arg == 0 || Op == OO_Plus) {
8107           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8108           // T* operator+(ptrdiff_t, T*);
8109           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8110         }
8111         if (Op == OO_Minus) {
8112           // ptrdiff_t operator-(T, T);
8113           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8114             continue;
8115 
8116           QualType ParamTypes[2] = { *Ptr, *Ptr };
8117           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8118         }
8119       }
8120     }
8121   }
8122 
8123   // C++ [over.built]p12:
8124   //
8125   //   For every pair of promoted arithmetic types L and R, there
8126   //   exist candidate operator functions of the form
8127   //
8128   //        LR         operator*(L, R);
8129   //        LR         operator/(L, R);
8130   //        LR         operator+(L, R);
8131   //        LR         operator-(L, R);
8132   //        bool       operator<(L, R);
8133   //        bool       operator>(L, R);
8134   //        bool       operator<=(L, R);
8135   //        bool       operator>=(L, R);
8136   //        bool       operator==(L, R);
8137   //        bool       operator!=(L, R);
8138   //
8139   //   where LR is the result of the usual arithmetic conversions
8140   //   between types L and R.
8141   //
8142   // C++ [over.built]p24:
8143   //
8144   //   For every pair of promoted arithmetic types L and R, there exist
8145   //   candidate operator functions of the form
8146   //
8147   //        LR       operator?(bool, L, R);
8148   //
8149   //   where LR is the result of the usual arithmetic conversions
8150   //   between types L and R.
8151   // Our candidates ignore the first parameter.
8152   void addGenericBinaryArithmeticOverloads() {
8153     if (!HasArithmeticOrEnumeralCandidateType)
8154       return;
8155 
8156     for (unsigned Left = FirstPromotedArithmeticType;
8157          Left < LastPromotedArithmeticType; ++Left) {
8158       for (unsigned Right = FirstPromotedArithmeticType;
8159            Right < LastPromotedArithmeticType; ++Right) {
8160         QualType LandR[2] = { ArithmeticTypes[Left],
8161                               ArithmeticTypes[Right] };
8162         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8163       }
8164     }
8165 
8166     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8167     // conditional operator for vector types.
8168     for (BuiltinCandidateTypeSet::iterator
8169               Vec1 = CandidateTypes[0].vector_begin(),
8170            Vec1End = CandidateTypes[0].vector_end();
8171          Vec1 != Vec1End; ++Vec1) {
8172       for (BuiltinCandidateTypeSet::iterator
8173                 Vec2 = CandidateTypes[1].vector_begin(),
8174              Vec2End = CandidateTypes[1].vector_end();
8175            Vec2 != Vec2End; ++Vec2) {
8176         QualType LandR[2] = { *Vec1, *Vec2 };
8177         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8178       }
8179     }
8180   }
8181 
8182   // C++ [over.built]p17:
8183   //
8184   //   For every pair of promoted integral types L and R, there
8185   //   exist candidate operator functions of the form
8186   //
8187   //      LR         operator%(L, R);
8188   //      LR         operator&(L, R);
8189   //      LR         operator^(L, R);
8190   //      LR         operator|(L, R);
8191   //      L          operator<<(L, R);
8192   //      L          operator>>(L, R);
8193   //
8194   //   where LR is the result of the usual arithmetic conversions
8195   //   between types L and R.
8196   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8197     if (!HasArithmeticOrEnumeralCandidateType)
8198       return;
8199 
8200     for (unsigned Left = FirstPromotedIntegralType;
8201          Left < LastPromotedIntegralType; ++Left) {
8202       for (unsigned Right = FirstPromotedIntegralType;
8203            Right < LastPromotedIntegralType; ++Right) {
8204         QualType LandR[2] = { ArithmeticTypes[Left],
8205                               ArithmeticTypes[Right] };
8206         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8207       }
8208     }
8209   }
8210 
8211   // C++ [over.built]p20:
8212   //
8213   //   For every pair (T, VQ), where T is an enumeration or
8214   //   pointer to member type and VQ is either volatile or
8215   //   empty, there exist candidate operator functions of the form
8216   //
8217   //        VQ T&      operator=(VQ T&, T);
8218   void addAssignmentMemberPointerOrEnumeralOverloads() {
8219     /// Set of (canonical) types that we've already handled.
8220     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8221 
8222     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8223       for (BuiltinCandidateTypeSet::iterator
8224                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8225              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8226            Enum != EnumEnd; ++Enum) {
8227         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8228           continue;
8229 
8230         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8231       }
8232 
8233       for (BuiltinCandidateTypeSet::iterator
8234                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8235              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8236            MemPtr != MemPtrEnd; ++MemPtr) {
8237         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8238           continue;
8239 
8240         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8241       }
8242     }
8243   }
8244 
8245   // C++ [over.built]p19:
8246   //
8247   //   For every pair (T, VQ), where T is any type and VQ is either
8248   //   volatile or empty, there exist candidate operator functions
8249   //   of the form
8250   //
8251   //        T*VQ&      operator=(T*VQ&, T*);
8252   //
8253   // C++ [over.built]p21:
8254   //
8255   //   For every pair (T, VQ), where T is a cv-qualified or
8256   //   cv-unqualified object type and VQ is either volatile or
8257   //   empty, there exist candidate operator functions of the form
8258   //
8259   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8260   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8261   void addAssignmentPointerOverloads(bool isEqualOp) {
8262     /// Set of (canonical) types that we've already handled.
8263     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8264 
8265     for (BuiltinCandidateTypeSet::iterator
8266               Ptr = CandidateTypes[0].pointer_begin(),
8267            PtrEnd = CandidateTypes[0].pointer_end();
8268          Ptr != PtrEnd; ++Ptr) {
8269       // If this is operator=, keep track of the builtin candidates we added.
8270       if (isEqualOp)
8271         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8272       else if (!(*Ptr)->getPointeeType()->isObjectType())
8273         continue;
8274 
8275       // non-volatile version
8276       QualType ParamTypes[2] = {
8277         S.Context.getLValueReferenceType(*Ptr),
8278         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8279       };
8280       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8281                             /*IsAssigmentOperator=*/ isEqualOp);
8282 
8283       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8284                           VisibleTypeConversionsQuals.hasVolatile();
8285       if (NeedVolatile) {
8286         // volatile version
8287         ParamTypes[0] =
8288           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8289         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8290                               /*IsAssigmentOperator=*/isEqualOp);
8291       }
8292 
8293       if (!(*Ptr).isRestrictQualified() &&
8294           VisibleTypeConversionsQuals.hasRestrict()) {
8295         // restrict version
8296         ParamTypes[0]
8297           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8298         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8299                               /*IsAssigmentOperator=*/isEqualOp);
8300 
8301         if (NeedVolatile) {
8302           // volatile restrict version
8303           ParamTypes[0]
8304             = S.Context.getLValueReferenceType(
8305                 S.Context.getCVRQualifiedType(*Ptr,
8306                                               (Qualifiers::Volatile |
8307                                                Qualifiers::Restrict)));
8308           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8309                                 /*IsAssigmentOperator=*/isEqualOp);
8310         }
8311       }
8312     }
8313 
8314     if (isEqualOp) {
8315       for (BuiltinCandidateTypeSet::iterator
8316                 Ptr = CandidateTypes[1].pointer_begin(),
8317              PtrEnd = CandidateTypes[1].pointer_end();
8318            Ptr != PtrEnd; ++Ptr) {
8319         // Make sure we don't add the same candidate twice.
8320         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8321           continue;
8322 
8323         QualType ParamTypes[2] = {
8324           S.Context.getLValueReferenceType(*Ptr),
8325           *Ptr,
8326         };
8327 
8328         // non-volatile version
8329         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8330                               /*IsAssigmentOperator=*/true);
8331 
8332         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8333                            VisibleTypeConversionsQuals.hasVolatile();
8334         if (NeedVolatile) {
8335           // volatile version
8336           ParamTypes[0] =
8337             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8338           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8339                                 /*IsAssigmentOperator=*/true);
8340         }
8341 
8342         if (!(*Ptr).isRestrictQualified() &&
8343             VisibleTypeConversionsQuals.hasRestrict()) {
8344           // restrict version
8345           ParamTypes[0]
8346             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8347           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8348                                 /*IsAssigmentOperator=*/true);
8349 
8350           if (NeedVolatile) {
8351             // volatile restrict version
8352             ParamTypes[0]
8353               = S.Context.getLValueReferenceType(
8354                   S.Context.getCVRQualifiedType(*Ptr,
8355                                                 (Qualifiers::Volatile |
8356                                                  Qualifiers::Restrict)));
8357             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8358                                   /*IsAssigmentOperator=*/true);
8359           }
8360         }
8361       }
8362     }
8363   }
8364 
8365   // C++ [over.built]p18:
8366   //
8367   //   For every triple (L, VQ, R), where L is an arithmetic type,
8368   //   VQ is either volatile or empty, and R is a promoted
8369   //   arithmetic type, there exist candidate operator functions of
8370   //   the form
8371   //
8372   //        VQ L&      operator=(VQ L&, R);
8373   //        VQ L&      operator*=(VQ L&, R);
8374   //        VQ L&      operator/=(VQ L&, R);
8375   //        VQ L&      operator+=(VQ L&, R);
8376   //        VQ L&      operator-=(VQ L&, R);
8377   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8378     if (!HasArithmeticOrEnumeralCandidateType)
8379       return;
8380 
8381     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8382       for (unsigned Right = FirstPromotedArithmeticType;
8383            Right < LastPromotedArithmeticType; ++Right) {
8384         QualType ParamTypes[2];
8385         ParamTypes[1] = ArithmeticTypes[Right];
8386 
8387         // Add this built-in operator as a candidate (VQ is empty).
8388         ParamTypes[0] =
8389           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8390         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8391                               /*IsAssigmentOperator=*/isEqualOp);
8392 
8393         // Add this built-in operator as a candidate (VQ is 'volatile').
8394         if (VisibleTypeConversionsQuals.hasVolatile()) {
8395           ParamTypes[0] =
8396             S.Context.getVolatileType(ArithmeticTypes[Left]);
8397           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8398           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8399                                 /*IsAssigmentOperator=*/isEqualOp);
8400         }
8401       }
8402     }
8403 
8404     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8405     for (BuiltinCandidateTypeSet::iterator
8406               Vec1 = CandidateTypes[0].vector_begin(),
8407            Vec1End = CandidateTypes[0].vector_end();
8408          Vec1 != Vec1End; ++Vec1) {
8409       for (BuiltinCandidateTypeSet::iterator
8410                 Vec2 = CandidateTypes[1].vector_begin(),
8411              Vec2End = CandidateTypes[1].vector_end();
8412            Vec2 != Vec2End; ++Vec2) {
8413         QualType ParamTypes[2];
8414         ParamTypes[1] = *Vec2;
8415         // Add this built-in operator as a candidate (VQ is empty).
8416         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8417         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8418                               /*IsAssigmentOperator=*/isEqualOp);
8419 
8420         // Add this built-in operator as a candidate (VQ is 'volatile').
8421         if (VisibleTypeConversionsQuals.hasVolatile()) {
8422           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8423           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8424           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8425                                 /*IsAssigmentOperator=*/isEqualOp);
8426         }
8427       }
8428     }
8429   }
8430 
8431   // C++ [over.built]p22:
8432   //
8433   //   For every triple (L, VQ, R), where L is an integral type, VQ
8434   //   is either volatile or empty, and R is a promoted integral
8435   //   type, there exist candidate operator functions of the form
8436   //
8437   //        VQ L&       operator%=(VQ L&, R);
8438   //        VQ L&       operator<<=(VQ L&, R);
8439   //        VQ L&       operator>>=(VQ L&, R);
8440   //        VQ L&       operator&=(VQ L&, R);
8441   //        VQ L&       operator^=(VQ L&, R);
8442   //        VQ L&       operator|=(VQ L&, R);
8443   void addAssignmentIntegralOverloads() {
8444     if (!HasArithmeticOrEnumeralCandidateType)
8445       return;
8446 
8447     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8448       for (unsigned Right = FirstPromotedIntegralType;
8449            Right < LastPromotedIntegralType; ++Right) {
8450         QualType ParamTypes[2];
8451         ParamTypes[1] = ArithmeticTypes[Right];
8452 
8453         // Add this built-in operator as a candidate (VQ is empty).
8454         ParamTypes[0] =
8455           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8456         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8457         if (VisibleTypeConversionsQuals.hasVolatile()) {
8458           // Add this built-in operator as a candidate (VQ is 'volatile').
8459           ParamTypes[0] = ArithmeticTypes[Left];
8460           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8461           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8462           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8463         }
8464       }
8465     }
8466   }
8467 
8468   // C++ [over.operator]p23:
8469   //
8470   //   There also exist candidate operator functions of the form
8471   //
8472   //        bool        operator!(bool);
8473   //        bool        operator&&(bool, bool);
8474   //        bool        operator||(bool, bool);
8475   void addExclaimOverload() {
8476     QualType ParamTy = S.Context.BoolTy;
8477     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8478                           /*IsAssignmentOperator=*/false,
8479                           /*NumContextualBoolArguments=*/1);
8480   }
8481   void addAmpAmpOrPipePipeOverload() {
8482     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8483     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8484                           /*IsAssignmentOperator=*/false,
8485                           /*NumContextualBoolArguments=*/2);
8486   }
8487 
8488   // C++ [over.built]p13:
8489   //
8490   //   For every cv-qualified or cv-unqualified object type T there
8491   //   exist candidate operator functions of the form
8492   //
8493   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8494   //        T&         operator[](T*, ptrdiff_t);
8495   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8496   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8497   //        T&         operator[](ptrdiff_t, T*);
8498   void addSubscriptOverloads() {
8499     for (BuiltinCandidateTypeSet::iterator
8500               Ptr = CandidateTypes[0].pointer_begin(),
8501            PtrEnd = CandidateTypes[0].pointer_end();
8502          Ptr != PtrEnd; ++Ptr) {
8503       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8504       QualType PointeeType = (*Ptr)->getPointeeType();
8505       if (!PointeeType->isObjectType())
8506         continue;
8507 
8508       // T& operator[](T*, ptrdiff_t)
8509       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8510     }
8511 
8512     for (BuiltinCandidateTypeSet::iterator
8513               Ptr = CandidateTypes[1].pointer_begin(),
8514            PtrEnd = CandidateTypes[1].pointer_end();
8515          Ptr != PtrEnd; ++Ptr) {
8516       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8517       QualType PointeeType = (*Ptr)->getPointeeType();
8518       if (!PointeeType->isObjectType())
8519         continue;
8520 
8521       // T& operator[](ptrdiff_t, T*)
8522       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8523     }
8524   }
8525 
8526   // C++ [over.built]p11:
8527   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8528   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8529   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8530   //    there exist candidate operator functions of the form
8531   //
8532   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8533   //
8534   //    where CV12 is the union of CV1 and CV2.
8535   void addArrowStarOverloads() {
8536     for (BuiltinCandidateTypeSet::iterator
8537              Ptr = CandidateTypes[0].pointer_begin(),
8538            PtrEnd = CandidateTypes[0].pointer_end();
8539          Ptr != PtrEnd; ++Ptr) {
8540       QualType C1Ty = (*Ptr);
8541       QualType C1;
8542       QualifierCollector Q1;
8543       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8544       if (!isa<RecordType>(C1))
8545         continue;
8546       // heuristic to reduce number of builtin candidates in the set.
8547       // Add volatile/restrict version only if there are conversions to a
8548       // volatile/restrict type.
8549       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8550         continue;
8551       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8552         continue;
8553       for (BuiltinCandidateTypeSet::iterator
8554                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8555              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8556            MemPtr != MemPtrEnd; ++MemPtr) {
8557         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8558         QualType C2 = QualType(mptr->getClass(), 0);
8559         C2 = C2.getUnqualifiedType();
8560         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8561           break;
8562         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8563         // build CV12 T&
8564         QualType T = mptr->getPointeeType();
8565         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8566             T.isVolatileQualified())
8567           continue;
8568         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8569             T.isRestrictQualified())
8570           continue;
8571         T = Q1.apply(S.Context, T);
8572         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8573       }
8574     }
8575   }
8576 
8577   // Note that we don't consider the first argument, since it has been
8578   // contextually converted to bool long ago. The candidates below are
8579   // therefore added as binary.
8580   //
8581   // C++ [over.built]p25:
8582   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8583   //   enumeration type, there exist candidate operator functions of the form
8584   //
8585   //        T        operator?(bool, T, T);
8586   //
8587   void addConditionalOperatorOverloads() {
8588     /// Set of (canonical) types that we've already handled.
8589     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8590 
8591     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8592       for (BuiltinCandidateTypeSet::iterator
8593                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8594              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8595            Ptr != PtrEnd; ++Ptr) {
8596         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8597           continue;
8598 
8599         QualType ParamTypes[2] = { *Ptr, *Ptr };
8600         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8601       }
8602 
8603       for (BuiltinCandidateTypeSet::iterator
8604                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8605              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8606            MemPtr != MemPtrEnd; ++MemPtr) {
8607         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8608           continue;
8609 
8610         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8611         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8612       }
8613 
8614       if (S.getLangOpts().CPlusPlus11) {
8615         for (BuiltinCandidateTypeSet::iterator
8616                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8617                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8618              Enum != EnumEnd; ++Enum) {
8619           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8620             continue;
8621 
8622           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8623             continue;
8624 
8625           QualType ParamTypes[2] = { *Enum, *Enum };
8626           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8627         }
8628       }
8629     }
8630   }
8631 };
8632 
8633 } // end anonymous namespace
8634 
8635 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8636 /// operator overloads to the candidate set (C++ [over.built]), based
8637 /// on the operator @p Op and the arguments given. For example, if the
8638 /// operator is a binary '+', this routine might add "int
8639 /// operator+(int, int)" to cover integer addition.
8640 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8641                                         SourceLocation OpLoc,
8642                                         ArrayRef<Expr *> Args,
8643                                         OverloadCandidateSet &CandidateSet) {
8644   // Find all of the types that the arguments can convert to, but only
8645   // if the operator we're looking at has built-in operator candidates
8646   // that make use of these types. Also record whether we encounter non-record
8647   // candidate types or either arithmetic or enumeral candidate types.
8648   Qualifiers VisibleTypeConversionsQuals;
8649   VisibleTypeConversionsQuals.addConst();
8650   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8651     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8652 
8653   bool HasNonRecordCandidateType = false;
8654   bool HasArithmeticOrEnumeralCandidateType = false;
8655   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8656   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8657     CandidateTypes.emplace_back(*this);
8658     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8659                                                  OpLoc,
8660                                                  true,
8661                                                  (Op == OO_Exclaim ||
8662                                                   Op == OO_AmpAmp ||
8663                                                   Op == OO_PipePipe),
8664                                                  VisibleTypeConversionsQuals);
8665     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8666         CandidateTypes[ArgIdx].hasNonRecordTypes();
8667     HasArithmeticOrEnumeralCandidateType =
8668         HasArithmeticOrEnumeralCandidateType ||
8669         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8670   }
8671 
8672   // Exit early when no non-record types have been added to the candidate set
8673   // for any of the arguments to the operator.
8674   //
8675   // We can't exit early for !, ||, or &&, since there we have always have
8676   // 'bool' overloads.
8677   if (!HasNonRecordCandidateType &&
8678       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8679     return;
8680 
8681   // Setup an object to manage the common state for building overloads.
8682   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8683                                            VisibleTypeConversionsQuals,
8684                                            HasArithmeticOrEnumeralCandidateType,
8685                                            CandidateTypes, CandidateSet);
8686 
8687   // Dispatch over the operation to add in only those overloads which apply.
8688   switch (Op) {
8689   case OO_None:
8690   case NUM_OVERLOADED_OPERATORS:
8691     llvm_unreachable("Expected an overloaded operator");
8692 
8693   case OO_New:
8694   case OO_Delete:
8695   case OO_Array_New:
8696   case OO_Array_Delete:
8697   case OO_Call:
8698     llvm_unreachable(
8699                     "Special operators don't use AddBuiltinOperatorCandidates");
8700 
8701   case OO_Comma:
8702   case OO_Arrow:
8703   case OO_Coawait:
8704     // C++ [over.match.oper]p3:
8705     //   -- For the operator ',', the unary operator '&', the
8706     //      operator '->', or the operator 'co_await', the
8707     //      built-in candidates set is empty.
8708     break;
8709 
8710   case OO_Plus: // '+' is either unary or binary
8711     if (Args.size() == 1)
8712       OpBuilder.addUnaryPlusPointerOverloads();
8713     LLVM_FALLTHROUGH;
8714 
8715   case OO_Minus: // '-' is either unary or binary
8716     if (Args.size() == 1) {
8717       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8718     } else {
8719       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8720       OpBuilder.addGenericBinaryArithmeticOverloads();
8721     }
8722     break;
8723 
8724   case OO_Star: // '*' is either unary or binary
8725     if (Args.size() == 1)
8726       OpBuilder.addUnaryStarPointerOverloads();
8727     else
8728       OpBuilder.addGenericBinaryArithmeticOverloads();
8729     break;
8730 
8731   case OO_Slash:
8732     OpBuilder.addGenericBinaryArithmeticOverloads();
8733     break;
8734 
8735   case OO_PlusPlus:
8736   case OO_MinusMinus:
8737     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8738     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8739     break;
8740 
8741   case OO_EqualEqual:
8742   case OO_ExclaimEqual:
8743     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8744     LLVM_FALLTHROUGH;
8745 
8746   case OO_Less:
8747   case OO_Greater:
8748   case OO_LessEqual:
8749   case OO_GreaterEqual:
8750     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8751     OpBuilder.addGenericBinaryArithmeticOverloads();
8752     break;
8753 
8754   case OO_Spaceship:
8755     llvm_unreachable("<=> expressions not supported yet");
8756 
8757   case OO_Percent:
8758   case OO_Caret:
8759   case OO_Pipe:
8760   case OO_LessLess:
8761   case OO_GreaterGreater:
8762     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8763     break;
8764 
8765   case OO_Amp: // '&' is either unary or binary
8766     if (Args.size() == 1)
8767       // C++ [over.match.oper]p3:
8768       //   -- For the operator ',', the unary operator '&', or the
8769       //      operator '->', the built-in candidates set is empty.
8770       break;
8771 
8772     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8773     break;
8774 
8775   case OO_Tilde:
8776     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8777     break;
8778 
8779   case OO_Equal:
8780     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8781     LLVM_FALLTHROUGH;
8782 
8783   case OO_PlusEqual:
8784   case OO_MinusEqual:
8785     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8786     LLVM_FALLTHROUGH;
8787 
8788   case OO_StarEqual:
8789   case OO_SlashEqual:
8790     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8791     break;
8792 
8793   case OO_PercentEqual:
8794   case OO_LessLessEqual:
8795   case OO_GreaterGreaterEqual:
8796   case OO_AmpEqual:
8797   case OO_CaretEqual:
8798   case OO_PipeEqual:
8799     OpBuilder.addAssignmentIntegralOverloads();
8800     break;
8801 
8802   case OO_Exclaim:
8803     OpBuilder.addExclaimOverload();
8804     break;
8805 
8806   case OO_AmpAmp:
8807   case OO_PipePipe:
8808     OpBuilder.addAmpAmpOrPipePipeOverload();
8809     break;
8810 
8811   case OO_Subscript:
8812     OpBuilder.addSubscriptOverloads();
8813     break;
8814 
8815   case OO_ArrowStar:
8816     OpBuilder.addArrowStarOverloads();
8817     break;
8818 
8819   case OO_Conditional:
8820     OpBuilder.addConditionalOperatorOverloads();
8821     OpBuilder.addGenericBinaryArithmeticOverloads();
8822     break;
8823   }
8824 }
8825 
8826 /// \brief Add function candidates found via argument-dependent lookup
8827 /// to the set of overloading candidates.
8828 ///
8829 /// This routine performs argument-dependent name lookup based on the
8830 /// given function name (which may also be an operator name) and adds
8831 /// all of the overload candidates found by ADL to the overload
8832 /// candidate set (C++ [basic.lookup.argdep]).
8833 void
8834 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8835                                            SourceLocation Loc,
8836                                            ArrayRef<Expr *> Args,
8837                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8838                                            OverloadCandidateSet& CandidateSet,
8839                                            bool PartialOverloading) {
8840   ADLResult Fns;
8841 
8842   // FIXME: This approach for uniquing ADL results (and removing
8843   // redundant candidates from the set) relies on pointer-equality,
8844   // which means we need to key off the canonical decl.  However,
8845   // always going back to the canonical decl might not get us the
8846   // right set of default arguments.  What default arguments are
8847   // we supposed to consider on ADL candidates, anyway?
8848 
8849   // FIXME: Pass in the explicit template arguments?
8850   ArgumentDependentLookup(Name, Loc, Args, Fns);
8851 
8852   // Erase all of the candidates we already knew about.
8853   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8854                                    CandEnd = CandidateSet.end();
8855        Cand != CandEnd; ++Cand)
8856     if (Cand->Function) {
8857       Fns.erase(Cand->Function);
8858       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8859         Fns.erase(FunTmpl);
8860     }
8861 
8862   // For each of the ADL candidates we found, add it to the overload
8863   // set.
8864   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8865     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8866     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8867       if (ExplicitTemplateArgs)
8868         continue;
8869 
8870       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8871                            PartialOverloading);
8872     } else
8873       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8874                                    FoundDecl, ExplicitTemplateArgs,
8875                                    Args, CandidateSet, PartialOverloading);
8876   }
8877 }
8878 
8879 namespace {
8880 enum class Comparison { Equal, Better, Worse };
8881 }
8882 
8883 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8884 /// overload resolution.
8885 ///
8886 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8887 /// Cand1's first N enable_if attributes have precisely the same conditions as
8888 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8889 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8890 ///
8891 /// Note that you can have a pair of candidates such that Cand1's enable_if
8892 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8893 /// worse than Cand1's.
8894 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8895                                        const FunctionDecl *Cand2) {
8896   // Common case: One (or both) decls don't have enable_if attrs.
8897   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8898   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8899   if (!Cand1Attr || !Cand2Attr) {
8900     if (Cand1Attr == Cand2Attr)
8901       return Comparison::Equal;
8902     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8903   }
8904 
8905   // FIXME: The next several lines are just
8906   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8907   // instead of reverse order which is how they're stored in the AST.
8908   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8909   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8910 
8911   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8912   // has fewer enable_if attributes than Cand2.
8913   if (Cand1Attrs.size() < Cand2Attrs.size())
8914     return Comparison::Worse;
8915 
8916   auto Cand1I = Cand1Attrs.begin();
8917   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8918   for (auto &Cand2A : Cand2Attrs) {
8919     Cand1ID.clear();
8920     Cand2ID.clear();
8921 
8922     auto &Cand1A = *Cand1I++;
8923     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8924     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8925     if (Cand1ID != Cand2ID)
8926       return Comparison::Worse;
8927   }
8928 
8929   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8930 }
8931 
8932 /// isBetterOverloadCandidate - Determines whether the first overload
8933 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8934 bool clang::isBetterOverloadCandidate(
8935     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8936     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8937   // Define viable functions to be better candidates than non-viable
8938   // functions.
8939   if (!Cand2.Viable)
8940     return Cand1.Viable;
8941   else if (!Cand1.Viable)
8942     return false;
8943 
8944   // C++ [over.match.best]p1:
8945   //
8946   //   -- if F is a static member function, ICS1(F) is defined such
8947   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8948   //      any function G, and, symmetrically, ICS1(G) is neither
8949   //      better nor worse than ICS1(F).
8950   unsigned StartArg = 0;
8951   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8952     StartArg = 1;
8953 
8954   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8955     // We don't allow incompatible pointer conversions in C++.
8956     if (!S.getLangOpts().CPlusPlus)
8957       return ICS.isStandard() &&
8958              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8959 
8960     // The only ill-formed conversion we allow in C++ is the string literal to
8961     // char* conversion, which is only considered ill-formed after C++11.
8962     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8963            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8964   };
8965 
8966   // Define functions that don't require ill-formed conversions for a given
8967   // argument to be better candidates than functions that do.
8968   unsigned NumArgs = Cand1.Conversions.size();
8969   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8970   bool HasBetterConversion = false;
8971   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8972     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8973     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8974     if (Cand1Bad != Cand2Bad) {
8975       if (Cand1Bad)
8976         return false;
8977       HasBetterConversion = true;
8978     }
8979   }
8980 
8981   if (HasBetterConversion)
8982     return true;
8983 
8984   // C++ [over.match.best]p1:
8985   //   A viable function F1 is defined to be a better function than another
8986   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8987   //   conversion sequence than ICSi(F2), and then...
8988   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8989     switch (CompareImplicitConversionSequences(S, Loc,
8990                                                Cand1.Conversions[ArgIdx],
8991                                                Cand2.Conversions[ArgIdx])) {
8992     case ImplicitConversionSequence::Better:
8993       // Cand1 has a better conversion sequence.
8994       HasBetterConversion = true;
8995       break;
8996 
8997     case ImplicitConversionSequence::Worse:
8998       // Cand1 can't be better than Cand2.
8999       return false;
9000 
9001     case ImplicitConversionSequence::Indistinguishable:
9002       // Do nothing.
9003       break;
9004     }
9005   }
9006 
9007   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9008   //       ICSj(F2), or, if not that,
9009   if (HasBetterConversion)
9010     return true;
9011 
9012   //   -- the context is an initialization by user-defined conversion
9013   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9014   //      from the return type of F1 to the destination type (i.e.,
9015   //      the type of the entity being initialized) is a better
9016   //      conversion sequence than the standard conversion sequence
9017   //      from the return type of F2 to the destination type.
9018   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9019       Cand1.Function && Cand2.Function &&
9020       isa<CXXConversionDecl>(Cand1.Function) &&
9021       isa<CXXConversionDecl>(Cand2.Function)) {
9022     // First check whether we prefer one of the conversion functions over the
9023     // other. This only distinguishes the results in non-standard, extension
9024     // cases such as the conversion from a lambda closure type to a function
9025     // pointer or block.
9026     ImplicitConversionSequence::CompareKind Result =
9027         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9028     if (Result == ImplicitConversionSequence::Indistinguishable)
9029       Result = CompareStandardConversionSequences(S, Loc,
9030                                                   Cand1.FinalConversion,
9031                                                   Cand2.FinalConversion);
9032 
9033     if (Result != ImplicitConversionSequence::Indistinguishable)
9034       return Result == ImplicitConversionSequence::Better;
9035 
9036     // FIXME: Compare kind of reference binding if conversion functions
9037     // convert to a reference type used in direct reference binding, per
9038     // C++14 [over.match.best]p1 section 2 bullet 3.
9039   }
9040 
9041   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9042   // as combined with the resolution to CWG issue 243.
9043   //
9044   // When the context is initialization by constructor ([over.match.ctor] or
9045   // either phase of [over.match.list]), a constructor is preferred over
9046   // a conversion function.
9047   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9048       Cand1.Function && Cand2.Function &&
9049       isa<CXXConstructorDecl>(Cand1.Function) !=
9050           isa<CXXConstructorDecl>(Cand2.Function))
9051     return isa<CXXConstructorDecl>(Cand1.Function);
9052 
9053   //    -- F1 is a non-template function and F2 is a function template
9054   //       specialization, or, if not that,
9055   bool Cand1IsSpecialization = Cand1.Function &&
9056                                Cand1.Function->getPrimaryTemplate();
9057   bool Cand2IsSpecialization = Cand2.Function &&
9058                                Cand2.Function->getPrimaryTemplate();
9059   if (Cand1IsSpecialization != Cand2IsSpecialization)
9060     return Cand2IsSpecialization;
9061 
9062   //   -- F1 and F2 are function template specializations, and the function
9063   //      template for F1 is more specialized than the template for F2
9064   //      according to the partial ordering rules described in 14.5.5.2, or,
9065   //      if not that,
9066   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9067     if (FunctionTemplateDecl *BetterTemplate
9068           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9069                                          Cand2.Function->getPrimaryTemplate(),
9070                                          Loc,
9071                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9072                                                              : TPOC_Call,
9073                                          Cand1.ExplicitCallArguments,
9074                                          Cand2.ExplicitCallArguments))
9075       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9076   }
9077 
9078   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9079   // A derived-class constructor beats an (inherited) base class constructor.
9080   bool Cand1IsInherited =
9081       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9082   bool Cand2IsInherited =
9083       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9084   if (Cand1IsInherited != Cand2IsInherited)
9085     return Cand2IsInherited;
9086   else if (Cand1IsInherited) {
9087     assert(Cand2IsInherited);
9088     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9089     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9090     if (Cand1Class->isDerivedFrom(Cand2Class))
9091       return true;
9092     if (Cand2Class->isDerivedFrom(Cand1Class))
9093       return false;
9094     // Inherited from sibling base classes: still ambiguous.
9095   }
9096 
9097   // Check C++17 tie-breakers for deduction guides.
9098   {
9099     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9100     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9101     if (Guide1 && Guide2) {
9102       //  -- F1 is generated from a deduction-guide and F2 is not
9103       if (Guide1->isImplicit() != Guide2->isImplicit())
9104         return Guide2->isImplicit();
9105 
9106       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9107       if (Guide1->isCopyDeductionCandidate())
9108         return true;
9109     }
9110   }
9111 
9112   // Check for enable_if value-based overload resolution.
9113   if (Cand1.Function && Cand2.Function) {
9114     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9115     if (Cmp != Comparison::Equal)
9116       return Cmp == Comparison::Better;
9117   }
9118 
9119   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9120     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9121     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9122            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9123   }
9124 
9125   bool HasPS1 = Cand1.Function != nullptr &&
9126                 functionHasPassObjectSizeParams(Cand1.Function);
9127   bool HasPS2 = Cand2.Function != nullptr &&
9128                 functionHasPassObjectSizeParams(Cand2.Function);
9129   return HasPS1 != HasPS2 && HasPS1;
9130 }
9131 
9132 /// Determine whether two declarations are "equivalent" for the purposes of
9133 /// name lookup and overload resolution. This applies when the same internal/no
9134 /// linkage entity is defined by two modules (probably by textually including
9135 /// the same header). In such a case, we don't consider the declarations to
9136 /// declare the same entity, but we also don't want lookups with both
9137 /// declarations visible to be ambiguous in some cases (this happens when using
9138 /// a modularized libstdc++).
9139 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9140                                                   const NamedDecl *B) {
9141   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9142   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9143   if (!VA || !VB)
9144     return false;
9145 
9146   // The declarations must be declaring the same name as an internal linkage
9147   // entity in different modules.
9148   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9149           VB->getDeclContext()->getRedeclContext()) ||
9150       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9151           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9152       VA->isExternallyVisible() || VB->isExternallyVisible())
9153     return false;
9154 
9155   // Check that the declarations appear to be equivalent.
9156   //
9157   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9158   // For constants and functions, we should check the initializer or body is
9159   // the same. For non-constant variables, we shouldn't allow it at all.
9160   if (Context.hasSameType(VA->getType(), VB->getType()))
9161     return true;
9162 
9163   // Enum constants within unnamed enumerations will have different types, but
9164   // may still be similar enough to be interchangeable for our purposes.
9165   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9166     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9167       // Only handle anonymous enums. If the enumerations were named and
9168       // equivalent, they would have been merged to the same type.
9169       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9170       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9171       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9172           !Context.hasSameType(EnumA->getIntegerType(),
9173                                EnumB->getIntegerType()))
9174         return false;
9175       // Allow this only if the value is the same for both enumerators.
9176       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9177     }
9178   }
9179 
9180   // Nothing else is sufficiently similar.
9181   return false;
9182 }
9183 
9184 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9185     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9186   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9187 
9188   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9189   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9190       << !M << (M ? M->getFullModuleName() : "");
9191 
9192   for (auto *E : Equiv) {
9193     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9194     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9195         << !M << (M ? M->getFullModuleName() : "");
9196   }
9197 }
9198 
9199 /// \brief Computes the best viable function (C++ 13.3.3)
9200 /// within an overload candidate set.
9201 ///
9202 /// \param Loc The location of the function name (or operator symbol) for
9203 /// which overload resolution occurs.
9204 ///
9205 /// \param Best If overload resolution was successful or found a deleted
9206 /// function, \p Best points to the candidate function found.
9207 ///
9208 /// \returns The result of overload resolution.
9209 OverloadingResult
9210 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9211                                          iterator &Best) {
9212   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9213   std::transform(begin(), end(), std::back_inserter(Candidates),
9214                  [](OverloadCandidate &Cand) { return &Cand; });
9215 
9216   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9217   // are accepted by both clang and NVCC. However, during a particular
9218   // compilation mode only one call variant is viable. We need to
9219   // exclude non-viable overload candidates from consideration based
9220   // only on their host/device attributes. Specifically, if one
9221   // candidate call is WrongSide and the other is SameSide, we ignore
9222   // the WrongSide candidate.
9223   if (S.getLangOpts().CUDA) {
9224     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9225     bool ContainsSameSideCandidate =
9226         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9227           return Cand->Function &&
9228                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9229                      Sema::CFP_SameSide;
9230         });
9231     if (ContainsSameSideCandidate) {
9232       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9233         return Cand->Function &&
9234                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9235                    Sema::CFP_WrongSide;
9236       };
9237       llvm::erase_if(Candidates, IsWrongSideCandidate);
9238     }
9239   }
9240 
9241   // Find the best viable function.
9242   Best = end();
9243   for (auto *Cand : Candidates)
9244     if (Cand->Viable)
9245       if (Best == end() ||
9246           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9247         Best = Cand;
9248 
9249   // If we didn't find any viable functions, abort.
9250   if (Best == end())
9251     return OR_No_Viable_Function;
9252 
9253   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9254 
9255   // Make sure that this function is better than every other viable
9256   // function. If not, we have an ambiguity.
9257   for (auto *Cand : Candidates) {
9258     if (Cand->Viable && Cand != Best &&
9259         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9260       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9261                                                    Cand->Function)) {
9262         EquivalentCands.push_back(Cand->Function);
9263         continue;
9264       }
9265 
9266       Best = end();
9267       return OR_Ambiguous;
9268     }
9269   }
9270 
9271   // Best is the best viable function.
9272   if (Best->Function &&
9273       (Best->Function->isDeleted() ||
9274        S.isFunctionConsideredUnavailable(Best->Function)))
9275     return OR_Deleted;
9276 
9277   if (!EquivalentCands.empty())
9278     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9279                                                     EquivalentCands);
9280 
9281   return OR_Success;
9282 }
9283 
9284 namespace {
9285 
9286 enum OverloadCandidateKind {
9287   oc_function,
9288   oc_method,
9289   oc_constructor,
9290   oc_function_template,
9291   oc_method_template,
9292   oc_constructor_template,
9293   oc_implicit_default_constructor,
9294   oc_implicit_copy_constructor,
9295   oc_implicit_move_constructor,
9296   oc_implicit_copy_assignment,
9297   oc_implicit_move_assignment,
9298   oc_inherited_constructor,
9299   oc_inherited_constructor_template
9300 };
9301 
9302 static OverloadCandidateKind
9303 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9304                           std::string &Description) {
9305   bool isTemplate = false;
9306 
9307   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9308     isTemplate = true;
9309     Description = S.getTemplateArgumentBindingsText(
9310       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9311   }
9312 
9313   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9314     if (!Ctor->isImplicit()) {
9315       if (isa<ConstructorUsingShadowDecl>(Found))
9316         return isTemplate ? oc_inherited_constructor_template
9317                           : oc_inherited_constructor;
9318       else
9319         return isTemplate ? oc_constructor_template : oc_constructor;
9320     }
9321 
9322     if (Ctor->isDefaultConstructor())
9323       return oc_implicit_default_constructor;
9324 
9325     if (Ctor->isMoveConstructor())
9326       return oc_implicit_move_constructor;
9327 
9328     assert(Ctor->isCopyConstructor() &&
9329            "unexpected sort of implicit constructor");
9330     return oc_implicit_copy_constructor;
9331   }
9332 
9333   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9334     // This actually gets spelled 'candidate function' for now, but
9335     // it doesn't hurt to split it out.
9336     if (!Meth->isImplicit())
9337       return isTemplate ? oc_method_template : oc_method;
9338 
9339     if (Meth->isMoveAssignmentOperator())
9340       return oc_implicit_move_assignment;
9341 
9342     if (Meth->isCopyAssignmentOperator())
9343       return oc_implicit_copy_assignment;
9344 
9345     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9346     return oc_method;
9347   }
9348 
9349   return isTemplate ? oc_function_template : oc_function;
9350 }
9351 
9352 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9353   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9354   // set.
9355   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9356     S.Diag(FoundDecl->getLocation(),
9357            diag::note_ovl_candidate_inherited_constructor)
9358       << Shadow->getNominatedBaseClass();
9359 }
9360 
9361 } // end anonymous namespace
9362 
9363 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9364                                     const FunctionDecl *FD) {
9365   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9366     bool AlwaysTrue;
9367     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9368       return false;
9369     if (!AlwaysTrue)
9370       return false;
9371   }
9372   return true;
9373 }
9374 
9375 /// \brief Returns true if we can take the address of the function.
9376 ///
9377 /// \param Complain - If true, we'll emit a diagnostic
9378 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9379 ///   we in overload resolution?
9380 /// \param Loc - The location of the statement we're complaining about. Ignored
9381 ///   if we're not complaining, or if we're in overload resolution.
9382 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9383                                               bool Complain,
9384                                               bool InOverloadResolution,
9385                                               SourceLocation Loc) {
9386   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9387     if (Complain) {
9388       if (InOverloadResolution)
9389         S.Diag(FD->getLocStart(),
9390                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9391       else
9392         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9393     }
9394     return false;
9395   }
9396 
9397   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9398     return P->hasAttr<PassObjectSizeAttr>();
9399   });
9400   if (I == FD->param_end())
9401     return true;
9402 
9403   if (Complain) {
9404     // Add one to ParamNo because it's user-facing
9405     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9406     if (InOverloadResolution)
9407       S.Diag(FD->getLocation(),
9408              diag::note_ovl_candidate_has_pass_object_size_params)
9409           << ParamNo;
9410     else
9411       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9412           << FD << ParamNo;
9413   }
9414   return false;
9415 }
9416 
9417 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9418                                                const FunctionDecl *FD) {
9419   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9420                                            /*InOverloadResolution=*/true,
9421                                            /*Loc=*/SourceLocation());
9422 }
9423 
9424 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9425                                              bool Complain,
9426                                              SourceLocation Loc) {
9427   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9428                                              /*InOverloadResolution=*/false,
9429                                              Loc);
9430 }
9431 
9432 // Notes the location of an overload candidate.
9433 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9434                                  QualType DestType, bool TakingAddress) {
9435   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9436     return;
9437   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9438     return;
9439 
9440   std::string FnDesc;
9441   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9442   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9443                              << (unsigned) K << Fn << FnDesc;
9444 
9445   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9446   Diag(Fn->getLocation(), PD);
9447   MaybeEmitInheritedConstructorNote(*this, Found);
9448 }
9449 
9450 // Notes the location of all overload candidates designated through
9451 // OverloadedExpr
9452 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9453                                      bool TakingAddress) {
9454   assert(OverloadedExpr->getType() == Context.OverloadTy);
9455 
9456   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9457   OverloadExpr *OvlExpr = Ovl.Expression;
9458 
9459   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9460                             IEnd = OvlExpr->decls_end();
9461        I != IEnd; ++I) {
9462     if (FunctionTemplateDecl *FunTmpl =
9463                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9464       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9465                             TakingAddress);
9466     } else if (FunctionDecl *Fun
9467                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9468       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9469     }
9470   }
9471 }
9472 
9473 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9474 /// "lead" diagnostic; it will be given two arguments, the source and
9475 /// target types of the conversion.
9476 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9477                                  Sema &S,
9478                                  SourceLocation CaretLoc,
9479                                  const PartialDiagnostic &PDiag) const {
9480   S.Diag(CaretLoc, PDiag)
9481     << Ambiguous.getFromType() << Ambiguous.getToType();
9482   // FIXME: The note limiting machinery is borrowed from
9483   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9484   // refactoring here.
9485   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9486   unsigned CandsShown = 0;
9487   AmbiguousConversionSequence::const_iterator I, E;
9488   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9489     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9490       break;
9491     ++CandsShown;
9492     S.NoteOverloadCandidate(I->first, I->second);
9493   }
9494   if (I != E)
9495     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9496 }
9497 
9498 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9499                                   unsigned I, bool TakingCandidateAddress) {
9500   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9501   assert(Conv.isBad());
9502   assert(Cand->Function && "for now, candidate must be a function");
9503   FunctionDecl *Fn = Cand->Function;
9504 
9505   // There's a conversion slot for the object argument if this is a
9506   // non-constructor method.  Note that 'I' corresponds the
9507   // conversion-slot index.
9508   bool isObjectArgument = false;
9509   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9510     if (I == 0)
9511       isObjectArgument = true;
9512     else
9513       I--;
9514   }
9515 
9516   std::string FnDesc;
9517   OverloadCandidateKind FnKind =
9518       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9519 
9520   Expr *FromExpr = Conv.Bad.FromExpr;
9521   QualType FromTy = Conv.Bad.getFromType();
9522   QualType ToTy = Conv.Bad.getToType();
9523 
9524   if (FromTy == S.Context.OverloadTy) {
9525     assert(FromExpr && "overload set argument came from implicit argument?");
9526     Expr *E = FromExpr->IgnoreParens();
9527     if (isa<UnaryOperator>(E))
9528       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9529     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9530 
9531     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9532       << (unsigned) FnKind << FnDesc
9533       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9534       << ToTy << Name << I+1;
9535     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9536     return;
9537   }
9538 
9539   // Do some hand-waving analysis to see if the non-viability is due
9540   // to a qualifier mismatch.
9541   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9542   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9543   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9544     CToTy = RT->getPointeeType();
9545   else {
9546     // TODO: detect and diagnose the full richness of const mismatches.
9547     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9548       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9549         CFromTy = FromPT->getPointeeType();
9550         CToTy = ToPT->getPointeeType();
9551       }
9552   }
9553 
9554   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9555       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9556     Qualifiers FromQs = CFromTy.getQualifiers();
9557     Qualifiers ToQs = CToTy.getQualifiers();
9558 
9559     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9560       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9561         << (unsigned) FnKind << FnDesc
9562         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9563         << FromTy
9564         << FromQs.getAddressSpaceAttributePrintValue()
9565         << ToQs.getAddressSpaceAttributePrintValue()
9566         << (unsigned) isObjectArgument << I+1;
9567       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9568       return;
9569     }
9570 
9571     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9572       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9573         << (unsigned) FnKind << FnDesc
9574         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9575         << FromTy
9576         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9577         << (unsigned) isObjectArgument << I+1;
9578       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9579       return;
9580     }
9581 
9582     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9583       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9584       << (unsigned) FnKind << FnDesc
9585       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9586       << FromTy
9587       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9588       << (unsigned) isObjectArgument << I+1;
9589       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9590       return;
9591     }
9592 
9593     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9594       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9595         << (unsigned) FnKind << FnDesc
9596         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9597         << FromTy << FromQs.hasUnaligned() << I+1;
9598       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9599       return;
9600     }
9601 
9602     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9603     assert(CVR && "unexpected qualifiers mismatch");
9604 
9605     if (isObjectArgument) {
9606       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9607         << (unsigned) FnKind << FnDesc
9608         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9609         << FromTy << (CVR - 1);
9610     } else {
9611       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9612         << (unsigned) FnKind << FnDesc
9613         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9614         << FromTy << (CVR - 1) << I+1;
9615     }
9616     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9617     return;
9618   }
9619 
9620   // Special diagnostic for failure to convert an initializer list, since
9621   // telling the user that it has type void is not useful.
9622   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9623     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9624       << (unsigned) FnKind << FnDesc
9625       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9626       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9627     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9628     return;
9629   }
9630 
9631   // Diagnose references or pointers to incomplete types differently,
9632   // since it's far from impossible that the incompleteness triggered
9633   // the failure.
9634   QualType TempFromTy = FromTy.getNonReferenceType();
9635   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9636     TempFromTy = PTy->getPointeeType();
9637   if (TempFromTy->isIncompleteType()) {
9638     // Emit the generic diagnostic and, optionally, add the hints to it.
9639     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9640       << (unsigned) FnKind << FnDesc
9641       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9642       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9643       << (unsigned) (Cand->Fix.Kind);
9644 
9645     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9646     return;
9647   }
9648 
9649   // Diagnose base -> derived pointer conversions.
9650   unsigned BaseToDerivedConversion = 0;
9651   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9652     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9653       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9654                                                FromPtrTy->getPointeeType()) &&
9655           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9656           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9657           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9658                           FromPtrTy->getPointeeType()))
9659         BaseToDerivedConversion = 1;
9660     }
9661   } else if (const ObjCObjectPointerType *FromPtrTy
9662                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9663     if (const ObjCObjectPointerType *ToPtrTy
9664                                         = ToTy->getAs<ObjCObjectPointerType>())
9665       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9666         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9667           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9668                                                 FromPtrTy->getPointeeType()) &&
9669               FromIface->isSuperClassOf(ToIface))
9670             BaseToDerivedConversion = 2;
9671   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9672     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9673         !FromTy->isIncompleteType() &&
9674         !ToRefTy->getPointeeType()->isIncompleteType() &&
9675         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9676       BaseToDerivedConversion = 3;
9677     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9678                ToTy.getNonReferenceType().getCanonicalType() ==
9679                FromTy.getNonReferenceType().getCanonicalType()) {
9680       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9681         << (unsigned) FnKind << FnDesc
9682         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9683         << (unsigned) isObjectArgument << I + 1;
9684       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9685       return;
9686     }
9687   }
9688 
9689   if (BaseToDerivedConversion) {
9690     S.Diag(Fn->getLocation(),
9691            diag::note_ovl_candidate_bad_base_to_derived_conv)
9692       << (unsigned) FnKind << FnDesc
9693       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9694       << (BaseToDerivedConversion - 1)
9695       << FromTy << ToTy << I+1;
9696     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9697     return;
9698   }
9699 
9700   if (isa<ObjCObjectPointerType>(CFromTy) &&
9701       isa<PointerType>(CToTy)) {
9702       Qualifiers FromQs = CFromTy.getQualifiers();
9703       Qualifiers ToQs = CToTy.getQualifiers();
9704       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9705         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9706         << (unsigned) FnKind << FnDesc
9707         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9708         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9709         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9710         return;
9711       }
9712   }
9713 
9714   if (TakingCandidateAddress &&
9715       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9716     return;
9717 
9718   // Emit the generic diagnostic and, optionally, add the hints to it.
9719   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9720   FDiag << (unsigned) FnKind << FnDesc
9721     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9722     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9723     << (unsigned) (Cand->Fix.Kind);
9724 
9725   // If we can fix the conversion, suggest the FixIts.
9726   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9727        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9728     FDiag << *HI;
9729   S.Diag(Fn->getLocation(), FDiag);
9730 
9731   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9732 }
9733 
9734 /// Additional arity mismatch diagnosis specific to a function overload
9735 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9736 /// over a candidate in any candidate set.
9737 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9738                                unsigned NumArgs) {
9739   FunctionDecl *Fn = Cand->Function;
9740   unsigned MinParams = Fn->getMinRequiredArguments();
9741 
9742   // With invalid overloaded operators, it's possible that we think we
9743   // have an arity mismatch when in fact it looks like we have the
9744   // right number of arguments, because only overloaded operators have
9745   // the weird behavior of overloading member and non-member functions.
9746   // Just don't report anything.
9747   if (Fn->isInvalidDecl() &&
9748       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9749     return true;
9750 
9751   if (NumArgs < MinParams) {
9752     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9753            (Cand->FailureKind == ovl_fail_bad_deduction &&
9754             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9755   } else {
9756     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9757            (Cand->FailureKind == ovl_fail_bad_deduction &&
9758             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9759   }
9760 
9761   return false;
9762 }
9763 
9764 /// General arity mismatch diagnosis over a candidate in a candidate set.
9765 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9766                                   unsigned NumFormalArgs) {
9767   assert(isa<FunctionDecl>(D) &&
9768       "The templated declaration should at least be a function"
9769       " when diagnosing bad template argument deduction due to too many"
9770       " or too few arguments");
9771 
9772   FunctionDecl *Fn = cast<FunctionDecl>(D);
9773 
9774   // TODO: treat calls to a missing default constructor as a special case
9775   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9776   unsigned MinParams = Fn->getMinRequiredArguments();
9777 
9778   // at least / at most / exactly
9779   unsigned mode, modeCount;
9780   if (NumFormalArgs < MinParams) {
9781     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9782         FnTy->isTemplateVariadic())
9783       mode = 0; // "at least"
9784     else
9785       mode = 2; // "exactly"
9786     modeCount = MinParams;
9787   } else {
9788     if (MinParams != FnTy->getNumParams())
9789       mode = 1; // "at most"
9790     else
9791       mode = 2; // "exactly"
9792     modeCount = FnTy->getNumParams();
9793   }
9794 
9795   std::string Description;
9796   OverloadCandidateKind FnKind =
9797       ClassifyOverloadCandidate(S, Found, Fn, Description);
9798 
9799   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9800     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9801       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9802       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9803   else
9804     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9805       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9806       << mode << modeCount << NumFormalArgs;
9807   MaybeEmitInheritedConstructorNote(S, Found);
9808 }
9809 
9810 /// Arity mismatch diagnosis specific to a function overload candidate.
9811 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9812                                   unsigned NumFormalArgs) {
9813   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9814     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9815 }
9816 
9817 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9818   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9819     return TD;
9820   llvm_unreachable("Unsupported: Getting the described template declaration"
9821                    " for bad deduction diagnosis");
9822 }
9823 
9824 /// Diagnose a failed template-argument deduction.
9825 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9826                                  DeductionFailureInfo &DeductionFailure,
9827                                  unsigned NumArgs,
9828                                  bool TakingCandidateAddress) {
9829   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9830   NamedDecl *ParamD;
9831   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9832   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9833   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9834   switch (DeductionFailure.Result) {
9835   case Sema::TDK_Success:
9836     llvm_unreachable("TDK_success while diagnosing bad deduction");
9837 
9838   case Sema::TDK_Incomplete: {
9839     assert(ParamD && "no parameter found for incomplete deduction result");
9840     S.Diag(Templated->getLocation(),
9841            diag::note_ovl_candidate_incomplete_deduction)
9842         << ParamD->getDeclName();
9843     MaybeEmitInheritedConstructorNote(S, Found);
9844     return;
9845   }
9846 
9847   case Sema::TDK_Underqualified: {
9848     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9849     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9850 
9851     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9852 
9853     // Param will have been canonicalized, but it should just be a
9854     // qualified version of ParamD, so move the qualifiers to that.
9855     QualifierCollector Qs;
9856     Qs.strip(Param);
9857     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9858     assert(S.Context.hasSameType(Param, NonCanonParam));
9859 
9860     // Arg has also been canonicalized, but there's nothing we can do
9861     // about that.  It also doesn't matter as much, because it won't
9862     // have any template parameters in it (because deduction isn't
9863     // done on dependent types).
9864     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9865 
9866     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9867         << ParamD->getDeclName() << Arg << NonCanonParam;
9868     MaybeEmitInheritedConstructorNote(S, Found);
9869     return;
9870   }
9871 
9872   case Sema::TDK_Inconsistent: {
9873     assert(ParamD && "no parameter found for inconsistent deduction result");
9874     int which = 0;
9875     if (isa<TemplateTypeParmDecl>(ParamD))
9876       which = 0;
9877     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9878       // Deduction might have failed because we deduced arguments of two
9879       // different types for a non-type template parameter.
9880       // FIXME: Use a different TDK value for this.
9881       QualType T1 =
9882           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9883       QualType T2 =
9884           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9885       if (!S.Context.hasSameType(T1, T2)) {
9886         S.Diag(Templated->getLocation(),
9887                diag::note_ovl_candidate_inconsistent_deduction_types)
9888           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9889           << *DeductionFailure.getSecondArg() << T2;
9890         MaybeEmitInheritedConstructorNote(S, Found);
9891         return;
9892       }
9893 
9894       which = 1;
9895     } else {
9896       which = 2;
9897     }
9898 
9899     S.Diag(Templated->getLocation(),
9900            diag::note_ovl_candidate_inconsistent_deduction)
9901         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9902         << *DeductionFailure.getSecondArg();
9903     MaybeEmitInheritedConstructorNote(S, Found);
9904     return;
9905   }
9906 
9907   case Sema::TDK_InvalidExplicitArguments:
9908     assert(ParamD && "no parameter found for invalid explicit arguments");
9909     if (ParamD->getDeclName())
9910       S.Diag(Templated->getLocation(),
9911              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9912           << ParamD->getDeclName();
9913     else {
9914       int index = 0;
9915       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9916         index = TTP->getIndex();
9917       else if (NonTypeTemplateParmDecl *NTTP
9918                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9919         index = NTTP->getIndex();
9920       else
9921         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9922       S.Diag(Templated->getLocation(),
9923              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9924           << (index + 1);
9925     }
9926     MaybeEmitInheritedConstructorNote(S, Found);
9927     return;
9928 
9929   case Sema::TDK_TooManyArguments:
9930   case Sema::TDK_TooFewArguments:
9931     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9932     return;
9933 
9934   case Sema::TDK_InstantiationDepth:
9935     S.Diag(Templated->getLocation(),
9936            diag::note_ovl_candidate_instantiation_depth);
9937     MaybeEmitInheritedConstructorNote(S, Found);
9938     return;
9939 
9940   case Sema::TDK_SubstitutionFailure: {
9941     // Format the template argument list into the argument string.
9942     SmallString<128> TemplateArgString;
9943     if (TemplateArgumentList *Args =
9944             DeductionFailure.getTemplateArgumentList()) {
9945       TemplateArgString = " ";
9946       TemplateArgString += S.getTemplateArgumentBindingsText(
9947           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9948     }
9949 
9950     // If this candidate was disabled by enable_if, say so.
9951     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9952     if (PDiag && PDiag->second.getDiagID() ==
9953           diag::err_typename_nested_not_found_enable_if) {
9954       // FIXME: Use the source range of the condition, and the fully-qualified
9955       //        name of the enable_if template. These are both present in PDiag.
9956       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9957         << "'enable_if'" << TemplateArgString;
9958       return;
9959     }
9960 
9961     // We found a specific requirement that disabled the enable_if.
9962     if (PDiag && PDiag->second.getDiagID() ==
9963         diag::err_typename_nested_not_found_requirement) {
9964       S.Diag(Templated->getLocation(),
9965              diag::note_ovl_candidate_disabled_by_requirement)
9966         << PDiag->second.getStringArg(0) << TemplateArgString;
9967       return;
9968     }
9969 
9970     // Format the SFINAE diagnostic into the argument string.
9971     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9972     //        formatted message in another diagnostic.
9973     SmallString<128> SFINAEArgString;
9974     SourceRange R;
9975     if (PDiag) {
9976       SFINAEArgString = ": ";
9977       R = SourceRange(PDiag->first, PDiag->first);
9978       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9979     }
9980 
9981     S.Diag(Templated->getLocation(),
9982            diag::note_ovl_candidate_substitution_failure)
9983         << TemplateArgString << SFINAEArgString << R;
9984     MaybeEmitInheritedConstructorNote(S, Found);
9985     return;
9986   }
9987 
9988   case Sema::TDK_DeducedMismatch:
9989   case Sema::TDK_DeducedMismatchNested: {
9990     // Format the template argument list into the argument string.
9991     SmallString<128> TemplateArgString;
9992     if (TemplateArgumentList *Args =
9993             DeductionFailure.getTemplateArgumentList()) {
9994       TemplateArgString = " ";
9995       TemplateArgString += S.getTemplateArgumentBindingsText(
9996           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9997     }
9998 
9999     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10000         << (*DeductionFailure.getCallArgIndex() + 1)
10001         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10002         << TemplateArgString
10003         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10004     break;
10005   }
10006 
10007   case Sema::TDK_NonDeducedMismatch: {
10008     // FIXME: Provide a source location to indicate what we couldn't match.
10009     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10010     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10011     if (FirstTA.getKind() == TemplateArgument::Template &&
10012         SecondTA.getKind() == TemplateArgument::Template) {
10013       TemplateName FirstTN = FirstTA.getAsTemplate();
10014       TemplateName SecondTN = SecondTA.getAsTemplate();
10015       if (FirstTN.getKind() == TemplateName::Template &&
10016           SecondTN.getKind() == TemplateName::Template) {
10017         if (FirstTN.getAsTemplateDecl()->getName() ==
10018             SecondTN.getAsTemplateDecl()->getName()) {
10019           // FIXME: This fixes a bad diagnostic where both templates are named
10020           // the same.  This particular case is a bit difficult since:
10021           // 1) It is passed as a string to the diagnostic printer.
10022           // 2) The diagnostic printer only attempts to find a better
10023           //    name for types, not decls.
10024           // Ideally, this should folded into the diagnostic printer.
10025           S.Diag(Templated->getLocation(),
10026                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10027               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10028           return;
10029         }
10030       }
10031     }
10032 
10033     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10034         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10035       return;
10036 
10037     // FIXME: For generic lambda parameters, check if the function is a lambda
10038     // call operator, and if so, emit a prettier and more informative
10039     // diagnostic that mentions 'auto' and lambda in addition to
10040     // (or instead of?) the canonical template type parameters.
10041     S.Diag(Templated->getLocation(),
10042            diag::note_ovl_candidate_non_deduced_mismatch)
10043         << FirstTA << SecondTA;
10044     return;
10045   }
10046   // TODO: diagnose these individually, then kill off
10047   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10048   case Sema::TDK_MiscellaneousDeductionFailure:
10049     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10050     MaybeEmitInheritedConstructorNote(S, Found);
10051     return;
10052   case Sema::TDK_CUDATargetMismatch:
10053     S.Diag(Templated->getLocation(),
10054            diag::note_cuda_ovl_candidate_target_mismatch);
10055     return;
10056   }
10057 }
10058 
10059 /// Diagnose a failed template-argument deduction, for function calls.
10060 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10061                                  unsigned NumArgs,
10062                                  bool TakingCandidateAddress) {
10063   unsigned TDK = Cand->DeductionFailure.Result;
10064   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10065     if (CheckArityMismatch(S, Cand, NumArgs))
10066       return;
10067   }
10068   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10069                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10070 }
10071 
10072 /// CUDA: diagnose an invalid call across targets.
10073 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10074   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10075   FunctionDecl *Callee = Cand->Function;
10076 
10077   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10078                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10079 
10080   std::string FnDesc;
10081   OverloadCandidateKind FnKind =
10082       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10083 
10084   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10085       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10086 
10087   // This could be an implicit constructor for which we could not infer the
10088   // target due to a collsion. Diagnose that case.
10089   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10090   if (Meth != nullptr && Meth->isImplicit()) {
10091     CXXRecordDecl *ParentClass = Meth->getParent();
10092     Sema::CXXSpecialMember CSM;
10093 
10094     switch (FnKind) {
10095     default:
10096       return;
10097     case oc_implicit_default_constructor:
10098       CSM = Sema::CXXDefaultConstructor;
10099       break;
10100     case oc_implicit_copy_constructor:
10101       CSM = Sema::CXXCopyConstructor;
10102       break;
10103     case oc_implicit_move_constructor:
10104       CSM = Sema::CXXMoveConstructor;
10105       break;
10106     case oc_implicit_copy_assignment:
10107       CSM = Sema::CXXCopyAssignment;
10108       break;
10109     case oc_implicit_move_assignment:
10110       CSM = Sema::CXXMoveAssignment;
10111       break;
10112     };
10113 
10114     bool ConstRHS = false;
10115     if (Meth->getNumParams()) {
10116       if (const ReferenceType *RT =
10117               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10118         ConstRHS = RT->getPointeeType().isConstQualified();
10119       }
10120     }
10121 
10122     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10123                                               /* ConstRHS */ ConstRHS,
10124                                               /* Diagnose */ true);
10125   }
10126 }
10127 
10128 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10129   FunctionDecl *Callee = Cand->Function;
10130   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10131 
10132   S.Diag(Callee->getLocation(),
10133          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10134       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10135 }
10136 
10137 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10138   FunctionDecl *Callee = Cand->Function;
10139 
10140   S.Diag(Callee->getLocation(),
10141          diag::note_ovl_candidate_disabled_by_extension);
10142 }
10143 
10144 /// Generates a 'note' diagnostic for an overload candidate.  We've
10145 /// already generated a primary error at the call site.
10146 ///
10147 /// It really does need to be a single diagnostic with its caret
10148 /// pointed at the candidate declaration.  Yes, this creates some
10149 /// major challenges of technical writing.  Yes, this makes pointing
10150 /// out problems with specific arguments quite awkward.  It's still
10151 /// better than generating twenty screens of text for every failed
10152 /// overload.
10153 ///
10154 /// It would be great to be able to express per-candidate problems
10155 /// more richly for those diagnostic clients that cared, but we'd
10156 /// still have to be just as careful with the default diagnostics.
10157 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10158                                   unsigned NumArgs,
10159                                   bool TakingCandidateAddress) {
10160   FunctionDecl *Fn = Cand->Function;
10161 
10162   // Note deleted candidates, but only if they're viable.
10163   if (Cand->Viable) {
10164     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10165       std::string FnDesc;
10166       OverloadCandidateKind FnKind =
10167         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10168 
10169       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10170         << FnKind << FnDesc
10171         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10172       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10173       return;
10174     }
10175 
10176     // We don't really have anything else to say about viable candidates.
10177     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10178     return;
10179   }
10180 
10181   switch (Cand->FailureKind) {
10182   case ovl_fail_too_many_arguments:
10183   case ovl_fail_too_few_arguments:
10184     return DiagnoseArityMismatch(S, Cand, NumArgs);
10185 
10186   case ovl_fail_bad_deduction:
10187     return DiagnoseBadDeduction(S, Cand, NumArgs,
10188                                 TakingCandidateAddress);
10189 
10190   case ovl_fail_illegal_constructor: {
10191     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10192       << (Fn->getPrimaryTemplate() ? 1 : 0);
10193     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10194     return;
10195   }
10196 
10197   case ovl_fail_trivial_conversion:
10198   case ovl_fail_bad_final_conversion:
10199   case ovl_fail_final_conversion_not_exact:
10200     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10201 
10202   case ovl_fail_bad_conversion: {
10203     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10204     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10205       if (Cand->Conversions[I].isBad())
10206         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10207 
10208     // FIXME: this currently happens when we're called from SemaInit
10209     // when user-conversion overload fails.  Figure out how to handle
10210     // those conditions and diagnose them well.
10211     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10212   }
10213 
10214   case ovl_fail_bad_target:
10215     return DiagnoseBadTarget(S, Cand);
10216 
10217   case ovl_fail_enable_if:
10218     return DiagnoseFailedEnableIfAttr(S, Cand);
10219 
10220   case ovl_fail_ext_disabled:
10221     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10222 
10223   case ovl_fail_inhctor_slice:
10224     // It's generally not interesting to note copy/move constructors here.
10225     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10226       return;
10227     S.Diag(Fn->getLocation(),
10228            diag::note_ovl_candidate_inherited_constructor_slice)
10229       << (Fn->getPrimaryTemplate() ? 1 : 0)
10230       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10231     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10232     return;
10233 
10234   case ovl_fail_addr_not_available: {
10235     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10236     (void)Available;
10237     assert(!Available);
10238     break;
10239   }
10240   case ovl_non_default_multiversion_function:
10241     // Do nothing, these should simply be ignored.
10242     break;
10243   }
10244 }
10245 
10246 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10247   // Desugar the type of the surrogate down to a function type,
10248   // retaining as many typedefs as possible while still showing
10249   // the function type (and, therefore, its parameter types).
10250   QualType FnType = Cand->Surrogate->getConversionType();
10251   bool isLValueReference = false;
10252   bool isRValueReference = false;
10253   bool isPointer = false;
10254   if (const LValueReferenceType *FnTypeRef =
10255         FnType->getAs<LValueReferenceType>()) {
10256     FnType = FnTypeRef->getPointeeType();
10257     isLValueReference = true;
10258   } else if (const RValueReferenceType *FnTypeRef =
10259                FnType->getAs<RValueReferenceType>()) {
10260     FnType = FnTypeRef->getPointeeType();
10261     isRValueReference = true;
10262   }
10263   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10264     FnType = FnTypePtr->getPointeeType();
10265     isPointer = true;
10266   }
10267   // Desugar down to a function type.
10268   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10269   // Reconstruct the pointer/reference as appropriate.
10270   if (isPointer) FnType = S.Context.getPointerType(FnType);
10271   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10272   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10273 
10274   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10275     << FnType;
10276 }
10277 
10278 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10279                                          SourceLocation OpLoc,
10280                                          OverloadCandidate *Cand) {
10281   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10282   std::string TypeStr("operator");
10283   TypeStr += Opc;
10284   TypeStr += "(";
10285   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10286   if (Cand->Conversions.size() == 1) {
10287     TypeStr += ")";
10288     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10289   } else {
10290     TypeStr += ", ";
10291     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10292     TypeStr += ")";
10293     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10294   }
10295 }
10296 
10297 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10298                                          OverloadCandidate *Cand) {
10299   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10300     if (ICS.isBad()) break; // all meaningless after first invalid
10301     if (!ICS.isAmbiguous()) continue;
10302 
10303     ICS.DiagnoseAmbiguousConversion(
10304         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10305   }
10306 }
10307 
10308 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10309   if (Cand->Function)
10310     return Cand->Function->getLocation();
10311   if (Cand->IsSurrogate)
10312     return Cand->Surrogate->getLocation();
10313   return SourceLocation();
10314 }
10315 
10316 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10317   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10318   case Sema::TDK_Success:
10319   case Sema::TDK_NonDependentConversionFailure:
10320     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10321 
10322   case Sema::TDK_Invalid:
10323   case Sema::TDK_Incomplete:
10324     return 1;
10325 
10326   case Sema::TDK_Underqualified:
10327   case Sema::TDK_Inconsistent:
10328     return 2;
10329 
10330   case Sema::TDK_SubstitutionFailure:
10331   case Sema::TDK_DeducedMismatch:
10332   case Sema::TDK_DeducedMismatchNested:
10333   case Sema::TDK_NonDeducedMismatch:
10334   case Sema::TDK_MiscellaneousDeductionFailure:
10335   case Sema::TDK_CUDATargetMismatch:
10336     return 3;
10337 
10338   case Sema::TDK_InstantiationDepth:
10339     return 4;
10340 
10341   case Sema::TDK_InvalidExplicitArguments:
10342     return 5;
10343 
10344   case Sema::TDK_TooManyArguments:
10345   case Sema::TDK_TooFewArguments:
10346     return 6;
10347   }
10348   llvm_unreachable("Unhandled deduction result");
10349 }
10350 
10351 namespace {
10352 struct CompareOverloadCandidatesForDisplay {
10353   Sema &S;
10354   SourceLocation Loc;
10355   size_t NumArgs;
10356   OverloadCandidateSet::CandidateSetKind CSK;
10357 
10358   CompareOverloadCandidatesForDisplay(
10359       Sema &S, SourceLocation Loc, size_t NArgs,
10360       OverloadCandidateSet::CandidateSetKind CSK)
10361       : S(S), NumArgs(NArgs), CSK(CSK) {}
10362 
10363   bool operator()(const OverloadCandidate *L,
10364                   const OverloadCandidate *R) {
10365     // Fast-path this check.
10366     if (L == R) return false;
10367 
10368     // Order first by viability.
10369     if (L->Viable) {
10370       if (!R->Viable) return true;
10371 
10372       // TODO: introduce a tri-valued comparison for overload
10373       // candidates.  Would be more worthwhile if we had a sort
10374       // that could exploit it.
10375       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10376         return true;
10377       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10378         return false;
10379     } else if (R->Viable)
10380       return false;
10381 
10382     assert(L->Viable == R->Viable);
10383 
10384     // Criteria by which we can sort non-viable candidates:
10385     if (!L->Viable) {
10386       // 1. Arity mismatches come after other candidates.
10387       if (L->FailureKind == ovl_fail_too_many_arguments ||
10388           L->FailureKind == ovl_fail_too_few_arguments) {
10389         if (R->FailureKind == ovl_fail_too_many_arguments ||
10390             R->FailureKind == ovl_fail_too_few_arguments) {
10391           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10392           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10393           if (LDist == RDist) {
10394             if (L->FailureKind == R->FailureKind)
10395               // Sort non-surrogates before surrogates.
10396               return !L->IsSurrogate && R->IsSurrogate;
10397             // Sort candidates requiring fewer parameters than there were
10398             // arguments given after candidates requiring more parameters
10399             // than there were arguments given.
10400             return L->FailureKind == ovl_fail_too_many_arguments;
10401           }
10402           return LDist < RDist;
10403         }
10404         return false;
10405       }
10406       if (R->FailureKind == ovl_fail_too_many_arguments ||
10407           R->FailureKind == ovl_fail_too_few_arguments)
10408         return true;
10409 
10410       // 2. Bad conversions come first and are ordered by the number
10411       // of bad conversions and quality of good conversions.
10412       if (L->FailureKind == ovl_fail_bad_conversion) {
10413         if (R->FailureKind != ovl_fail_bad_conversion)
10414           return true;
10415 
10416         // The conversion that can be fixed with a smaller number of changes,
10417         // comes first.
10418         unsigned numLFixes = L->Fix.NumConversionsFixed;
10419         unsigned numRFixes = R->Fix.NumConversionsFixed;
10420         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10421         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10422         if (numLFixes != numRFixes) {
10423           return numLFixes < numRFixes;
10424         }
10425 
10426         // If there's any ordering between the defined conversions...
10427         // FIXME: this might not be transitive.
10428         assert(L->Conversions.size() == R->Conversions.size());
10429 
10430         int leftBetter = 0;
10431         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10432         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10433           switch (CompareImplicitConversionSequences(S, Loc,
10434                                                      L->Conversions[I],
10435                                                      R->Conversions[I])) {
10436           case ImplicitConversionSequence::Better:
10437             leftBetter++;
10438             break;
10439 
10440           case ImplicitConversionSequence::Worse:
10441             leftBetter--;
10442             break;
10443 
10444           case ImplicitConversionSequence::Indistinguishable:
10445             break;
10446           }
10447         }
10448         if (leftBetter > 0) return true;
10449         if (leftBetter < 0) return false;
10450 
10451       } else if (R->FailureKind == ovl_fail_bad_conversion)
10452         return false;
10453 
10454       if (L->FailureKind == ovl_fail_bad_deduction) {
10455         if (R->FailureKind != ovl_fail_bad_deduction)
10456           return true;
10457 
10458         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10459           return RankDeductionFailure(L->DeductionFailure)
10460                < RankDeductionFailure(R->DeductionFailure);
10461       } else if (R->FailureKind == ovl_fail_bad_deduction)
10462         return false;
10463 
10464       // TODO: others?
10465     }
10466 
10467     // Sort everything else by location.
10468     SourceLocation LLoc = GetLocationForCandidate(L);
10469     SourceLocation RLoc = GetLocationForCandidate(R);
10470 
10471     // Put candidates without locations (e.g. builtins) at the end.
10472     if (LLoc.isInvalid()) return false;
10473     if (RLoc.isInvalid()) return true;
10474 
10475     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10476   }
10477 };
10478 }
10479 
10480 /// CompleteNonViableCandidate - Normally, overload resolution only
10481 /// computes up to the first bad conversion. Produces the FixIt set if
10482 /// possible.
10483 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10484                                        ArrayRef<Expr *> Args) {
10485   assert(!Cand->Viable);
10486 
10487   // Don't do anything on failures other than bad conversion.
10488   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10489 
10490   // We only want the FixIts if all the arguments can be corrected.
10491   bool Unfixable = false;
10492   // Use a implicit copy initialization to check conversion fixes.
10493   Cand->Fix.setConversionChecker(TryCopyInitialization);
10494 
10495   // Attempt to fix the bad conversion.
10496   unsigned ConvCount = Cand->Conversions.size();
10497   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10498        ++ConvIdx) {
10499     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10500     if (Cand->Conversions[ConvIdx].isInitialized() &&
10501         Cand->Conversions[ConvIdx].isBad()) {
10502       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10503       break;
10504     }
10505   }
10506 
10507   // FIXME: this should probably be preserved from the overload
10508   // operation somehow.
10509   bool SuppressUserConversions = false;
10510 
10511   unsigned ConvIdx = 0;
10512   ArrayRef<QualType> ParamTypes;
10513 
10514   if (Cand->IsSurrogate) {
10515     QualType ConvType
10516       = Cand->Surrogate->getConversionType().getNonReferenceType();
10517     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10518       ConvType = ConvPtrType->getPointeeType();
10519     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10520     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10521     ConvIdx = 1;
10522   } else if (Cand->Function) {
10523     ParamTypes =
10524         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10525     if (isa<CXXMethodDecl>(Cand->Function) &&
10526         !isa<CXXConstructorDecl>(Cand->Function)) {
10527       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10528       ConvIdx = 1;
10529     }
10530   } else {
10531     // Builtin operator.
10532     assert(ConvCount <= 3);
10533     ParamTypes = Cand->BuiltinParamTypes;
10534   }
10535 
10536   // Fill in the rest of the conversions.
10537   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10538     if (Cand->Conversions[ConvIdx].isInitialized()) {
10539       // We've already checked this conversion.
10540     } else if (ArgIdx < ParamTypes.size()) {
10541       if (ParamTypes[ArgIdx]->isDependentType())
10542         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10543             Args[ArgIdx]->getType());
10544       else {
10545         Cand->Conversions[ConvIdx] =
10546             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10547                                   SuppressUserConversions,
10548                                   /*InOverloadResolution=*/true,
10549                                   /*AllowObjCWritebackConversion=*/
10550                                   S.getLangOpts().ObjCAutoRefCount);
10551         // Store the FixIt in the candidate if it exists.
10552         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10553           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10554       }
10555     } else
10556       Cand->Conversions[ConvIdx].setEllipsis();
10557   }
10558 }
10559 
10560 /// When overload resolution fails, prints diagnostic messages containing the
10561 /// candidates in the candidate set.
10562 void OverloadCandidateSet::NoteCandidates(
10563     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10564     StringRef Opc, SourceLocation OpLoc,
10565     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10566   // Sort the candidates by viability and position.  Sorting directly would
10567   // be prohibitive, so we make a set of pointers and sort those.
10568   SmallVector<OverloadCandidate*, 32> Cands;
10569   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10570   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10571     if (!Filter(*Cand))
10572       continue;
10573     if (Cand->Viable)
10574       Cands.push_back(Cand);
10575     else if (OCD == OCD_AllCandidates) {
10576       CompleteNonViableCandidate(S, Cand, Args);
10577       if (Cand->Function || Cand->IsSurrogate)
10578         Cands.push_back(Cand);
10579       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10580       // want to list every possible builtin candidate.
10581     }
10582   }
10583 
10584   std::stable_sort(Cands.begin(), Cands.end(),
10585             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10586 
10587   bool ReportedAmbiguousConversions = false;
10588 
10589   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10590   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10591   unsigned CandsShown = 0;
10592   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10593     OverloadCandidate *Cand = *I;
10594 
10595     // Set an arbitrary limit on the number of candidate functions we'll spam
10596     // the user with.  FIXME: This limit should depend on details of the
10597     // candidate list.
10598     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10599       break;
10600     }
10601     ++CandsShown;
10602 
10603     if (Cand->Function)
10604       NoteFunctionCandidate(S, Cand, Args.size(),
10605                             /*TakingCandidateAddress=*/false);
10606     else if (Cand->IsSurrogate)
10607       NoteSurrogateCandidate(S, Cand);
10608     else {
10609       assert(Cand->Viable &&
10610              "Non-viable built-in candidates are not added to Cands.");
10611       // Generally we only see ambiguities including viable builtin
10612       // operators if overload resolution got screwed up by an
10613       // ambiguous user-defined conversion.
10614       //
10615       // FIXME: It's quite possible for different conversions to see
10616       // different ambiguities, though.
10617       if (!ReportedAmbiguousConversions) {
10618         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10619         ReportedAmbiguousConversions = true;
10620       }
10621 
10622       // If this is a viable builtin, print it.
10623       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10624     }
10625   }
10626 
10627   if (I != E)
10628     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10629 }
10630 
10631 static SourceLocation
10632 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10633   return Cand->Specialization ? Cand->Specialization->getLocation()
10634                               : SourceLocation();
10635 }
10636 
10637 namespace {
10638 struct CompareTemplateSpecCandidatesForDisplay {
10639   Sema &S;
10640   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10641 
10642   bool operator()(const TemplateSpecCandidate *L,
10643                   const TemplateSpecCandidate *R) {
10644     // Fast-path this check.
10645     if (L == R)
10646       return false;
10647 
10648     // Assuming that both candidates are not matches...
10649 
10650     // Sort by the ranking of deduction failures.
10651     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10652       return RankDeductionFailure(L->DeductionFailure) <
10653              RankDeductionFailure(R->DeductionFailure);
10654 
10655     // Sort everything else by location.
10656     SourceLocation LLoc = GetLocationForCandidate(L);
10657     SourceLocation RLoc = GetLocationForCandidate(R);
10658 
10659     // Put candidates without locations (e.g. builtins) at the end.
10660     if (LLoc.isInvalid())
10661       return false;
10662     if (RLoc.isInvalid())
10663       return true;
10664 
10665     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10666   }
10667 };
10668 }
10669 
10670 /// Diagnose a template argument deduction failure.
10671 /// We are treating these failures as overload failures due to bad
10672 /// deductions.
10673 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10674                                                  bool ForTakingAddress) {
10675   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10676                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10677 }
10678 
10679 void TemplateSpecCandidateSet::destroyCandidates() {
10680   for (iterator i = begin(), e = end(); i != e; ++i) {
10681     i->DeductionFailure.Destroy();
10682   }
10683 }
10684 
10685 void TemplateSpecCandidateSet::clear() {
10686   destroyCandidates();
10687   Candidates.clear();
10688 }
10689 
10690 /// NoteCandidates - When no template specialization match is found, prints
10691 /// diagnostic messages containing the non-matching specializations that form
10692 /// the candidate set.
10693 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10694 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10695 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10696   // Sort the candidates by position (assuming no candidate is a match).
10697   // Sorting directly would be prohibitive, so we make a set of pointers
10698   // and sort those.
10699   SmallVector<TemplateSpecCandidate *, 32> Cands;
10700   Cands.reserve(size());
10701   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10702     if (Cand->Specialization)
10703       Cands.push_back(Cand);
10704     // Otherwise, this is a non-matching builtin candidate.  We do not,
10705     // in general, want to list every possible builtin candidate.
10706   }
10707 
10708   llvm::sort(Cands.begin(), Cands.end(),
10709              CompareTemplateSpecCandidatesForDisplay(S));
10710 
10711   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10712   // for generalization purposes (?).
10713   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10714 
10715   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10716   unsigned CandsShown = 0;
10717   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10718     TemplateSpecCandidate *Cand = *I;
10719 
10720     // Set an arbitrary limit on the number of candidates we'll spam
10721     // the user with.  FIXME: This limit should depend on details of the
10722     // candidate list.
10723     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10724       break;
10725     ++CandsShown;
10726 
10727     assert(Cand->Specialization &&
10728            "Non-matching built-in candidates are not added to Cands.");
10729     Cand->NoteDeductionFailure(S, ForTakingAddress);
10730   }
10731 
10732   if (I != E)
10733     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10734 }
10735 
10736 // [PossiblyAFunctionType]  -->   [Return]
10737 // NonFunctionType --> NonFunctionType
10738 // R (A) --> R(A)
10739 // R (*)(A) --> R (A)
10740 // R (&)(A) --> R (A)
10741 // R (S::*)(A) --> R (A)
10742 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10743   QualType Ret = PossiblyAFunctionType;
10744   if (const PointerType *ToTypePtr =
10745     PossiblyAFunctionType->getAs<PointerType>())
10746     Ret = ToTypePtr->getPointeeType();
10747   else if (const ReferenceType *ToTypeRef =
10748     PossiblyAFunctionType->getAs<ReferenceType>())
10749     Ret = ToTypeRef->getPointeeType();
10750   else if (const MemberPointerType *MemTypePtr =
10751     PossiblyAFunctionType->getAs<MemberPointerType>())
10752     Ret = MemTypePtr->getPointeeType();
10753   Ret =
10754     Context.getCanonicalType(Ret).getUnqualifiedType();
10755   return Ret;
10756 }
10757 
10758 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10759                                  bool Complain = true) {
10760   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10761       S.DeduceReturnType(FD, Loc, Complain))
10762     return true;
10763 
10764   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10765   if (S.getLangOpts().CPlusPlus17 &&
10766       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10767       !S.ResolveExceptionSpec(Loc, FPT))
10768     return true;
10769 
10770   return false;
10771 }
10772 
10773 namespace {
10774 // A helper class to help with address of function resolution
10775 // - allows us to avoid passing around all those ugly parameters
10776 class AddressOfFunctionResolver {
10777   Sema& S;
10778   Expr* SourceExpr;
10779   const QualType& TargetType;
10780   QualType TargetFunctionType; // Extracted function type from target type
10781 
10782   bool Complain;
10783   //DeclAccessPair& ResultFunctionAccessPair;
10784   ASTContext& Context;
10785 
10786   bool TargetTypeIsNonStaticMemberFunction;
10787   bool FoundNonTemplateFunction;
10788   bool StaticMemberFunctionFromBoundPointer;
10789   bool HasComplained;
10790 
10791   OverloadExpr::FindResult OvlExprInfo;
10792   OverloadExpr *OvlExpr;
10793   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10794   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10795   TemplateSpecCandidateSet FailedCandidates;
10796 
10797 public:
10798   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10799                             const QualType &TargetType, bool Complain)
10800       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10801         Complain(Complain), Context(S.getASTContext()),
10802         TargetTypeIsNonStaticMemberFunction(
10803             !!TargetType->getAs<MemberPointerType>()),
10804         FoundNonTemplateFunction(false),
10805         StaticMemberFunctionFromBoundPointer(false),
10806         HasComplained(false),
10807         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10808         OvlExpr(OvlExprInfo.Expression),
10809         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10810     ExtractUnqualifiedFunctionTypeFromTargetType();
10811 
10812     if (TargetFunctionType->isFunctionType()) {
10813       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10814         if (!UME->isImplicitAccess() &&
10815             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10816           StaticMemberFunctionFromBoundPointer = true;
10817     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10818       DeclAccessPair dap;
10819       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10820               OvlExpr, false, &dap)) {
10821         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10822           if (!Method->isStatic()) {
10823             // If the target type is a non-function type and the function found
10824             // is a non-static member function, pretend as if that was the
10825             // target, it's the only possible type to end up with.
10826             TargetTypeIsNonStaticMemberFunction = true;
10827 
10828             // And skip adding the function if its not in the proper form.
10829             // We'll diagnose this due to an empty set of functions.
10830             if (!OvlExprInfo.HasFormOfMemberPointer)
10831               return;
10832           }
10833 
10834         Matches.push_back(std::make_pair(dap, Fn));
10835       }
10836       return;
10837     }
10838 
10839     if (OvlExpr->hasExplicitTemplateArgs())
10840       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10841 
10842     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10843       // C++ [over.over]p4:
10844       //   If more than one function is selected, [...]
10845       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10846         if (FoundNonTemplateFunction)
10847           EliminateAllTemplateMatches();
10848         else
10849           EliminateAllExceptMostSpecializedTemplate();
10850       }
10851     }
10852 
10853     if (S.getLangOpts().CUDA && Matches.size() > 1)
10854       EliminateSuboptimalCudaMatches();
10855   }
10856 
10857   bool hasComplained() const { return HasComplained; }
10858 
10859 private:
10860   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10861     QualType Discard;
10862     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10863            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10864   }
10865 
10866   /// \return true if A is considered a better overload candidate for the
10867   /// desired type than B.
10868   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10869     // If A doesn't have exactly the correct type, we don't want to classify it
10870     // as "better" than anything else. This way, the user is required to
10871     // disambiguate for us if there are multiple candidates and no exact match.
10872     return candidateHasExactlyCorrectType(A) &&
10873            (!candidateHasExactlyCorrectType(B) ||
10874             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10875   }
10876 
10877   /// \return true if we were able to eliminate all but one overload candidate,
10878   /// false otherwise.
10879   bool eliminiateSuboptimalOverloadCandidates() {
10880     // Same algorithm as overload resolution -- one pass to pick the "best",
10881     // another pass to be sure that nothing is better than the best.
10882     auto Best = Matches.begin();
10883     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10884       if (isBetterCandidate(I->second, Best->second))
10885         Best = I;
10886 
10887     const FunctionDecl *BestFn = Best->second;
10888     auto IsBestOrInferiorToBest = [this, BestFn](
10889         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10890       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10891     };
10892 
10893     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10894     // option, so we can potentially give the user a better error
10895     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10896       return false;
10897     Matches[0] = *Best;
10898     Matches.resize(1);
10899     return true;
10900   }
10901 
10902   bool isTargetTypeAFunction() const {
10903     return TargetFunctionType->isFunctionType();
10904   }
10905 
10906   // [ToType]     [Return]
10907 
10908   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10909   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10910   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10911   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10912     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10913   }
10914 
10915   // return true if any matching specializations were found
10916   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10917                                    const DeclAccessPair& CurAccessFunPair) {
10918     if (CXXMethodDecl *Method
10919               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10920       // Skip non-static function templates when converting to pointer, and
10921       // static when converting to member pointer.
10922       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10923         return false;
10924     }
10925     else if (TargetTypeIsNonStaticMemberFunction)
10926       return false;
10927 
10928     // C++ [over.over]p2:
10929     //   If the name is a function template, template argument deduction is
10930     //   done (14.8.2.2), and if the argument deduction succeeds, the
10931     //   resulting template argument list is used to generate a single
10932     //   function template specialization, which is added to the set of
10933     //   overloaded functions considered.
10934     FunctionDecl *Specialization = nullptr;
10935     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10936     if (Sema::TemplateDeductionResult Result
10937           = S.DeduceTemplateArguments(FunctionTemplate,
10938                                       &OvlExplicitTemplateArgs,
10939                                       TargetFunctionType, Specialization,
10940                                       Info, /*IsAddressOfFunction*/true)) {
10941       // Make a note of the failed deduction for diagnostics.
10942       FailedCandidates.addCandidate()
10943           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10944                MakeDeductionFailureInfo(Context, Result, Info));
10945       return false;
10946     }
10947 
10948     // Template argument deduction ensures that we have an exact match or
10949     // compatible pointer-to-function arguments that would be adjusted by ICS.
10950     // This function template specicalization works.
10951     assert(S.isSameOrCompatibleFunctionType(
10952               Context.getCanonicalType(Specialization->getType()),
10953               Context.getCanonicalType(TargetFunctionType)));
10954 
10955     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10956       return false;
10957 
10958     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10959     return true;
10960   }
10961 
10962   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10963                                       const DeclAccessPair& CurAccessFunPair) {
10964     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10965       // Skip non-static functions when converting to pointer, and static
10966       // when converting to member pointer.
10967       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10968         return false;
10969     }
10970     else if (TargetTypeIsNonStaticMemberFunction)
10971       return false;
10972 
10973     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10974       if (S.getLangOpts().CUDA)
10975         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10976           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10977             return false;
10978       if (FunDecl->isMultiVersion()) {
10979         const auto *TA = FunDecl->getAttr<TargetAttr>();
10980         assert(TA && "Multiversioned functions require a target attribute");
10981         if (!TA->isDefaultVersion())
10982           return false;
10983       }
10984 
10985       // If any candidate has a placeholder return type, trigger its deduction
10986       // now.
10987       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10988                                Complain)) {
10989         HasComplained |= Complain;
10990         return false;
10991       }
10992 
10993       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10994         return false;
10995 
10996       // If we're in C, we need to support types that aren't exactly identical.
10997       if (!S.getLangOpts().CPlusPlus ||
10998           candidateHasExactlyCorrectType(FunDecl)) {
10999         Matches.push_back(std::make_pair(
11000             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11001         FoundNonTemplateFunction = true;
11002         return true;
11003       }
11004     }
11005 
11006     return false;
11007   }
11008 
11009   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11010     bool Ret = false;
11011 
11012     // If the overload expression doesn't have the form of a pointer to
11013     // member, don't try to convert it to a pointer-to-member type.
11014     if (IsInvalidFormOfPointerToMemberFunction())
11015       return false;
11016 
11017     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11018                                E = OvlExpr->decls_end();
11019          I != E; ++I) {
11020       // Look through any using declarations to find the underlying function.
11021       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11022 
11023       // C++ [over.over]p3:
11024       //   Non-member functions and static member functions match
11025       //   targets of type "pointer-to-function" or "reference-to-function."
11026       //   Nonstatic member functions match targets of
11027       //   type "pointer-to-member-function."
11028       // Note that according to DR 247, the containing class does not matter.
11029       if (FunctionTemplateDecl *FunctionTemplate
11030                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11031         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11032           Ret = true;
11033       }
11034       // If we have explicit template arguments supplied, skip non-templates.
11035       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11036                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11037         Ret = true;
11038     }
11039     assert(Ret || Matches.empty());
11040     return Ret;
11041   }
11042 
11043   void EliminateAllExceptMostSpecializedTemplate() {
11044     //   [...] and any given function template specialization F1 is
11045     //   eliminated if the set contains a second function template
11046     //   specialization whose function template is more specialized
11047     //   than the function template of F1 according to the partial
11048     //   ordering rules of 14.5.5.2.
11049 
11050     // The algorithm specified above is quadratic. We instead use a
11051     // two-pass algorithm (similar to the one used to identify the
11052     // best viable function in an overload set) that identifies the
11053     // best function template (if it exists).
11054 
11055     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11056     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11057       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11058 
11059     // TODO: It looks like FailedCandidates does not serve much purpose
11060     // here, since the no_viable diagnostic has index 0.
11061     UnresolvedSetIterator Result = S.getMostSpecialized(
11062         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11063         SourceExpr->getLocStart(), S.PDiag(),
11064         S.PDiag(diag::err_addr_ovl_ambiguous)
11065           << Matches[0].second->getDeclName(),
11066         S.PDiag(diag::note_ovl_candidate)
11067           << (unsigned)oc_function_template,
11068         Complain, TargetFunctionType);
11069 
11070     if (Result != MatchesCopy.end()) {
11071       // Make it the first and only element
11072       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11073       Matches[0].second = cast<FunctionDecl>(*Result);
11074       Matches.resize(1);
11075     } else
11076       HasComplained |= Complain;
11077   }
11078 
11079   void EliminateAllTemplateMatches() {
11080     //   [...] any function template specializations in the set are
11081     //   eliminated if the set also contains a non-template function, [...]
11082     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11083       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11084         ++I;
11085       else {
11086         Matches[I] = Matches[--N];
11087         Matches.resize(N);
11088       }
11089     }
11090   }
11091 
11092   void EliminateSuboptimalCudaMatches() {
11093     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11094   }
11095 
11096 public:
11097   void ComplainNoMatchesFound() const {
11098     assert(Matches.empty());
11099     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11100         << OvlExpr->getName() << TargetFunctionType
11101         << OvlExpr->getSourceRange();
11102     if (FailedCandidates.empty())
11103       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11104                                   /*TakingAddress=*/true);
11105     else {
11106       // We have some deduction failure messages. Use them to diagnose
11107       // the function templates, and diagnose the non-template candidates
11108       // normally.
11109       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11110                                  IEnd = OvlExpr->decls_end();
11111            I != IEnd; ++I)
11112         if (FunctionDecl *Fun =
11113                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11114           if (!functionHasPassObjectSizeParams(Fun))
11115             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11116                                     /*TakingAddress=*/true);
11117       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11118     }
11119   }
11120 
11121   bool IsInvalidFormOfPointerToMemberFunction() const {
11122     return TargetTypeIsNonStaticMemberFunction &&
11123       !OvlExprInfo.HasFormOfMemberPointer;
11124   }
11125 
11126   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11127       // TODO: Should we condition this on whether any functions might
11128       // have matched, or is it more appropriate to do that in callers?
11129       // TODO: a fixit wouldn't hurt.
11130       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11131         << TargetType << OvlExpr->getSourceRange();
11132   }
11133 
11134   bool IsStaticMemberFunctionFromBoundPointer() const {
11135     return StaticMemberFunctionFromBoundPointer;
11136   }
11137 
11138   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11139     S.Diag(OvlExpr->getLocStart(),
11140            diag::err_invalid_form_pointer_member_function)
11141       << OvlExpr->getSourceRange();
11142   }
11143 
11144   void ComplainOfInvalidConversion() const {
11145     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11146       << OvlExpr->getName() << TargetType;
11147   }
11148 
11149   void ComplainMultipleMatchesFound() const {
11150     assert(Matches.size() > 1);
11151     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11152       << OvlExpr->getName()
11153       << OvlExpr->getSourceRange();
11154     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11155                                 /*TakingAddress=*/true);
11156   }
11157 
11158   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11159 
11160   int getNumMatches() const { return Matches.size(); }
11161 
11162   FunctionDecl* getMatchingFunctionDecl() const {
11163     if (Matches.size() != 1) return nullptr;
11164     return Matches[0].second;
11165   }
11166 
11167   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11168     if (Matches.size() != 1) return nullptr;
11169     return &Matches[0].first;
11170   }
11171 };
11172 }
11173 
11174 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11175 /// an overloaded function (C++ [over.over]), where @p From is an
11176 /// expression with overloaded function type and @p ToType is the type
11177 /// we're trying to resolve to. For example:
11178 ///
11179 /// @code
11180 /// int f(double);
11181 /// int f(int);
11182 ///
11183 /// int (*pfd)(double) = f; // selects f(double)
11184 /// @endcode
11185 ///
11186 /// This routine returns the resulting FunctionDecl if it could be
11187 /// resolved, and NULL otherwise. When @p Complain is true, this
11188 /// routine will emit diagnostics if there is an error.
11189 FunctionDecl *
11190 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11191                                          QualType TargetType,
11192                                          bool Complain,
11193                                          DeclAccessPair &FoundResult,
11194                                          bool *pHadMultipleCandidates) {
11195   assert(AddressOfExpr->getType() == Context.OverloadTy);
11196 
11197   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11198                                      Complain);
11199   int NumMatches = Resolver.getNumMatches();
11200   FunctionDecl *Fn = nullptr;
11201   bool ShouldComplain = Complain && !Resolver.hasComplained();
11202   if (NumMatches == 0 && ShouldComplain) {
11203     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11204       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11205     else
11206       Resolver.ComplainNoMatchesFound();
11207   }
11208   else if (NumMatches > 1 && ShouldComplain)
11209     Resolver.ComplainMultipleMatchesFound();
11210   else if (NumMatches == 1) {
11211     Fn = Resolver.getMatchingFunctionDecl();
11212     assert(Fn);
11213     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11214       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11215     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11216     if (Complain) {
11217       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11218         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11219       else
11220         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11221     }
11222   }
11223 
11224   if (pHadMultipleCandidates)
11225     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11226   return Fn;
11227 }
11228 
11229 /// \brief Given an expression that refers to an overloaded function, try to
11230 /// resolve that function to a single function that can have its address taken.
11231 /// This will modify `Pair` iff it returns non-null.
11232 ///
11233 /// This routine can only realistically succeed if all but one candidates in the
11234 /// overload set for SrcExpr cannot have their addresses taken.
11235 FunctionDecl *
11236 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11237                                                   DeclAccessPair &Pair) {
11238   OverloadExpr::FindResult R = OverloadExpr::find(E);
11239   OverloadExpr *Ovl = R.Expression;
11240   FunctionDecl *Result = nullptr;
11241   DeclAccessPair DAP;
11242   // Don't use the AddressOfResolver because we're specifically looking for
11243   // cases where we have one overload candidate that lacks
11244   // enable_if/pass_object_size/...
11245   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11246     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11247     if (!FD)
11248       return nullptr;
11249 
11250     if (!checkAddressOfFunctionIsAvailable(FD))
11251       continue;
11252 
11253     // We have more than one result; quit.
11254     if (Result)
11255       return nullptr;
11256     DAP = I.getPair();
11257     Result = FD;
11258   }
11259 
11260   if (Result)
11261     Pair = DAP;
11262   return Result;
11263 }
11264 
11265 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11266 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11267 /// will perform access checks, diagnose the use of the resultant decl, and, if
11268 /// requested, potentially perform a function-to-pointer decay.
11269 ///
11270 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11271 /// Otherwise, returns true. This may emit diagnostics and return true.
11272 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11273     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11274   Expr *E = SrcExpr.get();
11275   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11276 
11277   DeclAccessPair DAP;
11278   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11279   if (!Found)
11280     return false;
11281 
11282   // Emitting multiple diagnostics for a function that is both inaccessible and
11283   // unavailable is consistent with our behavior elsewhere. So, always check
11284   // for both.
11285   DiagnoseUseOfDecl(Found, E->getExprLoc());
11286   CheckAddressOfMemberAccess(E, DAP);
11287   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11288   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11289     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11290   else
11291     SrcExpr = Fixed;
11292   return true;
11293 }
11294 
11295 /// \brief Given an expression that refers to an overloaded function, try to
11296 /// resolve that overloaded function expression down to a single function.
11297 ///
11298 /// This routine can only resolve template-ids that refer to a single function
11299 /// template, where that template-id refers to a single template whose template
11300 /// arguments are either provided by the template-id or have defaults,
11301 /// as described in C++0x [temp.arg.explicit]p3.
11302 ///
11303 /// If no template-ids are found, no diagnostics are emitted and NULL is
11304 /// returned.
11305 FunctionDecl *
11306 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11307                                                   bool Complain,
11308                                                   DeclAccessPair *FoundResult) {
11309   // C++ [over.over]p1:
11310   //   [...] [Note: any redundant set of parentheses surrounding the
11311   //   overloaded function name is ignored (5.1). ]
11312   // C++ [over.over]p1:
11313   //   [...] The overloaded function name can be preceded by the &
11314   //   operator.
11315 
11316   // If we didn't actually find any template-ids, we're done.
11317   if (!ovl->hasExplicitTemplateArgs())
11318     return nullptr;
11319 
11320   TemplateArgumentListInfo ExplicitTemplateArgs;
11321   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11322   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11323 
11324   // Look through all of the overloaded functions, searching for one
11325   // whose type matches exactly.
11326   FunctionDecl *Matched = nullptr;
11327   for (UnresolvedSetIterator I = ovl->decls_begin(),
11328          E = ovl->decls_end(); I != E; ++I) {
11329     // C++0x [temp.arg.explicit]p3:
11330     //   [...] In contexts where deduction is done and fails, or in contexts
11331     //   where deduction is not done, if a template argument list is
11332     //   specified and it, along with any default template arguments,
11333     //   identifies a single function template specialization, then the
11334     //   template-id is an lvalue for the function template specialization.
11335     FunctionTemplateDecl *FunctionTemplate
11336       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11337 
11338     // C++ [over.over]p2:
11339     //   If the name is a function template, template argument deduction is
11340     //   done (14.8.2.2), and if the argument deduction succeeds, the
11341     //   resulting template argument list is used to generate a single
11342     //   function template specialization, which is added to the set of
11343     //   overloaded functions considered.
11344     FunctionDecl *Specialization = nullptr;
11345     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11346     if (TemplateDeductionResult Result
11347           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11348                                     Specialization, Info,
11349                                     /*IsAddressOfFunction*/true)) {
11350       // Make a note of the failed deduction for diagnostics.
11351       // TODO: Actually use the failed-deduction info?
11352       FailedCandidates.addCandidate()
11353           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11354                MakeDeductionFailureInfo(Context, Result, Info));
11355       continue;
11356     }
11357 
11358     assert(Specialization && "no specialization and no error?");
11359 
11360     // Multiple matches; we can't resolve to a single declaration.
11361     if (Matched) {
11362       if (Complain) {
11363         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11364           << ovl->getName();
11365         NoteAllOverloadCandidates(ovl);
11366       }
11367       return nullptr;
11368     }
11369 
11370     Matched = Specialization;
11371     if (FoundResult) *FoundResult = I.getPair();
11372   }
11373 
11374   if (Matched &&
11375       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11376     return nullptr;
11377 
11378   return Matched;
11379 }
11380 
11381 // Resolve and fix an overloaded expression that can be resolved
11382 // because it identifies a single function template specialization.
11383 //
11384 // Last three arguments should only be supplied if Complain = true
11385 //
11386 // Return true if it was logically possible to so resolve the
11387 // expression, regardless of whether or not it succeeded.  Always
11388 // returns true if 'complain' is set.
11389 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11390                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11391                       bool complain, SourceRange OpRangeForComplaining,
11392                                            QualType DestTypeForComplaining,
11393                                             unsigned DiagIDForComplaining) {
11394   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11395 
11396   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11397 
11398   DeclAccessPair found;
11399   ExprResult SingleFunctionExpression;
11400   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11401                            ovl.Expression, /*complain*/ false, &found)) {
11402     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11403       SrcExpr = ExprError();
11404       return true;
11405     }
11406 
11407     // It is only correct to resolve to an instance method if we're
11408     // resolving a form that's permitted to be a pointer to member.
11409     // Otherwise we'll end up making a bound member expression, which
11410     // is illegal in all the contexts we resolve like this.
11411     if (!ovl.HasFormOfMemberPointer &&
11412         isa<CXXMethodDecl>(fn) &&
11413         cast<CXXMethodDecl>(fn)->isInstance()) {
11414       if (!complain) return false;
11415 
11416       Diag(ovl.Expression->getExprLoc(),
11417            diag::err_bound_member_function)
11418         << 0 << ovl.Expression->getSourceRange();
11419 
11420       // TODO: I believe we only end up here if there's a mix of
11421       // static and non-static candidates (otherwise the expression
11422       // would have 'bound member' type, not 'overload' type).
11423       // Ideally we would note which candidate was chosen and why
11424       // the static candidates were rejected.
11425       SrcExpr = ExprError();
11426       return true;
11427     }
11428 
11429     // Fix the expression to refer to 'fn'.
11430     SingleFunctionExpression =
11431         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11432 
11433     // If desired, do function-to-pointer decay.
11434     if (doFunctionPointerConverion) {
11435       SingleFunctionExpression =
11436         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11437       if (SingleFunctionExpression.isInvalid()) {
11438         SrcExpr = ExprError();
11439         return true;
11440       }
11441     }
11442   }
11443 
11444   if (!SingleFunctionExpression.isUsable()) {
11445     if (complain) {
11446       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11447         << ovl.Expression->getName()
11448         << DestTypeForComplaining
11449         << OpRangeForComplaining
11450         << ovl.Expression->getQualifierLoc().getSourceRange();
11451       NoteAllOverloadCandidates(SrcExpr.get());
11452 
11453       SrcExpr = ExprError();
11454       return true;
11455     }
11456 
11457     return false;
11458   }
11459 
11460   SrcExpr = SingleFunctionExpression;
11461   return true;
11462 }
11463 
11464 /// \brief Add a single candidate to the overload set.
11465 static void AddOverloadedCallCandidate(Sema &S,
11466                                        DeclAccessPair FoundDecl,
11467                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11468                                        ArrayRef<Expr *> Args,
11469                                        OverloadCandidateSet &CandidateSet,
11470                                        bool PartialOverloading,
11471                                        bool KnownValid) {
11472   NamedDecl *Callee = FoundDecl.getDecl();
11473   if (isa<UsingShadowDecl>(Callee))
11474     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11475 
11476   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11477     if (ExplicitTemplateArgs) {
11478       assert(!KnownValid && "Explicit template arguments?");
11479       return;
11480     }
11481     // Prevent ill-formed function decls to be added as overload candidates.
11482     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11483       return;
11484 
11485     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11486                            /*SuppressUsedConversions=*/false,
11487                            PartialOverloading);
11488     return;
11489   }
11490 
11491   if (FunctionTemplateDecl *FuncTemplate
11492       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11493     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11494                                    ExplicitTemplateArgs, Args, CandidateSet,
11495                                    /*SuppressUsedConversions=*/false,
11496                                    PartialOverloading);
11497     return;
11498   }
11499 
11500   assert(!KnownValid && "unhandled case in overloaded call candidate");
11501 }
11502 
11503 /// \brief Add the overload candidates named by callee and/or found by argument
11504 /// dependent lookup to the given overload set.
11505 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11506                                        ArrayRef<Expr *> Args,
11507                                        OverloadCandidateSet &CandidateSet,
11508                                        bool PartialOverloading) {
11509 
11510 #ifndef NDEBUG
11511   // Verify that ArgumentDependentLookup is consistent with the rules
11512   // in C++0x [basic.lookup.argdep]p3:
11513   //
11514   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11515   //   and let Y be the lookup set produced by argument dependent
11516   //   lookup (defined as follows). If X contains
11517   //
11518   //     -- a declaration of a class member, or
11519   //
11520   //     -- a block-scope function declaration that is not a
11521   //        using-declaration, or
11522   //
11523   //     -- a declaration that is neither a function or a function
11524   //        template
11525   //
11526   //   then Y is empty.
11527 
11528   if (ULE->requiresADL()) {
11529     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11530            E = ULE->decls_end(); I != E; ++I) {
11531       assert(!(*I)->getDeclContext()->isRecord());
11532       assert(isa<UsingShadowDecl>(*I) ||
11533              !(*I)->getDeclContext()->isFunctionOrMethod());
11534       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11535     }
11536   }
11537 #endif
11538 
11539   // It would be nice to avoid this copy.
11540   TemplateArgumentListInfo TABuffer;
11541   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11542   if (ULE->hasExplicitTemplateArgs()) {
11543     ULE->copyTemplateArgumentsInto(TABuffer);
11544     ExplicitTemplateArgs = &TABuffer;
11545   }
11546 
11547   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11548          E = ULE->decls_end(); I != E; ++I)
11549     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11550                                CandidateSet, PartialOverloading,
11551                                /*KnownValid*/ true);
11552 
11553   if (ULE->requiresADL())
11554     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11555                                          Args, ExplicitTemplateArgs,
11556                                          CandidateSet, PartialOverloading);
11557 }
11558 
11559 /// Determine whether a declaration with the specified name could be moved into
11560 /// a different namespace.
11561 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11562   switch (Name.getCXXOverloadedOperator()) {
11563   case OO_New: case OO_Array_New:
11564   case OO_Delete: case OO_Array_Delete:
11565     return false;
11566 
11567   default:
11568     return true;
11569   }
11570 }
11571 
11572 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11573 /// template, where the non-dependent name was declared after the template
11574 /// was defined. This is common in code written for a compilers which do not
11575 /// correctly implement two-stage name lookup.
11576 ///
11577 /// Returns true if a viable candidate was found and a diagnostic was issued.
11578 static bool
11579 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11580                        const CXXScopeSpec &SS, LookupResult &R,
11581                        OverloadCandidateSet::CandidateSetKind CSK,
11582                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11583                        ArrayRef<Expr *> Args,
11584                        bool *DoDiagnoseEmptyLookup = nullptr) {
11585   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11586     return false;
11587 
11588   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11589     if (DC->isTransparentContext())
11590       continue;
11591 
11592     SemaRef.LookupQualifiedName(R, DC);
11593 
11594     if (!R.empty()) {
11595       R.suppressDiagnostics();
11596 
11597       if (isa<CXXRecordDecl>(DC)) {
11598         // Don't diagnose names we find in classes; we get much better
11599         // diagnostics for these from DiagnoseEmptyLookup.
11600         R.clear();
11601         if (DoDiagnoseEmptyLookup)
11602           *DoDiagnoseEmptyLookup = true;
11603         return false;
11604       }
11605 
11606       OverloadCandidateSet Candidates(FnLoc, CSK);
11607       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11608         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11609                                    ExplicitTemplateArgs, Args,
11610                                    Candidates, false, /*KnownValid*/ false);
11611 
11612       OverloadCandidateSet::iterator Best;
11613       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11614         // No viable functions. Don't bother the user with notes for functions
11615         // which don't work and shouldn't be found anyway.
11616         R.clear();
11617         return false;
11618       }
11619 
11620       // Find the namespaces where ADL would have looked, and suggest
11621       // declaring the function there instead.
11622       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11623       Sema::AssociatedClassSet AssociatedClasses;
11624       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11625                                                  AssociatedNamespaces,
11626                                                  AssociatedClasses);
11627       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11628       if (canBeDeclaredInNamespace(R.getLookupName())) {
11629         DeclContext *Std = SemaRef.getStdNamespace();
11630         for (Sema::AssociatedNamespaceSet::iterator
11631                it = AssociatedNamespaces.begin(),
11632                end = AssociatedNamespaces.end(); it != end; ++it) {
11633           // Never suggest declaring a function within namespace 'std'.
11634           if (Std && Std->Encloses(*it))
11635             continue;
11636 
11637           // Never suggest declaring a function within a namespace with a
11638           // reserved name, like __gnu_cxx.
11639           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11640           if (NS &&
11641               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11642             continue;
11643 
11644           SuggestedNamespaces.insert(*it);
11645         }
11646       }
11647 
11648       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11649         << R.getLookupName();
11650       if (SuggestedNamespaces.empty()) {
11651         SemaRef.Diag(Best->Function->getLocation(),
11652                      diag::note_not_found_by_two_phase_lookup)
11653           << R.getLookupName() << 0;
11654       } else if (SuggestedNamespaces.size() == 1) {
11655         SemaRef.Diag(Best->Function->getLocation(),
11656                      diag::note_not_found_by_two_phase_lookup)
11657           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11658       } else {
11659         // FIXME: It would be useful to list the associated namespaces here,
11660         // but the diagnostics infrastructure doesn't provide a way to produce
11661         // a localized representation of a list of items.
11662         SemaRef.Diag(Best->Function->getLocation(),
11663                      diag::note_not_found_by_two_phase_lookup)
11664           << R.getLookupName() << 2;
11665       }
11666 
11667       // Try to recover by calling this function.
11668       return true;
11669     }
11670 
11671     R.clear();
11672   }
11673 
11674   return false;
11675 }
11676 
11677 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11678 /// template, where the non-dependent operator was declared after the template
11679 /// was defined.
11680 ///
11681 /// Returns true if a viable candidate was found and a diagnostic was issued.
11682 static bool
11683 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11684                                SourceLocation OpLoc,
11685                                ArrayRef<Expr *> Args) {
11686   DeclarationName OpName =
11687     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11688   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11689   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11690                                 OverloadCandidateSet::CSK_Operator,
11691                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11692 }
11693 
11694 namespace {
11695 class BuildRecoveryCallExprRAII {
11696   Sema &SemaRef;
11697 public:
11698   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11699     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11700     SemaRef.IsBuildingRecoveryCallExpr = true;
11701   }
11702 
11703   ~BuildRecoveryCallExprRAII() {
11704     SemaRef.IsBuildingRecoveryCallExpr = false;
11705   }
11706 };
11707 
11708 }
11709 
11710 static std::unique_ptr<CorrectionCandidateCallback>
11711 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11712               bool HasTemplateArgs, bool AllowTypoCorrection) {
11713   if (!AllowTypoCorrection)
11714     return llvm::make_unique<NoTypoCorrectionCCC>();
11715   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11716                                                   HasTemplateArgs, ME);
11717 }
11718 
11719 /// Attempts to recover from a call where no functions were found.
11720 ///
11721 /// Returns true if new candidates were found.
11722 static ExprResult
11723 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11724                       UnresolvedLookupExpr *ULE,
11725                       SourceLocation LParenLoc,
11726                       MutableArrayRef<Expr *> Args,
11727                       SourceLocation RParenLoc,
11728                       bool EmptyLookup, bool AllowTypoCorrection) {
11729   // Do not try to recover if it is already building a recovery call.
11730   // This stops infinite loops for template instantiations like
11731   //
11732   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11733   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11734   //
11735   if (SemaRef.IsBuildingRecoveryCallExpr)
11736     return ExprError();
11737   BuildRecoveryCallExprRAII RCE(SemaRef);
11738 
11739   CXXScopeSpec SS;
11740   SS.Adopt(ULE->getQualifierLoc());
11741   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11742 
11743   TemplateArgumentListInfo TABuffer;
11744   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11745   if (ULE->hasExplicitTemplateArgs()) {
11746     ULE->copyTemplateArgumentsInto(TABuffer);
11747     ExplicitTemplateArgs = &TABuffer;
11748   }
11749 
11750   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11751                  Sema::LookupOrdinaryName);
11752   bool DoDiagnoseEmptyLookup = EmptyLookup;
11753   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11754                               OverloadCandidateSet::CSK_Normal,
11755                               ExplicitTemplateArgs, Args,
11756                               &DoDiagnoseEmptyLookup) &&
11757     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11758         S, SS, R,
11759         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11760                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11761         ExplicitTemplateArgs, Args)))
11762     return ExprError();
11763 
11764   assert(!R.empty() && "lookup results empty despite recovery");
11765 
11766   // If recovery created an ambiguity, just bail out.
11767   if (R.isAmbiguous()) {
11768     R.suppressDiagnostics();
11769     return ExprError();
11770   }
11771 
11772   // Build an implicit member call if appropriate.  Just drop the
11773   // casts and such from the call, we don't really care.
11774   ExprResult NewFn = ExprError();
11775   if ((*R.begin())->isCXXClassMember())
11776     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11777                                                     ExplicitTemplateArgs, S);
11778   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11779     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11780                                         ExplicitTemplateArgs);
11781   else
11782     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11783 
11784   if (NewFn.isInvalid())
11785     return ExprError();
11786 
11787   // This shouldn't cause an infinite loop because we're giving it
11788   // an expression with viable lookup results, which should never
11789   // end up here.
11790   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11791                                MultiExprArg(Args.data(), Args.size()),
11792                                RParenLoc);
11793 }
11794 
11795 /// \brief Constructs and populates an OverloadedCandidateSet from
11796 /// the given function.
11797 /// \returns true when an the ExprResult output parameter has been set.
11798 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11799                                   UnresolvedLookupExpr *ULE,
11800                                   MultiExprArg Args,
11801                                   SourceLocation RParenLoc,
11802                                   OverloadCandidateSet *CandidateSet,
11803                                   ExprResult *Result) {
11804 #ifndef NDEBUG
11805   if (ULE->requiresADL()) {
11806     // To do ADL, we must have found an unqualified name.
11807     assert(!ULE->getQualifier() && "qualified name with ADL");
11808 
11809     // We don't perform ADL for implicit declarations of builtins.
11810     // Verify that this was correctly set up.
11811     FunctionDecl *F;
11812     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11813         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11814         F->getBuiltinID() && F->isImplicit())
11815       llvm_unreachable("performing ADL for builtin");
11816 
11817     // We don't perform ADL in C.
11818     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11819   }
11820 #endif
11821 
11822   UnbridgedCastsSet UnbridgedCasts;
11823   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11824     *Result = ExprError();
11825     return true;
11826   }
11827 
11828   // Add the functions denoted by the callee to the set of candidate
11829   // functions, including those from argument-dependent lookup.
11830   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11831 
11832   if (getLangOpts().MSVCCompat &&
11833       CurContext->isDependentContext() && !isSFINAEContext() &&
11834       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11835 
11836     OverloadCandidateSet::iterator Best;
11837     if (CandidateSet->empty() ||
11838         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11839             OR_No_Viable_Function) {
11840       // In Microsoft mode, if we are inside a template class member function then
11841       // create a type dependent CallExpr. The goal is to postpone name lookup
11842       // to instantiation time to be able to search into type dependent base
11843       // classes.
11844       CallExpr *CE = new (Context) CallExpr(
11845           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11846       CE->setTypeDependent(true);
11847       CE->setValueDependent(true);
11848       CE->setInstantiationDependent(true);
11849       *Result = CE;
11850       return true;
11851     }
11852   }
11853 
11854   if (CandidateSet->empty())
11855     return false;
11856 
11857   UnbridgedCasts.restore();
11858   return false;
11859 }
11860 
11861 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11862 /// the completed call expression. If overload resolution fails, emits
11863 /// diagnostics and returns ExprError()
11864 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11865                                            UnresolvedLookupExpr *ULE,
11866                                            SourceLocation LParenLoc,
11867                                            MultiExprArg Args,
11868                                            SourceLocation RParenLoc,
11869                                            Expr *ExecConfig,
11870                                            OverloadCandidateSet *CandidateSet,
11871                                            OverloadCandidateSet::iterator *Best,
11872                                            OverloadingResult OverloadResult,
11873                                            bool AllowTypoCorrection) {
11874   if (CandidateSet->empty())
11875     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11876                                  RParenLoc, /*EmptyLookup=*/true,
11877                                  AllowTypoCorrection);
11878 
11879   switch (OverloadResult) {
11880   case OR_Success: {
11881     FunctionDecl *FDecl = (*Best)->Function;
11882     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11883     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11884       return ExprError();
11885     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11886     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11887                                          ExecConfig);
11888   }
11889 
11890   case OR_No_Viable_Function: {
11891     // Try to recover by looking for viable functions which the user might
11892     // have meant to call.
11893     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11894                                                 Args, RParenLoc,
11895                                                 /*EmptyLookup=*/false,
11896                                                 AllowTypoCorrection);
11897     if (!Recovery.isInvalid())
11898       return Recovery;
11899 
11900     // If the user passes in a function that we can't take the address of, we
11901     // generally end up emitting really bad error messages. Here, we attempt to
11902     // emit better ones.
11903     for (const Expr *Arg : Args) {
11904       if (!Arg->getType()->isFunctionType())
11905         continue;
11906       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11907         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11908         if (FD &&
11909             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11910                                                        Arg->getExprLoc()))
11911           return ExprError();
11912       }
11913     }
11914 
11915     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11916         << ULE->getName() << Fn->getSourceRange();
11917     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11918     break;
11919   }
11920 
11921   case OR_Ambiguous:
11922     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11923       << ULE->getName() << Fn->getSourceRange();
11924     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11925     break;
11926 
11927   case OR_Deleted: {
11928     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11929       << (*Best)->Function->isDeleted()
11930       << ULE->getName()
11931       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11932       << Fn->getSourceRange();
11933     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11934 
11935     // We emitted an error for the unavailable/deleted function call but keep
11936     // the call in the AST.
11937     FunctionDecl *FDecl = (*Best)->Function;
11938     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11939     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11940                                          ExecConfig);
11941   }
11942   }
11943 
11944   // Overload resolution failed.
11945   return ExprError();
11946 }
11947 
11948 static void markUnaddressableCandidatesUnviable(Sema &S,
11949                                                 OverloadCandidateSet &CS) {
11950   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11951     if (I->Viable &&
11952         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11953       I->Viable = false;
11954       I->FailureKind = ovl_fail_addr_not_available;
11955     }
11956   }
11957 }
11958 
11959 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11960 /// (which eventually refers to the declaration Func) and the call
11961 /// arguments Args/NumArgs, attempt to resolve the function call down
11962 /// to a specific function. If overload resolution succeeds, returns
11963 /// the call expression produced by overload resolution.
11964 /// Otherwise, emits diagnostics and returns ExprError.
11965 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11966                                          UnresolvedLookupExpr *ULE,
11967                                          SourceLocation LParenLoc,
11968                                          MultiExprArg Args,
11969                                          SourceLocation RParenLoc,
11970                                          Expr *ExecConfig,
11971                                          bool AllowTypoCorrection,
11972                                          bool CalleesAddressIsTaken) {
11973   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11974                                     OverloadCandidateSet::CSK_Normal);
11975   ExprResult result;
11976 
11977   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11978                              &result))
11979     return result;
11980 
11981   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11982   // functions that aren't addressible are considered unviable.
11983   if (CalleesAddressIsTaken)
11984     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11985 
11986   OverloadCandidateSet::iterator Best;
11987   OverloadingResult OverloadResult =
11988       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11989 
11990   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11991                                   RParenLoc, ExecConfig, &CandidateSet,
11992                                   &Best, OverloadResult,
11993                                   AllowTypoCorrection);
11994 }
11995 
11996 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11997   return Functions.size() > 1 ||
11998     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11999 }
12000 
12001 /// \brief Create a unary operation that may resolve to an overloaded
12002 /// operator.
12003 ///
12004 /// \param OpLoc The location of the operator itself (e.g., '*').
12005 ///
12006 /// \param Opc The UnaryOperatorKind that describes this operator.
12007 ///
12008 /// \param Fns The set of non-member functions that will be
12009 /// considered by overload resolution. The caller needs to build this
12010 /// set based on the context using, e.g.,
12011 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12012 /// set should not contain any member functions; those will be added
12013 /// by CreateOverloadedUnaryOp().
12014 ///
12015 /// \param Input The input argument.
12016 ExprResult
12017 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12018                               const UnresolvedSetImpl &Fns,
12019                               Expr *Input, bool PerformADL) {
12020   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12021   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12022   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12023   // TODO: provide better source location info.
12024   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12025 
12026   if (checkPlaceholderForOverload(*this, Input))
12027     return ExprError();
12028 
12029   Expr *Args[2] = { Input, nullptr };
12030   unsigned NumArgs = 1;
12031 
12032   // For post-increment and post-decrement, add the implicit '0' as
12033   // the second argument, so that we know this is a post-increment or
12034   // post-decrement.
12035   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12036     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12037     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12038                                      SourceLocation());
12039     NumArgs = 2;
12040   }
12041 
12042   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12043 
12044   if (Input->isTypeDependent()) {
12045     if (Fns.empty())
12046       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12047                                          VK_RValue, OK_Ordinary, OpLoc, false);
12048 
12049     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12050     UnresolvedLookupExpr *Fn
12051       = UnresolvedLookupExpr::Create(Context, NamingClass,
12052                                      NestedNameSpecifierLoc(), OpNameInfo,
12053                                      /*ADL*/ true, IsOverloaded(Fns),
12054                                      Fns.begin(), Fns.end());
12055     return new (Context)
12056         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12057                             VK_RValue, OpLoc, FPOptions());
12058   }
12059 
12060   // Build an empty overload set.
12061   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12062 
12063   // Add the candidates from the given function set.
12064   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12065 
12066   // Add operator candidates that are member functions.
12067   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12068 
12069   // Add candidates from ADL.
12070   if (PerformADL) {
12071     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12072                                          /*ExplicitTemplateArgs*/nullptr,
12073                                          CandidateSet);
12074   }
12075 
12076   // Add builtin operator candidates.
12077   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12078 
12079   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12080 
12081   // Perform overload resolution.
12082   OverloadCandidateSet::iterator Best;
12083   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12084   case OR_Success: {
12085     // We found a built-in operator or an overloaded operator.
12086     FunctionDecl *FnDecl = Best->Function;
12087 
12088     if (FnDecl) {
12089       Expr *Base = nullptr;
12090       // We matched an overloaded operator. Build a call to that
12091       // operator.
12092 
12093       // Convert the arguments.
12094       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12095         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12096 
12097         ExprResult InputRes =
12098           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12099                                               Best->FoundDecl, Method);
12100         if (InputRes.isInvalid())
12101           return ExprError();
12102         Base = Input = InputRes.get();
12103       } else {
12104         // Convert the arguments.
12105         ExprResult InputInit
12106           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12107                                                       Context,
12108                                                       FnDecl->getParamDecl(0)),
12109                                       SourceLocation(),
12110                                       Input);
12111         if (InputInit.isInvalid())
12112           return ExprError();
12113         Input = InputInit.get();
12114       }
12115 
12116       // Build the actual expression node.
12117       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12118                                                 Base, HadMultipleCandidates,
12119                                                 OpLoc);
12120       if (FnExpr.isInvalid())
12121         return ExprError();
12122 
12123       // Determine the result type.
12124       QualType ResultTy = FnDecl->getReturnType();
12125       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12126       ResultTy = ResultTy.getNonLValueExprType(Context);
12127 
12128       Args[0] = Input;
12129       CallExpr *TheCall =
12130         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12131                                           ResultTy, VK, OpLoc, FPOptions());
12132 
12133       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12134         return ExprError();
12135 
12136       if (CheckFunctionCall(FnDecl, TheCall,
12137                             FnDecl->getType()->castAs<FunctionProtoType>()))
12138         return ExprError();
12139 
12140       return MaybeBindToTemporary(TheCall);
12141     } else {
12142       // We matched a built-in operator. Convert the arguments, then
12143       // break out so that we will build the appropriate built-in
12144       // operator node.
12145       ExprResult InputRes = PerformImplicitConversion(
12146           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12147       if (InputRes.isInvalid())
12148         return ExprError();
12149       Input = InputRes.get();
12150       break;
12151     }
12152   }
12153 
12154   case OR_No_Viable_Function:
12155     // This is an erroneous use of an operator which can be overloaded by
12156     // a non-member function. Check for non-member operators which were
12157     // defined too late to be candidates.
12158     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12159       // FIXME: Recover by calling the found function.
12160       return ExprError();
12161 
12162     // No viable function; fall through to handling this as a
12163     // built-in operator, which will produce an error message for us.
12164     break;
12165 
12166   case OR_Ambiguous:
12167     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12168         << UnaryOperator::getOpcodeStr(Opc)
12169         << Input->getType()
12170         << Input->getSourceRange();
12171     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12172                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12173     return ExprError();
12174 
12175   case OR_Deleted:
12176     Diag(OpLoc, diag::err_ovl_deleted_oper)
12177       << Best->Function->isDeleted()
12178       << UnaryOperator::getOpcodeStr(Opc)
12179       << getDeletedOrUnavailableSuffix(Best->Function)
12180       << Input->getSourceRange();
12181     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12182                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12183     return ExprError();
12184   }
12185 
12186   // Either we found no viable overloaded operator or we matched a
12187   // built-in operator. In either case, fall through to trying to
12188   // build a built-in operation.
12189   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12190 }
12191 
12192 /// \brief Create a binary operation that may resolve to an overloaded
12193 /// operator.
12194 ///
12195 /// \param OpLoc The location of the operator itself (e.g., '+').
12196 ///
12197 /// \param Opc The BinaryOperatorKind that describes this operator.
12198 ///
12199 /// \param Fns The set of non-member functions that will be
12200 /// considered by overload resolution. The caller needs to build this
12201 /// set based on the context using, e.g.,
12202 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12203 /// set should not contain any member functions; those will be added
12204 /// by CreateOverloadedBinOp().
12205 ///
12206 /// \param LHS Left-hand argument.
12207 /// \param RHS Right-hand argument.
12208 ExprResult
12209 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12210                             BinaryOperatorKind Opc,
12211                             const UnresolvedSetImpl &Fns,
12212                             Expr *LHS, Expr *RHS, bool PerformADL) {
12213   Expr *Args[2] = { LHS, RHS };
12214   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12215 
12216   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12217   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12218 
12219   // If either side is type-dependent, create an appropriate dependent
12220   // expression.
12221   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12222     if (Fns.empty()) {
12223       // If there are no functions to store, just build a dependent
12224       // BinaryOperator or CompoundAssignment.
12225       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12226         return new (Context) BinaryOperator(
12227             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12228             OpLoc, FPFeatures);
12229 
12230       return new (Context) CompoundAssignOperator(
12231           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12232           Context.DependentTy, Context.DependentTy, OpLoc,
12233           FPFeatures);
12234     }
12235 
12236     // FIXME: save results of ADL from here?
12237     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12238     // TODO: provide better source location info in DNLoc component.
12239     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12240     UnresolvedLookupExpr *Fn
12241       = UnresolvedLookupExpr::Create(Context, NamingClass,
12242                                      NestedNameSpecifierLoc(), OpNameInfo,
12243                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12244                                      Fns.begin(), Fns.end());
12245     return new (Context)
12246         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12247                             VK_RValue, OpLoc, FPFeatures);
12248   }
12249 
12250   // Always do placeholder-like conversions on the RHS.
12251   if (checkPlaceholderForOverload(*this, Args[1]))
12252     return ExprError();
12253 
12254   // Do placeholder-like conversion on the LHS; note that we should
12255   // not get here with a PseudoObject LHS.
12256   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12257   if (checkPlaceholderForOverload(*this, Args[0]))
12258     return ExprError();
12259 
12260   // If this is the assignment operator, we only perform overload resolution
12261   // if the left-hand side is a class or enumeration type. This is actually
12262   // a hack. The standard requires that we do overload resolution between the
12263   // various built-in candidates, but as DR507 points out, this can lead to
12264   // problems. So we do it this way, which pretty much follows what GCC does.
12265   // Note that we go the traditional code path for compound assignment forms.
12266   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12267     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12268 
12269   // If this is the .* operator, which is not overloadable, just
12270   // create a built-in binary operator.
12271   if (Opc == BO_PtrMemD)
12272     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12273 
12274   // Build an empty overload set.
12275   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12276 
12277   // Add the candidates from the given function set.
12278   AddFunctionCandidates(Fns, Args, CandidateSet);
12279 
12280   // Add operator candidates that are member functions.
12281   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12282 
12283   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12284   // performed for an assignment operator (nor for operator[] nor operator->,
12285   // which don't get here).
12286   if (Opc != BO_Assign && PerformADL)
12287     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12288                                          /*ExplicitTemplateArgs*/ nullptr,
12289                                          CandidateSet);
12290 
12291   // Add builtin operator candidates.
12292   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12293 
12294   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12295 
12296   // Perform overload resolution.
12297   OverloadCandidateSet::iterator Best;
12298   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12299     case OR_Success: {
12300       // We found a built-in operator or an overloaded operator.
12301       FunctionDecl *FnDecl = Best->Function;
12302 
12303       if (FnDecl) {
12304         Expr *Base = nullptr;
12305         // We matched an overloaded operator. Build a call to that
12306         // operator.
12307 
12308         // Convert the arguments.
12309         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12310           // Best->Access is only meaningful for class members.
12311           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12312 
12313           ExprResult Arg1 =
12314             PerformCopyInitialization(
12315               InitializedEntity::InitializeParameter(Context,
12316                                                      FnDecl->getParamDecl(0)),
12317               SourceLocation(), Args[1]);
12318           if (Arg1.isInvalid())
12319             return ExprError();
12320 
12321           ExprResult Arg0 =
12322             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12323                                                 Best->FoundDecl, Method);
12324           if (Arg0.isInvalid())
12325             return ExprError();
12326           Base = Args[0] = Arg0.getAs<Expr>();
12327           Args[1] = RHS = Arg1.getAs<Expr>();
12328         } else {
12329           // Convert the arguments.
12330           ExprResult Arg0 = PerformCopyInitialization(
12331             InitializedEntity::InitializeParameter(Context,
12332                                                    FnDecl->getParamDecl(0)),
12333             SourceLocation(), Args[0]);
12334           if (Arg0.isInvalid())
12335             return ExprError();
12336 
12337           ExprResult Arg1 =
12338             PerformCopyInitialization(
12339               InitializedEntity::InitializeParameter(Context,
12340                                                      FnDecl->getParamDecl(1)),
12341               SourceLocation(), Args[1]);
12342           if (Arg1.isInvalid())
12343             return ExprError();
12344           Args[0] = LHS = Arg0.getAs<Expr>();
12345           Args[1] = RHS = Arg1.getAs<Expr>();
12346         }
12347 
12348         // Build the actual expression node.
12349         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12350                                                   Best->FoundDecl, Base,
12351                                                   HadMultipleCandidates, OpLoc);
12352         if (FnExpr.isInvalid())
12353           return ExprError();
12354 
12355         // Determine the result type.
12356         QualType ResultTy = FnDecl->getReturnType();
12357         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12358         ResultTy = ResultTy.getNonLValueExprType(Context);
12359 
12360         CXXOperatorCallExpr *TheCall =
12361           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12362                                             Args, ResultTy, VK, OpLoc,
12363                                             FPFeatures);
12364 
12365         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12366                                 FnDecl))
12367           return ExprError();
12368 
12369         ArrayRef<const Expr *> ArgsArray(Args, 2);
12370         const Expr *ImplicitThis = nullptr;
12371         // Cut off the implicit 'this'.
12372         if (isa<CXXMethodDecl>(FnDecl)) {
12373           ImplicitThis = ArgsArray[0];
12374           ArgsArray = ArgsArray.slice(1);
12375         }
12376 
12377         // Check for a self move.
12378         if (Op == OO_Equal)
12379           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12380 
12381         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12382                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12383                   VariadicDoesNotApply);
12384 
12385         return MaybeBindToTemporary(TheCall);
12386       } else {
12387         // We matched a built-in operator. Convert the arguments, then
12388         // break out so that we will build the appropriate built-in
12389         // operator node.
12390         ExprResult ArgsRes0 =
12391             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12392                                       Best->Conversions[0], AA_Passing);
12393         if (ArgsRes0.isInvalid())
12394           return ExprError();
12395         Args[0] = ArgsRes0.get();
12396 
12397         ExprResult ArgsRes1 =
12398             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12399                                       Best->Conversions[1], AA_Passing);
12400         if (ArgsRes1.isInvalid())
12401           return ExprError();
12402         Args[1] = ArgsRes1.get();
12403         break;
12404       }
12405     }
12406 
12407     case OR_No_Viable_Function: {
12408       // C++ [over.match.oper]p9:
12409       //   If the operator is the operator , [...] and there are no
12410       //   viable functions, then the operator is assumed to be the
12411       //   built-in operator and interpreted according to clause 5.
12412       if (Opc == BO_Comma)
12413         break;
12414 
12415       // For class as left operand for assignment or compound assignment
12416       // operator do not fall through to handling in built-in, but report that
12417       // no overloaded assignment operator found
12418       ExprResult Result = ExprError();
12419       if (Args[0]->getType()->isRecordType() &&
12420           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12421         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12422              << BinaryOperator::getOpcodeStr(Opc)
12423              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12424         if (Args[0]->getType()->isIncompleteType()) {
12425           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12426             << Args[0]->getType()
12427             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12428         }
12429       } else {
12430         // This is an erroneous use of an operator which can be overloaded by
12431         // a non-member function. Check for non-member operators which were
12432         // defined too late to be candidates.
12433         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12434           // FIXME: Recover by calling the found function.
12435           return ExprError();
12436 
12437         // No viable function; try to create a built-in operation, which will
12438         // produce an error. Then, show the non-viable candidates.
12439         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12440       }
12441       assert(Result.isInvalid() &&
12442              "C++ binary operator overloading is missing candidates!");
12443       if (Result.isInvalid())
12444         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12445                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12446       return Result;
12447     }
12448 
12449     case OR_Ambiguous:
12450       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12451           << BinaryOperator::getOpcodeStr(Opc)
12452           << Args[0]->getType() << Args[1]->getType()
12453           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12454       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12455                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12456       return ExprError();
12457 
12458     case OR_Deleted:
12459       if (isImplicitlyDeleted(Best->Function)) {
12460         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12461         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12462           << Context.getRecordType(Method->getParent())
12463           << getSpecialMember(Method);
12464 
12465         // The user probably meant to call this special member. Just
12466         // explain why it's deleted.
12467         NoteDeletedFunction(Method);
12468         return ExprError();
12469       } else {
12470         Diag(OpLoc, diag::err_ovl_deleted_oper)
12471           << Best->Function->isDeleted()
12472           << BinaryOperator::getOpcodeStr(Opc)
12473           << getDeletedOrUnavailableSuffix(Best->Function)
12474           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12475       }
12476       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12477                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12478       return ExprError();
12479   }
12480 
12481   // We matched a built-in operator; build it.
12482   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12483 }
12484 
12485 ExprResult
12486 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12487                                          SourceLocation RLoc,
12488                                          Expr *Base, Expr *Idx) {
12489   Expr *Args[2] = { Base, Idx };
12490   DeclarationName OpName =
12491       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12492 
12493   // If either side is type-dependent, create an appropriate dependent
12494   // expression.
12495   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12496 
12497     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12498     // CHECKME: no 'operator' keyword?
12499     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12500     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12501     UnresolvedLookupExpr *Fn
12502       = UnresolvedLookupExpr::Create(Context, NamingClass,
12503                                      NestedNameSpecifierLoc(), OpNameInfo,
12504                                      /*ADL*/ true, /*Overloaded*/ false,
12505                                      UnresolvedSetIterator(),
12506                                      UnresolvedSetIterator());
12507     // Can't add any actual overloads yet
12508 
12509     return new (Context)
12510         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12511                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12512   }
12513 
12514   // Handle placeholders on both operands.
12515   if (checkPlaceholderForOverload(*this, Args[0]))
12516     return ExprError();
12517   if (checkPlaceholderForOverload(*this, Args[1]))
12518     return ExprError();
12519 
12520   // Build an empty overload set.
12521   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12522 
12523   // Subscript can only be overloaded as a member function.
12524 
12525   // Add operator candidates that are member functions.
12526   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12527 
12528   // Add builtin operator candidates.
12529   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12530 
12531   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12532 
12533   // Perform overload resolution.
12534   OverloadCandidateSet::iterator Best;
12535   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12536     case OR_Success: {
12537       // We found a built-in operator or an overloaded operator.
12538       FunctionDecl *FnDecl = Best->Function;
12539 
12540       if (FnDecl) {
12541         // We matched an overloaded operator. Build a call to that
12542         // operator.
12543 
12544         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12545 
12546         // Convert the arguments.
12547         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12548         ExprResult Arg0 =
12549           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12550                                               Best->FoundDecl, Method);
12551         if (Arg0.isInvalid())
12552           return ExprError();
12553         Args[0] = Arg0.get();
12554 
12555         // Convert the arguments.
12556         ExprResult InputInit
12557           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12558                                                       Context,
12559                                                       FnDecl->getParamDecl(0)),
12560                                       SourceLocation(),
12561                                       Args[1]);
12562         if (InputInit.isInvalid())
12563           return ExprError();
12564 
12565         Args[1] = InputInit.getAs<Expr>();
12566 
12567         // Build the actual expression node.
12568         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12569         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12570         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12571                                                   Best->FoundDecl,
12572                                                   Base,
12573                                                   HadMultipleCandidates,
12574                                                   OpLocInfo.getLoc(),
12575                                                   OpLocInfo.getInfo());
12576         if (FnExpr.isInvalid())
12577           return ExprError();
12578 
12579         // Determine the result type
12580         QualType ResultTy = FnDecl->getReturnType();
12581         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12582         ResultTy = ResultTy.getNonLValueExprType(Context);
12583 
12584         CXXOperatorCallExpr *TheCall =
12585           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12586                                             FnExpr.get(), Args,
12587                                             ResultTy, VK, RLoc,
12588                                             FPOptions());
12589 
12590         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12591           return ExprError();
12592 
12593         if (CheckFunctionCall(Method, TheCall,
12594                               Method->getType()->castAs<FunctionProtoType>()))
12595           return ExprError();
12596 
12597         return MaybeBindToTemporary(TheCall);
12598       } else {
12599         // We matched a built-in operator. Convert the arguments, then
12600         // break out so that we will build the appropriate built-in
12601         // operator node.
12602         ExprResult ArgsRes0 =
12603             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12604                                       Best->Conversions[0], AA_Passing);
12605         if (ArgsRes0.isInvalid())
12606           return ExprError();
12607         Args[0] = ArgsRes0.get();
12608 
12609         ExprResult ArgsRes1 =
12610             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12611                                       Best->Conversions[1], AA_Passing);
12612         if (ArgsRes1.isInvalid())
12613           return ExprError();
12614         Args[1] = ArgsRes1.get();
12615 
12616         break;
12617       }
12618     }
12619 
12620     case OR_No_Viable_Function: {
12621       if (CandidateSet.empty())
12622         Diag(LLoc, diag::err_ovl_no_oper)
12623           << Args[0]->getType() << /*subscript*/ 0
12624           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12625       else
12626         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12627           << Args[0]->getType()
12628           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12629       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12630                                   "[]", LLoc);
12631       return ExprError();
12632     }
12633 
12634     case OR_Ambiguous:
12635       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12636           << "[]"
12637           << Args[0]->getType() << Args[1]->getType()
12638           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12639       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12640                                   "[]", LLoc);
12641       return ExprError();
12642 
12643     case OR_Deleted:
12644       Diag(LLoc, diag::err_ovl_deleted_oper)
12645         << Best->Function->isDeleted() << "[]"
12646         << getDeletedOrUnavailableSuffix(Best->Function)
12647         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12648       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12649                                   "[]", LLoc);
12650       return ExprError();
12651     }
12652 
12653   // We matched a built-in operator; build it.
12654   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12655 }
12656 
12657 /// BuildCallToMemberFunction - Build a call to a member
12658 /// function. MemExpr is the expression that refers to the member
12659 /// function (and includes the object parameter), Args/NumArgs are the
12660 /// arguments to the function call (not including the object
12661 /// parameter). The caller needs to validate that the member
12662 /// expression refers to a non-static member function or an overloaded
12663 /// member function.
12664 ExprResult
12665 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12666                                 SourceLocation LParenLoc,
12667                                 MultiExprArg Args,
12668                                 SourceLocation RParenLoc) {
12669   assert(MemExprE->getType() == Context.BoundMemberTy ||
12670          MemExprE->getType() == Context.OverloadTy);
12671 
12672   // Dig out the member expression. This holds both the object
12673   // argument and the member function we're referring to.
12674   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12675 
12676   // Determine whether this is a call to a pointer-to-member function.
12677   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12678     assert(op->getType() == Context.BoundMemberTy);
12679     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12680 
12681     QualType fnType =
12682       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12683 
12684     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12685     QualType resultType = proto->getCallResultType(Context);
12686     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12687 
12688     // Check that the object type isn't more qualified than the
12689     // member function we're calling.
12690     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12691 
12692     QualType objectType = op->getLHS()->getType();
12693     if (op->getOpcode() == BO_PtrMemI)
12694       objectType = objectType->castAs<PointerType>()->getPointeeType();
12695     Qualifiers objectQuals = objectType.getQualifiers();
12696 
12697     Qualifiers difference = objectQuals - funcQuals;
12698     difference.removeObjCGCAttr();
12699     difference.removeAddressSpace();
12700     if (difference) {
12701       std::string qualsString = difference.getAsString();
12702       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12703         << fnType.getUnqualifiedType()
12704         << qualsString
12705         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12706     }
12707 
12708     CXXMemberCallExpr *call
12709       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12710                                         resultType, valueKind, RParenLoc);
12711 
12712     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12713                             call, nullptr))
12714       return ExprError();
12715 
12716     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12717       return ExprError();
12718 
12719     if (CheckOtherCall(call, proto))
12720       return ExprError();
12721 
12722     return MaybeBindToTemporary(call);
12723   }
12724 
12725   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12726     return new (Context)
12727         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12728 
12729   UnbridgedCastsSet UnbridgedCasts;
12730   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12731     return ExprError();
12732 
12733   MemberExpr *MemExpr;
12734   CXXMethodDecl *Method = nullptr;
12735   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12736   NestedNameSpecifier *Qualifier = nullptr;
12737   if (isa<MemberExpr>(NakedMemExpr)) {
12738     MemExpr = cast<MemberExpr>(NakedMemExpr);
12739     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12740     FoundDecl = MemExpr->getFoundDecl();
12741     Qualifier = MemExpr->getQualifier();
12742     UnbridgedCasts.restore();
12743   } else {
12744     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12745     Qualifier = UnresExpr->getQualifier();
12746 
12747     QualType ObjectType = UnresExpr->getBaseType();
12748     Expr::Classification ObjectClassification
12749       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12750                             : UnresExpr->getBase()->Classify(Context);
12751 
12752     // Add overload candidates
12753     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12754                                       OverloadCandidateSet::CSK_Normal);
12755 
12756     // FIXME: avoid copy.
12757     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12758     if (UnresExpr->hasExplicitTemplateArgs()) {
12759       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12760       TemplateArgs = &TemplateArgsBuffer;
12761     }
12762 
12763     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12764            E = UnresExpr->decls_end(); I != E; ++I) {
12765 
12766       NamedDecl *Func = *I;
12767       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12768       if (isa<UsingShadowDecl>(Func))
12769         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12770 
12771 
12772       // Microsoft supports direct constructor calls.
12773       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12774         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12775                              Args, CandidateSet);
12776       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12777         // If explicit template arguments were provided, we can't call a
12778         // non-template member function.
12779         if (TemplateArgs)
12780           continue;
12781 
12782         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12783                            ObjectClassification, Args, CandidateSet,
12784                            /*SuppressUserConversions=*/false);
12785       } else {
12786         AddMethodTemplateCandidate(
12787             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12788             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12789             /*SuppressUsedConversions=*/false);
12790       }
12791     }
12792 
12793     DeclarationName DeclName = UnresExpr->getMemberName();
12794 
12795     UnbridgedCasts.restore();
12796 
12797     OverloadCandidateSet::iterator Best;
12798     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12799                                             Best)) {
12800     case OR_Success:
12801       Method = cast<CXXMethodDecl>(Best->Function);
12802       FoundDecl = Best->FoundDecl;
12803       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12804       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12805         return ExprError();
12806       // If FoundDecl is different from Method (such as if one is a template
12807       // and the other a specialization), make sure DiagnoseUseOfDecl is
12808       // called on both.
12809       // FIXME: This would be more comprehensively addressed by modifying
12810       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12811       // being used.
12812       if (Method != FoundDecl.getDecl() &&
12813                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12814         return ExprError();
12815       break;
12816 
12817     case OR_No_Viable_Function:
12818       Diag(UnresExpr->getMemberLoc(),
12819            diag::err_ovl_no_viable_member_function_in_call)
12820         << DeclName << MemExprE->getSourceRange();
12821       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12822       // FIXME: Leaking incoming expressions!
12823       return ExprError();
12824 
12825     case OR_Ambiguous:
12826       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12827         << DeclName << MemExprE->getSourceRange();
12828       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12829       // FIXME: Leaking incoming expressions!
12830       return ExprError();
12831 
12832     case OR_Deleted:
12833       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12834         << Best->Function->isDeleted()
12835         << DeclName
12836         << getDeletedOrUnavailableSuffix(Best->Function)
12837         << MemExprE->getSourceRange();
12838       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12839       // FIXME: Leaking incoming expressions!
12840       return ExprError();
12841     }
12842 
12843     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12844 
12845     // If overload resolution picked a static member, build a
12846     // non-member call based on that function.
12847     if (Method->isStatic()) {
12848       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12849                                    RParenLoc);
12850     }
12851 
12852     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12853   }
12854 
12855   QualType ResultType = Method->getReturnType();
12856   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12857   ResultType = ResultType.getNonLValueExprType(Context);
12858 
12859   assert(Method && "Member call to something that isn't a method?");
12860   CXXMemberCallExpr *TheCall =
12861     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12862                                     ResultType, VK, RParenLoc);
12863 
12864   // Check for a valid return type.
12865   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12866                           TheCall, Method))
12867     return ExprError();
12868 
12869   // Convert the object argument (for a non-static member function call).
12870   // We only need to do this if there was actually an overload; otherwise
12871   // it was done at lookup.
12872   if (!Method->isStatic()) {
12873     ExprResult ObjectArg =
12874       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12875                                           FoundDecl, Method);
12876     if (ObjectArg.isInvalid())
12877       return ExprError();
12878     MemExpr->setBase(ObjectArg.get());
12879   }
12880 
12881   // Convert the rest of the arguments
12882   const FunctionProtoType *Proto =
12883     Method->getType()->getAs<FunctionProtoType>();
12884   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12885                               RParenLoc))
12886     return ExprError();
12887 
12888   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12889 
12890   if (CheckFunctionCall(Method, TheCall, Proto))
12891     return ExprError();
12892 
12893   // In the case the method to call was not selected by the overloading
12894   // resolution process, we still need to handle the enable_if attribute. Do
12895   // that here, so it will not hide previous -- and more relevant -- errors.
12896   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12897     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12898       Diag(MemE->getMemberLoc(),
12899            diag::err_ovl_no_viable_member_function_in_call)
12900           << Method << Method->getSourceRange();
12901       Diag(Method->getLocation(),
12902            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12903           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12904       return ExprError();
12905     }
12906   }
12907 
12908   if ((isa<CXXConstructorDecl>(CurContext) ||
12909        isa<CXXDestructorDecl>(CurContext)) &&
12910       TheCall->getMethodDecl()->isPure()) {
12911     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12912 
12913     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12914         MemExpr->performsVirtualDispatch(getLangOpts())) {
12915       Diag(MemExpr->getLocStart(),
12916            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12917         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12918         << MD->getParent()->getDeclName();
12919 
12920       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12921       if (getLangOpts().AppleKext)
12922         Diag(MemExpr->getLocStart(),
12923              diag::note_pure_qualified_call_kext)
12924              << MD->getParent()->getDeclName()
12925              << MD->getDeclName();
12926     }
12927   }
12928 
12929   if (CXXDestructorDecl *DD =
12930           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12931     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12932     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12933     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12934                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12935                          MemExpr->getMemberLoc());
12936   }
12937 
12938   return MaybeBindToTemporary(TheCall);
12939 }
12940 
12941 /// BuildCallToObjectOfClassType - Build a call to an object of class
12942 /// type (C++ [over.call.object]), which can end up invoking an
12943 /// overloaded function call operator (@c operator()) or performing a
12944 /// user-defined conversion on the object argument.
12945 ExprResult
12946 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12947                                    SourceLocation LParenLoc,
12948                                    MultiExprArg Args,
12949                                    SourceLocation RParenLoc) {
12950   if (checkPlaceholderForOverload(*this, Obj))
12951     return ExprError();
12952   ExprResult Object = Obj;
12953 
12954   UnbridgedCastsSet UnbridgedCasts;
12955   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12956     return ExprError();
12957 
12958   assert(Object.get()->getType()->isRecordType() &&
12959          "Requires object type argument");
12960   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12961 
12962   // C++ [over.call.object]p1:
12963   //  If the primary-expression E in the function call syntax
12964   //  evaluates to a class object of type "cv T", then the set of
12965   //  candidate functions includes at least the function call
12966   //  operators of T. The function call operators of T are obtained by
12967   //  ordinary lookup of the name operator() in the context of
12968   //  (E).operator().
12969   OverloadCandidateSet CandidateSet(LParenLoc,
12970                                     OverloadCandidateSet::CSK_Operator);
12971   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12972 
12973   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12974                           diag::err_incomplete_object_call, Object.get()))
12975     return true;
12976 
12977   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12978   LookupQualifiedName(R, Record->getDecl());
12979   R.suppressDiagnostics();
12980 
12981   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12982        Oper != OperEnd; ++Oper) {
12983     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12984                        Object.get()->Classify(Context), Args, CandidateSet,
12985                        /*SuppressUserConversions=*/false);
12986   }
12987 
12988   // C++ [over.call.object]p2:
12989   //   In addition, for each (non-explicit in C++0x) conversion function
12990   //   declared in T of the form
12991   //
12992   //        operator conversion-type-id () cv-qualifier;
12993   //
12994   //   where cv-qualifier is the same cv-qualification as, or a
12995   //   greater cv-qualification than, cv, and where conversion-type-id
12996   //   denotes the type "pointer to function of (P1,...,Pn) returning
12997   //   R", or the type "reference to pointer to function of
12998   //   (P1,...,Pn) returning R", or the type "reference to function
12999   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13000   //   is also considered as a candidate function. Similarly,
13001   //   surrogate call functions are added to the set of candidate
13002   //   functions for each conversion function declared in an
13003   //   accessible base class provided the function is not hidden
13004   //   within T by another intervening declaration.
13005   const auto &Conversions =
13006       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13007   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13008     NamedDecl *D = *I;
13009     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13010     if (isa<UsingShadowDecl>(D))
13011       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13012 
13013     // Skip over templated conversion functions; they aren't
13014     // surrogates.
13015     if (isa<FunctionTemplateDecl>(D))
13016       continue;
13017 
13018     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13019     if (!Conv->isExplicit()) {
13020       // Strip the reference type (if any) and then the pointer type (if
13021       // any) to get down to what might be a function type.
13022       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13023       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13024         ConvType = ConvPtrType->getPointeeType();
13025 
13026       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13027       {
13028         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13029                               Object.get(), Args, CandidateSet);
13030       }
13031     }
13032   }
13033 
13034   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13035 
13036   // Perform overload resolution.
13037   OverloadCandidateSet::iterator Best;
13038   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13039                                           Best)) {
13040   case OR_Success:
13041     // Overload resolution succeeded; we'll build the appropriate call
13042     // below.
13043     break;
13044 
13045   case OR_No_Viable_Function:
13046     if (CandidateSet.empty())
13047       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13048         << Object.get()->getType() << /*call*/ 1
13049         << Object.get()->getSourceRange();
13050     else
13051       Diag(Object.get()->getLocStart(),
13052            diag::err_ovl_no_viable_object_call)
13053         << Object.get()->getType() << Object.get()->getSourceRange();
13054     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13055     break;
13056 
13057   case OR_Ambiguous:
13058     Diag(Object.get()->getLocStart(),
13059          diag::err_ovl_ambiguous_object_call)
13060       << Object.get()->getType() << Object.get()->getSourceRange();
13061     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13062     break;
13063 
13064   case OR_Deleted:
13065     Diag(Object.get()->getLocStart(),
13066          diag::err_ovl_deleted_object_call)
13067       << Best->Function->isDeleted()
13068       << Object.get()->getType()
13069       << getDeletedOrUnavailableSuffix(Best->Function)
13070       << Object.get()->getSourceRange();
13071     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13072     break;
13073   }
13074 
13075   if (Best == CandidateSet.end())
13076     return true;
13077 
13078   UnbridgedCasts.restore();
13079 
13080   if (Best->Function == nullptr) {
13081     // Since there is no function declaration, this is one of the
13082     // surrogate candidates. Dig out the conversion function.
13083     CXXConversionDecl *Conv
13084       = cast<CXXConversionDecl>(
13085                          Best->Conversions[0].UserDefined.ConversionFunction);
13086 
13087     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13088                               Best->FoundDecl);
13089     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13090       return ExprError();
13091     assert(Conv == Best->FoundDecl.getDecl() &&
13092              "Found Decl & conversion-to-functionptr should be same, right?!");
13093     // We selected one of the surrogate functions that converts the
13094     // object parameter to a function pointer. Perform the conversion
13095     // on the object argument, then let ActOnCallExpr finish the job.
13096 
13097     // Create an implicit member expr to refer to the conversion operator.
13098     // and then call it.
13099     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13100                                              Conv, HadMultipleCandidates);
13101     if (Call.isInvalid())
13102       return ExprError();
13103     // Record usage of conversion in an implicit cast.
13104     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13105                                     CK_UserDefinedConversion, Call.get(),
13106                                     nullptr, VK_RValue);
13107 
13108     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13109   }
13110 
13111   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13112 
13113   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13114   // that calls this method, using Object for the implicit object
13115   // parameter and passing along the remaining arguments.
13116   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13117 
13118   // An error diagnostic has already been printed when parsing the declaration.
13119   if (Method->isInvalidDecl())
13120     return ExprError();
13121 
13122   const FunctionProtoType *Proto =
13123     Method->getType()->getAs<FunctionProtoType>();
13124 
13125   unsigned NumParams = Proto->getNumParams();
13126 
13127   DeclarationNameInfo OpLocInfo(
13128                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13129   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13130   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13131                                            Obj, HadMultipleCandidates,
13132                                            OpLocInfo.getLoc(),
13133                                            OpLocInfo.getInfo());
13134   if (NewFn.isInvalid())
13135     return true;
13136 
13137   // Build the full argument list for the method call (the implicit object
13138   // parameter is placed at the beginning of the list).
13139   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13140   MethodArgs[0] = Object.get();
13141   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13142 
13143   // Once we've built TheCall, all of the expressions are properly
13144   // owned.
13145   QualType ResultTy = Method->getReturnType();
13146   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13147   ResultTy = ResultTy.getNonLValueExprType(Context);
13148 
13149   CXXOperatorCallExpr *TheCall = new (Context)
13150       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13151                           VK, RParenLoc, FPOptions());
13152 
13153   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13154     return true;
13155 
13156   // We may have default arguments. If so, we need to allocate more
13157   // slots in the call for them.
13158   if (Args.size() < NumParams)
13159     TheCall->setNumArgs(Context, NumParams + 1);
13160 
13161   bool IsError = false;
13162 
13163   // Initialize the implicit object parameter.
13164   ExprResult ObjRes =
13165     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13166                                         Best->FoundDecl, Method);
13167   if (ObjRes.isInvalid())
13168     IsError = true;
13169   else
13170     Object = ObjRes;
13171   TheCall->setArg(0, Object.get());
13172 
13173   // Check the argument types.
13174   for (unsigned i = 0; i != NumParams; i++) {
13175     Expr *Arg;
13176     if (i < Args.size()) {
13177       Arg = Args[i];
13178 
13179       // Pass the argument.
13180 
13181       ExprResult InputInit
13182         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13183                                                     Context,
13184                                                     Method->getParamDecl(i)),
13185                                     SourceLocation(), Arg);
13186 
13187       IsError |= InputInit.isInvalid();
13188       Arg = InputInit.getAs<Expr>();
13189     } else {
13190       ExprResult DefArg
13191         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13192       if (DefArg.isInvalid()) {
13193         IsError = true;
13194         break;
13195       }
13196 
13197       Arg = DefArg.getAs<Expr>();
13198     }
13199 
13200     TheCall->setArg(i + 1, Arg);
13201   }
13202 
13203   // If this is a variadic call, handle args passed through "...".
13204   if (Proto->isVariadic()) {
13205     // Promote the arguments (C99 6.5.2.2p7).
13206     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13207       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13208                                                         nullptr);
13209       IsError |= Arg.isInvalid();
13210       TheCall->setArg(i + 1, Arg.get());
13211     }
13212   }
13213 
13214   if (IsError) return true;
13215 
13216   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13217 
13218   if (CheckFunctionCall(Method, TheCall, Proto))
13219     return true;
13220 
13221   return MaybeBindToTemporary(TheCall);
13222 }
13223 
13224 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13225 ///  (if one exists), where @c Base is an expression of class type and
13226 /// @c Member is the name of the member we're trying to find.
13227 ExprResult
13228 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13229                                bool *NoArrowOperatorFound) {
13230   assert(Base->getType()->isRecordType() &&
13231          "left-hand side must have class type");
13232 
13233   if (checkPlaceholderForOverload(*this, Base))
13234     return ExprError();
13235 
13236   SourceLocation Loc = Base->getExprLoc();
13237 
13238   // C++ [over.ref]p1:
13239   //
13240   //   [...] An expression x->m is interpreted as (x.operator->())->m
13241   //   for a class object x of type T if T::operator->() exists and if
13242   //   the operator is selected as the best match function by the
13243   //   overload resolution mechanism (13.3).
13244   DeclarationName OpName =
13245     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13246   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13247   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13248 
13249   if (RequireCompleteType(Loc, Base->getType(),
13250                           diag::err_typecheck_incomplete_tag, Base))
13251     return ExprError();
13252 
13253   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13254   LookupQualifiedName(R, BaseRecord->getDecl());
13255   R.suppressDiagnostics();
13256 
13257   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13258        Oper != OperEnd; ++Oper) {
13259     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13260                        None, CandidateSet, /*SuppressUserConversions=*/false);
13261   }
13262 
13263   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13264 
13265   // Perform overload resolution.
13266   OverloadCandidateSet::iterator Best;
13267   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13268   case OR_Success:
13269     // Overload resolution succeeded; we'll build the call below.
13270     break;
13271 
13272   case OR_No_Viable_Function:
13273     if (CandidateSet.empty()) {
13274       QualType BaseType = Base->getType();
13275       if (NoArrowOperatorFound) {
13276         // Report this specific error to the caller instead of emitting a
13277         // diagnostic, as requested.
13278         *NoArrowOperatorFound = true;
13279         return ExprError();
13280       }
13281       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13282         << BaseType << Base->getSourceRange();
13283       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13284         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13285           << FixItHint::CreateReplacement(OpLoc, ".");
13286       }
13287     } else
13288       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13289         << "operator->" << Base->getSourceRange();
13290     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13291     return ExprError();
13292 
13293   case OR_Ambiguous:
13294     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13295       << "->" << Base->getType() << Base->getSourceRange();
13296     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13297     return ExprError();
13298 
13299   case OR_Deleted:
13300     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13301       << Best->Function->isDeleted()
13302       << "->"
13303       << getDeletedOrUnavailableSuffix(Best->Function)
13304       << Base->getSourceRange();
13305     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13306     return ExprError();
13307   }
13308 
13309   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13310 
13311   // Convert the object parameter.
13312   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13313   ExprResult BaseResult =
13314     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13315                                         Best->FoundDecl, Method);
13316   if (BaseResult.isInvalid())
13317     return ExprError();
13318   Base = BaseResult.get();
13319 
13320   // Build the operator call.
13321   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13322                                             Base, HadMultipleCandidates, OpLoc);
13323   if (FnExpr.isInvalid())
13324     return ExprError();
13325 
13326   QualType ResultTy = Method->getReturnType();
13327   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13328   ResultTy = ResultTy.getNonLValueExprType(Context);
13329   CXXOperatorCallExpr *TheCall =
13330     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13331                                       Base, ResultTy, VK, OpLoc, FPOptions());
13332 
13333   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13334     return ExprError();
13335 
13336   if (CheckFunctionCall(Method, TheCall,
13337                         Method->getType()->castAs<FunctionProtoType>()))
13338     return ExprError();
13339 
13340   return MaybeBindToTemporary(TheCall);
13341 }
13342 
13343 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13344 /// a literal operator described by the provided lookup results.
13345 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13346                                           DeclarationNameInfo &SuffixInfo,
13347                                           ArrayRef<Expr*> Args,
13348                                           SourceLocation LitEndLoc,
13349                                        TemplateArgumentListInfo *TemplateArgs) {
13350   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13351 
13352   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13353                                     OverloadCandidateSet::CSK_Normal);
13354   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13355                         /*SuppressUserConversions=*/true);
13356 
13357   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13358 
13359   // Perform overload resolution. This will usually be trivial, but might need
13360   // to perform substitutions for a literal operator template.
13361   OverloadCandidateSet::iterator Best;
13362   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13363   case OR_Success:
13364   case OR_Deleted:
13365     break;
13366 
13367   case OR_No_Viable_Function:
13368     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13369       << R.getLookupName();
13370     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13371     return ExprError();
13372 
13373   case OR_Ambiguous:
13374     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13375     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13376     return ExprError();
13377   }
13378 
13379   FunctionDecl *FD = Best->Function;
13380   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13381                                         nullptr, HadMultipleCandidates,
13382                                         SuffixInfo.getLoc(),
13383                                         SuffixInfo.getInfo());
13384   if (Fn.isInvalid())
13385     return true;
13386 
13387   // Check the argument types. This should almost always be a no-op, except
13388   // that array-to-pointer decay is applied to string literals.
13389   Expr *ConvArgs[2];
13390   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13391     ExprResult InputInit = PerformCopyInitialization(
13392       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13393       SourceLocation(), Args[ArgIdx]);
13394     if (InputInit.isInvalid())
13395       return true;
13396     ConvArgs[ArgIdx] = InputInit.get();
13397   }
13398 
13399   QualType ResultTy = FD->getReturnType();
13400   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13401   ResultTy = ResultTy.getNonLValueExprType(Context);
13402 
13403   UserDefinedLiteral *UDL =
13404     new (Context) UserDefinedLiteral(Context, Fn.get(),
13405                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13406                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13407 
13408   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13409     return ExprError();
13410 
13411   if (CheckFunctionCall(FD, UDL, nullptr))
13412     return ExprError();
13413 
13414   return MaybeBindToTemporary(UDL);
13415 }
13416 
13417 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13418 /// given LookupResult is non-empty, it is assumed to describe a member which
13419 /// will be invoked. Otherwise, the function will be found via argument
13420 /// dependent lookup.
13421 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13422 /// otherwise CallExpr is set to ExprError() and some non-success value
13423 /// is returned.
13424 Sema::ForRangeStatus
13425 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13426                                 SourceLocation RangeLoc,
13427                                 const DeclarationNameInfo &NameInfo,
13428                                 LookupResult &MemberLookup,
13429                                 OverloadCandidateSet *CandidateSet,
13430                                 Expr *Range, ExprResult *CallExpr) {
13431   Scope *S = nullptr;
13432 
13433   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13434   if (!MemberLookup.empty()) {
13435     ExprResult MemberRef =
13436         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13437                                  /*IsPtr=*/false, CXXScopeSpec(),
13438                                  /*TemplateKWLoc=*/SourceLocation(),
13439                                  /*FirstQualifierInScope=*/nullptr,
13440                                  MemberLookup,
13441                                  /*TemplateArgs=*/nullptr, S);
13442     if (MemberRef.isInvalid()) {
13443       *CallExpr = ExprError();
13444       return FRS_DiagnosticIssued;
13445     }
13446     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13447     if (CallExpr->isInvalid()) {
13448       *CallExpr = ExprError();
13449       return FRS_DiagnosticIssued;
13450     }
13451   } else {
13452     UnresolvedSet<0> FoundNames;
13453     UnresolvedLookupExpr *Fn =
13454       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13455                                    NestedNameSpecifierLoc(), NameInfo,
13456                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13457                                    FoundNames.begin(), FoundNames.end());
13458 
13459     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13460                                                     CandidateSet, CallExpr);
13461     if (CandidateSet->empty() || CandidateSetError) {
13462       *CallExpr = ExprError();
13463       return FRS_NoViableFunction;
13464     }
13465     OverloadCandidateSet::iterator Best;
13466     OverloadingResult OverloadResult =
13467         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13468 
13469     if (OverloadResult == OR_No_Viable_Function) {
13470       *CallExpr = ExprError();
13471       return FRS_NoViableFunction;
13472     }
13473     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13474                                          Loc, nullptr, CandidateSet, &Best,
13475                                          OverloadResult,
13476                                          /*AllowTypoCorrection=*/false);
13477     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13478       *CallExpr = ExprError();
13479       return FRS_DiagnosticIssued;
13480     }
13481   }
13482   return FRS_Success;
13483 }
13484 
13485 
13486 /// FixOverloadedFunctionReference - E is an expression that refers to
13487 /// a C++ overloaded function (possibly with some parentheses and
13488 /// perhaps a '&' around it). We have resolved the overloaded function
13489 /// to the function declaration Fn, so patch up the expression E to
13490 /// refer (possibly indirectly) to Fn. Returns the new expr.
13491 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13492                                            FunctionDecl *Fn) {
13493   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13494     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13495                                                    Found, Fn);
13496     if (SubExpr == PE->getSubExpr())
13497       return PE;
13498 
13499     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13500   }
13501 
13502   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13503     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13504                                                    Found, Fn);
13505     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13506                                SubExpr->getType()) &&
13507            "Implicit cast type cannot be determined from overload");
13508     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13509     if (SubExpr == ICE->getSubExpr())
13510       return ICE;
13511 
13512     return ImplicitCastExpr::Create(Context, ICE->getType(),
13513                                     ICE->getCastKind(),
13514                                     SubExpr, nullptr,
13515                                     ICE->getValueKind());
13516   }
13517 
13518   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13519     if (!GSE->isResultDependent()) {
13520       Expr *SubExpr =
13521           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13522       if (SubExpr == GSE->getResultExpr())
13523         return GSE;
13524 
13525       // Replace the resulting type information before rebuilding the generic
13526       // selection expression.
13527       ArrayRef<Expr *> A = GSE->getAssocExprs();
13528       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13529       unsigned ResultIdx = GSE->getResultIndex();
13530       AssocExprs[ResultIdx] = SubExpr;
13531 
13532       return new (Context) GenericSelectionExpr(
13533           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13534           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13535           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13536           ResultIdx);
13537     }
13538     // Rather than fall through to the unreachable, return the original generic
13539     // selection expression.
13540     return GSE;
13541   }
13542 
13543   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13544     assert(UnOp->getOpcode() == UO_AddrOf &&
13545            "Can only take the address of an overloaded function");
13546     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13547       if (Method->isStatic()) {
13548         // Do nothing: static member functions aren't any different
13549         // from non-member functions.
13550       } else {
13551         // Fix the subexpression, which really has to be an
13552         // UnresolvedLookupExpr holding an overloaded member function
13553         // or template.
13554         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13555                                                        Found, Fn);
13556         if (SubExpr == UnOp->getSubExpr())
13557           return UnOp;
13558 
13559         assert(isa<DeclRefExpr>(SubExpr)
13560                && "fixed to something other than a decl ref");
13561         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13562                && "fixed to a member ref with no nested name qualifier");
13563 
13564         // We have taken the address of a pointer to member
13565         // function. Perform the computation here so that we get the
13566         // appropriate pointer to member type.
13567         QualType ClassType
13568           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13569         QualType MemPtrType
13570           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13571         // Under the MS ABI, lock down the inheritance model now.
13572         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13573           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13574 
13575         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13576                                            VK_RValue, OK_Ordinary,
13577                                            UnOp->getOperatorLoc(), false);
13578       }
13579     }
13580     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13581                                                    Found, Fn);
13582     if (SubExpr == UnOp->getSubExpr())
13583       return UnOp;
13584 
13585     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13586                                      Context.getPointerType(SubExpr->getType()),
13587                                        VK_RValue, OK_Ordinary,
13588                                        UnOp->getOperatorLoc(), false);
13589   }
13590 
13591   // C++ [except.spec]p17:
13592   //   An exception-specification is considered to be needed when:
13593   //   - in an expression the function is the unique lookup result or the
13594   //     selected member of a set of overloaded functions
13595   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13596     ResolveExceptionSpec(E->getExprLoc(), FPT);
13597 
13598   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13599     // FIXME: avoid copy.
13600     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13601     if (ULE->hasExplicitTemplateArgs()) {
13602       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13603       TemplateArgs = &TemplateArgsBuffer;
13604     }
13605 
13606     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13607                                            ULE->getQualifierLoc(),
13608                                            ULE->getTemplateKeywordLoc(),
13609                                            Fn,
13610                                            /*enclosing*/ false, // FIXME?
13611                                            ULE->getNameLoc(),
13612                                            Fn->getType(),
13613                                            VK_LValue,
13614                                            Found.getDecl(),
13615                                            TemplateArgs);
13616     MarkDeclRefReferenced(DRE);
13617     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13618     return DRE;
13619   }
13620 
13621   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13622     // FIXME: avoid copy.
13623     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13624     if (MemExpr->hasExplicitTemplateArgs()) {
13625       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13626       TemplateArgs = &TemplateArgsBuffer;
13627     }
13628 
13629     Expr *Base;
13630 
13631     // If we're filling in a static method where we used to have an
13632     // implicit member access, rewrite to a simple decl ref.
13633     if (MemExpr->isImplicitAccess()) {
13634       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13635         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13636                                                MemExpr->getQualifierLoc(),
13637                                                MemExpr->getTemplateKeywordLoc(),
13638                                                Fn,
13639                                                /*enclosing*/ false,
13640                                                MemExpr->getMemberLoc(),
13641                                                Fn->getType(),
13642                                                VK_LValue,
13643                                                Found.getDecl(),
13644                                                TemplateArgs);
13645         MarkDeclRefReferenced(DRE);
13646         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13647         return DRE;
13648       } else {
13649         SourceLocation Loc = MemExpr->getMemberLoc();
13650         if (MemExpr->getQualifier())
13651           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13652         CheckCXXThisCapture(Loc);
13653         Base = new (Context) CXXThisExpr(Loc,
13654                                          MemExpr->getBaseType(),
13655                                          /*isImplicit=*/true);
13656       }
13657     } else
13658       Base = MemExpr->getBase();
13659 
13660     ExprValueKind valueKind;
13661     QualType type;
13662     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13663       valueKind = VK_LValue;
13664       type = Fn->getType();
13665     } else {
13666       valueKind = VK_RValue;
13667       type = Context.BoundMemberTy;
13668     }
13669 
13670     MemberExpr *ME = MemberExpr::Create(
13671         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13672         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13673         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13674         OK_Ordinary);
13675     ME->setHadMultipleCandidates(true);
13676     MarkMemberReferenced(ME);
13677     return ME;
13678   }
13679 
13680   llvm_unreachable("Invalid reference to overloaded function");
13681 }
13682 
13683 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13684                                                 DeclAccessPair Found,
13685                                                 FunctionDecl *Fn) {
13686   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13687 }
13688