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(Context) && !ToFPT->isNothrow(Context)) {
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(Context) !=
2813       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2814           ->isNothrow(Context)) {
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     ArithmeticTypes.push_back(S.Context.Char16Ty);
7711     ArithmeticTypes.push_back(S.Context.Char32Ty);
7712     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7713     ArithmeticTypes.push_back(S.Context.ShortTy);
7714     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7715     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7716     LastIntegralType = ArithmeticTypes.size();
7717     NumArithmeticTypes = ArithmeticTypes.size();
7718     // End of integral types.
7719     // FIXME: What about complex? What about half?
7720 
7721     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7722            "Enough inline storage for all arithmetic types.");
7723   }
7724 
7725   /// \brief Helper method to factor out the common pattern of adding overloads
7726   /// for '++' and '--' builtin operators.
7727   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7728                                            bool HasVolatile,
7729                                            bool HasRestrict) {
7730     QualType ParamTypes[2] = {
7731       S.Context.getLValueReferenceType(CandidateTy),
7732       S.Context.IntTy
7733     };
7734 
7735     // Non-volatile version.
7736     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7737 
7738     // Use a heuristic to reduce number of builtin candidates in the set:
7739     // add volatile version only if there are conversions to a volatile type.
7740     if (HasVolatile) {
7741       ParamTypes[0] =
7742         S.Context.getLValueReferenceType(
7743           S.Context.getVolatileType(CandidateTy));
7744       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7745     }
7746 
7747     // Add restrict version only if there are conversions to a restrict type
7748     // and our candidate type is a non-restrict-qualified pointer.
7749     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7750         !CandidateTy.isRestrictQualified()) {
7751       ParamTypes[0]
7752         = S.Context.getLValueReferenceType(
7753             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7754       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7755 
7756       if (HasVolatile) {
7757         ParamTypes[0]
7758           = S.Context.getLValueReferenceType(
7759               S.Context.getCVRQualifiedType(CandidateTy,
7760                                             (Qualifiers::Volatile |
7761                                              Qualifiers::Restrict)));
7762         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7763       }
7764     }
7765 
7766   }
7767 
7768 public:
7769   BuiltinOperatorOverloadBuilder(
7770     Sema &S, ArrayRef<Expr *> Args,
7771     Qualifiers VisibleTypeConversionsQuals,
7772     bool HasArithmeticOrEnumeralCandidateType,
7773     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7774     OverloadCandidateSet &CandidateSet)
7775     : S(S), Args(Args),
7776       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7777       HasArithmeticOrEnumeralCandidateType(
7778         HasArithmeticOrEnumeralCandidateType),
7779       CandidateTypes(CandidateTypes),
7780       CandidateSet(CandidateSet) {
7781 
7782     InitArithmeticTypes();
7783   }
7784 
7785   // Increment is deprecated for bool since C++17.
7786   //
7787   // C++ [over.built]p3:
7788   //
7789   //   For every pair (T, VQ), where T is an arithmetic type other
7790   //   than bool, and VQ is either volatile or empty, there exist
7791   //   candidate operator functions of the form
7792   //
7793   //       VQ T&      operator++(VQ T&);
7794   //       T          operator++(VQ T&, int);
7795   //
7796   // C++ [over.built]p4:
7797   //
7798   //   For every pair (T, VQ), where T is an arithmetic type other
7799   //   than bool, and VQ is either volatile or empty, there exist
7800   //   candidate operator functions of the form
7801   //
7802   //       VQ T&      operator--(VQ T&);
7803   //       T          operator--(VQ T&, int);
7804   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7805     if (!HasArithmeticOrEnumeralCandidateType)
7806       return;
7807 
7808     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7809       const auto TypeOfT = ArithmeticTypes[Arith];
7810       if (TypeOfT == S.Context.BoolTy) {
7811         if (Op == OO_MinusMinus)
7812           continue;
7813         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7814           continue;
7815       }
7816       addPlusPlusMinusMinusStyleOverloads(
7817         TypeOfT,
7818         VisibleTypeConversionsQuals.hasVolatile(),
7819         VisibleTypeConversionsQuals.hasRestrict());
7820     }
7821   }
7822 
7823   // C++ [over.built]p5:
7824   //
7825   //   For every pair (T, VQ), where T is a cv-qualified or
7826   //   cv-unqualified object type, and VQ is either volatile or
7827   //   empty, there exist candidate operator functions of the form
7828   //
7829   //       T*VQ&      operator++(T*VQ&);
7830   //       T*VQ&      operator--(T*VQ&);
7831   //       T*         operator++(T*VQ&, int);
7832   //       T*         operator--(T*VQ&, int);
7833   void addPlusPlusMinusMinusPointerOverloads() {
7834     for (BuiltinCandidateTypeSet::iterator
7835               Ptr = CandidateTypes[0].pointer_begin(),
7836            PtrEnd = CandidateTypes[0].pointer_end();
7837          Ptr != PtrEnd; ++Ptr) {
7838       // Skip pointer types that aren't pointers to object types.
7839       if (!(*Ptr)->getPointeeType()->isObjectType())
7840         continue;
7841 
7842       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7843         (!(*Ptr).isVolatileQualified() &&
7844          VisibleTypeConversionsQuals.hasVolatile()),
7845         (!(*Ptr).isRestrictQualified() &&
7846          VisibleTypeConversionsQuals.hasRestrict()));
7847     }
7848   }
7849 
7850   // C++ [over.built]p6:
7851   //   For every cv-qualified or cv-unqualified object type T, there
7852   //   exist candidate operator functions of the form
7853   //
7854   //       T&         operator*(T*);
7855   //
7856   // C++ [over.built]p7:
7857   //   For every function type T that does not have cv-qualifiers or a
7858   //   ref-qualifier, there exist candidate operator functions of the form
7859   //       T&         operator*(T*);
7860   void addUnaryStarPointerOverloads() {
7861     for (BuiltinCandidateTypeSet::iterator
7862               Ptr = CandidateTypes[0].pointer_begin(),
7863            PtrEnd = CandidateTypes[0].pointer_end();
7864          Ptr != PtrEnd; ++Ptr) {
7865       QualType ParamTy = *Ptr;
7866       QualType PointeeTy = ParamTy->getPointeeType();
7867       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7868         continue;
7869 
7870       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7871         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7872           continue;
7873 
7874       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7875     }
7876   }
7877 
7878   // C++ [over.built]p9:
7879   //  For every promoted arithmetic type T, there exist candidate
7880   //  operator functions of the form
7881   //
7882   //       T         operator+(T);
7883   //       T         operator-(T);
7884   void addUnaryPlusOrMinusArithmeticOverloads() {
7885     if (!HasArithmeticOrEnumeralCandidateType)
7886       return;
7887 
7888     for (unsigned Arith = FirstPromotedArithmeticType;
7889          Arith < LastPromotedArithmeticType; ++Arith) {
7890       QualType ArithTy = ArithmeticTypes[Arith];
7891       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7892     }
7893 
7894     // Extension: We also add these operators for vector types.
7895     for (BuiltinCandidateTypeSet::iterator
7896               Vec = CandidateTypes[0].vector_begin(),
7897            VecEnd = CandidateTypes[0].vector_end();
7898          Vec != VecEnd; ++Vec) {
7899       QualType VecTy = *Vec;
7900       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7901     }
7902   }
7903 
7904   // C++ [over.built]p8:
7905   //   For every type T, there exist candidate operator functions of
7906   //   the form
7907   //
7908   //       T*         operator+(T*);
7909   void addUnaryPlusPointerOverloads() {
7910     for (BuiltinCandidateTypeSet::iterator
7911               Ptr = CandidateTypes[0].pointer_begin(),
7912            PtrEnd = CandidateTypes[0].pointer_end();
7913          Ptr != PtrEnd; ++Ptr) {
7914       QualType ParamTy = *Ptr;
7915       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7916     }
7917   }
7918 
7919   // C++ [over.built]p10:
7920   //   For every promoted integral type T, there exist candidate
7921   //   operator functions of the form
7922   //
7923   //        T         operator~(T);
7924   void addUnaryTildePromotedIntegralOverloads() {
7925     if (!HasArithmeticOrEnumeralCandidateType)
7926       return;
7927 
7928     for (unsigned Int = FirstPromotedIntegralType;
7929          Int < LastPromotedIntegralType; ++Int) {
7930       QualType IntTy = ArithmeticTypes[Int];
7931       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7932     }
7933 
7934     // Extension: We also add this operator for vector types.
7935     for (BuiltinCandidateTypeSet::iterator
7936               Vec = CandidateTypes[0].vector_begin(),
7937            VecEnd = CandidateTypes[0].vector_end();
7938          Vec != VecEnd; ++Vec) {
7939       QualType VecTy = *Vec;
7940       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7941     }
7942   }
7943 
7944   // C++ [over.match.oper]p16:
7945   //   For every pointer to member type T or type std::nullptr_t, there
7946   //   exist candidate operator functions of the form
7947   //
7948   //        bool operator==(T,T);
7949   //        bool operator!=(T,T);
7950   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7951     /// Set of (canonical) types that we've already handled.
7952     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7953 
7954     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7955       for (BuiltinCandidateTypeSet::iterator
7956                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7957              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7958            MemPtr != MemPtrEnd;
7959            ++MemPtr) {
7960         // Don't add the same builtin candidate twice.
7961         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7962           continue;
7963 
7964         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7965         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7966       }
7967 
7968       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7969         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7970         if (AddedTypes.insert(NullPtrTy).second) {
7971           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7972           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7973         }
7974       }
7975     }
7976   }
7977 
7978   // C++ [over.built]p15:
7979   //
7980   //   For every T, where T is an enumeration type or a pointer type,
7981   //   there exist candidate operator functions of the form
7982   //
7983   //        bool       operator<(T, T);
7984   //        bool       operator>(T, T);
7985   //        bool       operator<=(T, T);
7986   //        bool       operator>=(T, T);
7987   //        bool       operator==(T, T);
7988   //        bool       operator!=(T, T);
7989   void addRelationalPointerOrEnumeralOverloads() {
7990     // C++ [over.match.oper]p3:
7991     //   [...]the built-in candidates include all of the candidate operator
7992     //   functions defined in 13.6 that, compared to the given operator, [...]
7993     //   do not have the same parameter-type-list as any non-template non-member
7994     //   candidate.
7995     //
7996     // Note that in practice, this only affects enumeration types because there
7997     // aren't any built-in candidates of record type, and a user-defined operator
7998     // must have an operand of record or enumeration type. Also, the only other
7999     // overloaded operator with enumeration arguments, operator=,
8000     // cannot be overloaded for enumeration types, so this is the only place
8001     // where we must suppress candidates like this.
8002     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8003       UserDefinedBinaryOperators;
8004 
8005     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8006       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8007           CandidateTypes[ArgIdx].enumeration_end()) {
8008         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8009                                          CEnd = CandidateSet.end();
8010              C != CEnd; ++C) {
8011           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8012             continue;
8013 
8014           if (C->Function->isFunctionTemplateSpecialization())
8015             continue;
8016 
8017           QualType FirstParamType =
8018             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8019           QualType SecondParamType =
8020             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8021 
8022           // Skip if either parameter isn't of enumeral type.
8023           if (!FirstParamType->isEnumeralType() ||
8024               !SecondParamType->isEnumeralType())
8025             continue;
8026 
8027           // Add this operator to the set of known user-defined operators.
8028           UserDefinedBinaryOperators.insert(
8029             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8030                            S.Context.getCanonicalType(SecondParamType)));
8031         }
8032       }
8033     }
8034 
8035     /// Set of (canonical) types that we've already handled.
8036     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8037 
8038     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8039       for (BuiltinCandidateTypeSet::iterator
8040                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8041              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8042            Ptr != PtrEnd; ++Ptr) {
8043         // Don't add the same builtin candidate twice.
8044         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8045           continue;
8046 
8047         QualType ParamTypes[2] = { *Ptr, *Ptr };
8048         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8049       }
8050       for (BuiltinCandidateTypeSet::iterator
8051                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8052              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8053            Enum != EnumEnd; ++Enum) {
8054         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8055 
8056         // Don't add the same builtin candidate twice, or if a user defined
8057         // candidate exists.
8058         if (!AddedTypes.insert(CanonType).second ||
8059             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8060                                                             CanonType)))
8061           continue;
8062 
8063         QualType ParamTypes[2] = { *Enum, *Enum };
8064         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8065       }
8066     }
8067   }
8068 
8069   // C++ [over.built]p13:
8070   //
8071   //   For every cv-qualified or cv-unqualified object type T
8072   //   there exist candidate operator functions of the form
8073   //
8074   //      T*         operator+(T*, ptrdiff_t);
8075   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8076   //      T*         operator-(T*, ptrdiff_t);
8077   //      T*         operator+(ptrdiff_t, T*);
8078   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8079   //
8080   // C++ [over.built]p14:
8081   //
8082   //   For every T, where T is a pointer to object type, there
8083   //   exist candidate operator functions of the form
8084   //
8085   //      ptrdiff_t  operator-(T, T);
8086   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8087     /// Set of (canonical) types that we've already handled.
8088     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8089 
8090     for (int Arg = 0; Arg < 2; ++Arg) {
8091       QualType AsymmetricParamTypes[2] = {
8092         S.Context.getPointerDiffType(),
8093         S.Context.getPointerDiffType(),
8094       };
8095       for (BuiltinCandidateTypeSet::iterator
8096                 Ptr = CandidateTypes[Arg].pointer_begin(),
8097              PtrEnd = CandidateTypes[Arg].pointer_end();
8098            Ptr != PtrEnd; ++Ptr) {
8099         QualType PointeeTy = (*Ptr)->getPointeeType();
8100         if (!PointeeTy->isObjectType())
8101           continue;
8102 
8103         AsymmetricParamTypes[Arg] = *Ptr;
8104         if (Arg == 0 || Op == OO_Plus) {
8105           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8106           // T* operator+(ptrdiff_t, T*);
8107           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8108         }
8109         if (Op == OO_Minus) {
8110           // ptrdiff_t operator-(T, T);
8111           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8112             continue;
8113 
8114           QualType ParamTypes[2] = { *Ptr, *Ptr };
8115           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8116         }
8117       }
8118     }
8119   }
8120 
8121   // C++ [over.built]p12:
8122   //
8123   //   For every pair of promoted arithmetic types L and R, there
8124   //   exist candidate operator functions of the form
8125   //
8126   //        LR         operator*(L, R);
8127   //        LR         operator/(L, R);
8128   //        LR         operator+(L, R);
8129   //        LR         operator-(L, R);
8130   //        bool       operator<(L, R);
8131   //        bool       operator>(L, R);
8132   //        bool       operator<=(L, R);
8133   //        bool       operator>=(L, R);
8134   //        bool       operator==(L, R);
8135   //        bool       operator!=(L, R);
8136   //
8137   //   where LR is the result of the usual arithmetic conversions
8138   //   between types L and R.
8139   //
8140   // C++ [over.built]p24:
8141   //
8142   //   For every pair of promoted arithmetic types L and R, there exist
8143   //   candidate operator functions of the form
8144   //
8145   //        LR       operator?(bool, L, R);
8146   //
8147   //   where LR is the result of the usual arithmetic conversions
8148   //   between types L and R.
8149   // Our candidates ignore the first parameter.
8150   void addGenericBinaryArithmeticOverloads() {
8151     if (!HasArithmeticOrEnumeralCandidateType)
8152       return;
8153 
8154     for (unsigned Left = FirstPromotedArithmeticType;
8155          Left < LastPromotedArithmeticType; ++Left) {
8156       for (unsigned Right = FirstPromotedArithmeticType;
8157            Right < LastPromotedArithmeticType; ++Right) {
8158         QualType LandR[2] = { ArithmeticTypes[Left],
8159                               ArithmeticTypes[Right] };
8160         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8161       }
8162     }
8163 
8164     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8165     // conditional operator for vector types.
8166     for (BuiltinCandidateTypeSet::iterator
8167               Vec1 = CandidateTypes[0].vector_begin(),
8168            Vec1End = CandidateTypes[0].vector_end();
8169          Vec1 != Vec1End; ++Vec1) {
8170       for (BuiltinCandidateTypeSet::iterator
8171                 Vec2 = CandidateTypes[1].vector_begin(),
8172              Vec2End = CandidateTypes[1].vector_end();
8173            Vec2 != Vec2End; ++Vec2) {
8174         QualType LandR[2] = { *Vec1, *Vec2 };
8175         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8176       }
8177     }
8178   }
8179 
8180   // C++ [over.built]p17:
8181   //
8182   //   For every pair of promoted integral types L and R, there
8183   //   exist candidate operator functions of the form
8184   //
8185   //      LR         operator%(L, R);
8186   //      LR         operator&(L, R);
8187   //      LR         operator^(L, R);
8188   //      LR         operator|(L, R);
8189   //      L          operator<<(L, R);
8190   //      L          operator>>(L, R);
8191   //
8192   //   where LR is the result of the usual arithmetic conversions
8193   //   between types L and R.
8194   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8195     if (!HasArithmeticOrEnumeralCandidateType)
8196       return;
8197 
8198     for (unsigned Left = FirstPromotedIntegralType;
8199          Left < LastPromotedIntegralType; ++Left) {
8200       for (unsigned Right = FirstPromotedIntegralType;
8201            Right < LastPromotedIntegralType; ++Right) {
8202         QualType LandR[2] = { ArithmeticTypes[Left],
8203                               ArithmeticTypes[Right] };
8204         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8205       }
8206     }
8207   }
8208 
8209   // C++ [over.built]p20:
8210   //
8211   //   For every pair (T, VQ), where T is an enumeration or
8212   //   pointer to member type and VQ is either volatile or
8213   //   empty, there exist candidate operator functions of the form
8214   //
8215   //        VQ T&      operator=(VQ T&, T);
8216   void addAssignmentMemberPointerOrEnumeralOverloads() {
8217     /// Set of (canonical) types that we've already handled.
8218     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8219 
8220     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8221       for (BuiltinCandidateTypeSet::iterator
8222                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8223              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8224            Enum != EnumEnd; ++Enum) {
8225         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8226           continue;
8227 
8228         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8229       }
8230 
8231       for (BuiltinCandidateTypeSet::iterator
8232                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8233              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8234            MemPtr != MemPtrEnd; ++MemPtr) {
8235         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8236           continue;
8237 
8238         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8239       }
8240     }
8241   }
8242 
8243   // C++ [over.built]p19:
8244   //
8245   //   For every pair (T, VQ), where T is any type and VQ is either
8246   //   volatile or empty, there exist candidate operator functions
8247   //   of the form
8248   //
8249   //        T*VQ&      operator=(T*VQ&, T*);
8250   //
8251   // C++ [over.built]p21:
8252   //
8253   //   For every pair (T, VQ), where T is a cv-qualified or
8254   //   cv-unqualified object type and VQ is either volatile or
8255   //   empty, there exist candidate operator functions of the form
8256   //
8257   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8258   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8259   void addAssignmentPointerOverloads(bool isEqualOp) {
8260     /// Set of (canonical) types that we've already handled.
8261     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8262 
8263     for (BuiltinCandidateTypeSet::iterator
8264               Ptr = CandidateTypes[0].pointer_begin(),
8265            PtrEnd = CandidateTypes[0].pointer_end();
8266          Ptr != PtrEnd; ++Ptr) {
8267       // If this is operator=, keep track of the builtin candidates we added.
8268       if (isEqualOp)
8269         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8270       else if (!(*Ptr)->getPointeeType()->isObjectType())
8271         continue;
8272 
8273       // non-volatile version
8274       QualType ParamTypes[2] = {
8275         S.Context.getLValueReferenceType(*Ptr),
8276         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8277       };
8278       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8279                             /*IsAssigmentOperator=*/ isEqualOp);
8280 
8281       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8282                           VisibleTypeConversionsQuals.hasVolatile();
8283       if (NeedVolatile) {
8284         // volatile version
8285         ParamTypes[0] =
8286           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8287         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8288                               /*IsAssigmentOperator=*/isEqualOp);
8289       }
8290 
8291       if (!(*Ptr).isRestrictQualified() &&
8292           VisibleTypeConversionsQuals.hasRestrict()) {
8293         // restrict version
8294         ParamTypes[0]
8295           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8296         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8297                               /*IsAssigmentOperator=*/isEqualOp);
8298 
8299         if (NeedVolatile) {
8300           // volatile restrict version
8301           ParamTypes[0]
8302             = S.Context.getLValueReferenceType(
8303                 S.Context.getCVRQualifiedType(*Ptr,
8304                                               (Qualifiers::Volatile |
8305                                                Qualifiers::Restrict)));
8306           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8307                                 /*IsAssigmentOperator=*/isEqualOp);
8308         }
8309       }
8310     }
8311 
8312     if (isEqualOp) {
8313       for (BuiltinCandidateTypeSet::iterator
8314                 Ptr = CandidateTypes[1].pointer_begin(),
8315              PtrEnd = CandidateTypes[1].pointer_end();
8316            Ptr != PtrEnd; ++Ptr) {
8317         // Make sure we don't add the same candidate twice.
8318         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8319           continue;
8320 
8321         QualType ParamTypes[2] = {
8322           S.Context.getLValueReferenceType(*Ptr),
8323           *Ptr,
8324         };
8325 
8326         // non-volatile version
8327         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8328                               /*IsAssigmentOperator=*/true);
8329 
8330         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8331                            VisibleTypeConversionsQuals.hasVolatile();
8332         if (NeedVolatile) {
8333           // volatile version
8334           ParamTypes[0] =
8335             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8336           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8337                                 /*IsAssigmentOperator=*/true);
8338         }
8339 
8340         if (!(*Ptr).isRestrictQualified() &&
8341             VisibleTypeConversionsQuals.hasRestrict()) {
8342           // restrict version
8343           ParamTypes[0]
8344             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8345           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8346                                 /*IsAssigmentOperator=*/true);
8347 
8348           if (NeedVolatile) {
8349             // volatile restrict version
8350             ParamTypes[0]
8351               = S.Context.getLValueReferenceType(
8352                   S.Context.getCVRQualifiedType(*Ptr,
8353                                                 (Qualifiers::Volatile |
8354                                                  Qualifiers::Restrict)));
8355             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8356                                   /*IsAssigmentOperator=*/true);
8357           }
8358         }
8359       }
8360     }
8361   }
8362 
8363   // C++ [over.built]p18:
8364   //
8365   //   For every triple (L, VQ, R), where L is an arithmetic type,
8366   //   VQ is either volatile or empty, and R is a promoted
8367   //   arithmetic type, there exist candidate operator functions of
8368   //   the form
8369   //
8370   //        VQ L&      operator=(VQ L&, R);
8371   //        VQ L&      operator*=(VQ L&, R);
8372   //        VQ L&      operator/=(VQ L&, R);
8373   //        VQ L&      operator+=(VQ L&, R);
8374   //        VQ L&      operator-=(VQ L&, R);
8375   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8376     if (!HasArithmeticOrEnumeralCandidateType)
8377       return;
8378 
8379     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8380       for (unsigned Right = FirstPromotedArithmeticType;
8381            Right < LastPromotedArithmeticType; ++Right) {
8382         QualType ParamTypes[2];
8383         ParamTypes[1] = ArithmeticTypes[Right];
8384 
8385         // Add this built-in operator as a candidate (VQ is empty).
8386         ParamTypes[0] =
8387           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8388         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8389                               /*IsAssigmentOperator=*/isEqualOp);
8390 
8391         // Add this built-in operator as a candidate (VQ is 'volatile').
8392         if (VisibleTypeConversionsQuals.hasVolatile()) {
8393           ParamTypes[0] =
8394             S.Context.getVolatileType(ArithmeticTypes[Left]);
8395           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8396           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8397                                 /*IsAssigmentOperator=*/isEqualOp);
8398         }
8399       }
8400     }
8401 
8402     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8403     for (BuiltinCandidateTypeSet::iterator
8404               Vec1 = CandidateTypes[0].vector_begin(),
8405            Vec1End = CandidateTypes[0].vector_end();
8406          Vec1 != Vec1End; ++Vec1) {
8407       for (BuiltinCandidateTypeSet::iterator
8408                 Vec2 = CandidateTypes[1].vector_begin(),
8409              Vec2End = CandidateTypes[1].vector_end();
8410            Vec2 != Vec2End; ++Vec2) {
8411         QualType ParamTypes[2];
8412         ParamTypes[1] = *Vec2;
8413         // Add this built-in operator as a candidate (VQ is empty).
8414         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8415         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8416                               /*IsAssigmentOperator=*/isEqualOp);
8417 
8418         // Add this built-in operator as a candidate (VQ is 'volatile').
8419         if (VisibleTypeConversionsQuals.hasVolatile()) {
8420           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8421           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8422           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8423                                 /*IsAssigmentOperator=*/isEqualOp);
8424         }
8425       }
8426     }
8427   }
8428 
8429   // C++ [over.built]p22:
8430   //
8431   //   For every triple (L, VQ, R), where L is an integral type, VQ
8432   //   is either volatile or empty, and R is a promoted integral
8433   //   type, there exist candidate operator functions of the form
8434   //
8435   //        VQ L&       operator%=(VQ L&, R);
8436   //        VQ L&       operator<<=(VQ L&, R);
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   void addAssignmentIntegralOverloads() {
8442     if (!HasArithmeticOrEnumeralCandidateType)
8443       return;
8444 
8445     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8446       for (unsigned Right = FirstPromotedIntegralType;
8447            Right < LastPromotedIntegralType; ++Right) {
8448         QualType ParamTypes[2];
8449         ParamTypes[1] = ArithmeticTypes[Right];
8450 
8451         // Add this built-in operator as a candidate (VQ is empty).
8452         ParamTypes[0] =
8453           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8454         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8455         if (VisibleTypeConversionsQuals.hasVolatile()) {
8456           // Add this built-in operator as a candidate (VQ is 'volatile').
8457           ParamTypes[0] = ArithmeticTypes[Left];
8458           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8459           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8460           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8461         }
8462       }
8463     }
8464   }
8465 
8466   // C++ [over.operator]p23:
8467   //
8468   //   There also exist candidate operator functions of the form
8469   //
8470   //        bool        operator!(bool);
8471   //        bool        operator&&(bool, bool);
8472   //        bool        operator||(bool, bool);
8473   void addExclaimOverload() {
8474     QualType ParamTy = S.Context.BoolTy;
8475     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8476                           /*IsAssignmentOperator=*/false,
8477                           /*NumContextualBoolArguments=*/1);
8478   }
8479   void addAmpAmpOrPipePipeOverload() {
8480     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8481     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8482                           /*IsAssignmentOperator=*/false,
8483                           /*NumContextualBoolArguments=*/2);
8484   }
8485 
8486   // C++ [over.built]p13:
8487   //
8488   //   For every cv-qualified or cv-unqualified object type T there
8489   //   exist candidate operator functions of the form
8490   //
8491   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8492   //        T&         operator[](T*, ptrdiff_t);
8493   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8494   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8495   //        T&         operator[](ptrdiff_t, T*);
8496   void addSubscriptOverloads() {
8497     for (BuiltinCandidateTypeSet::iterator
8498               Ptr = CandidateTypes[0].pointer_begin(),
8499            PtrEnd = CandidateTypes[0].pointer_end();
8500          Ptr != PtrEnd; ++Ptr) {
8501       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8502       QualType PointeeType = (*Ptr)->getPointeeType();
8503       if (!PointeeType->isObjectType())
8504         continue;
8505 
8506       // T& operator[](T*, ptrdiff_t)
8507       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8508     }
8509 
8510     for (BuiltinCandidateTypeSet::iterator
8511               Ptr = CandidateTypes[1].pointer_begin(),
8512            PtrEnd = CandidateTypes[1].pointer_end();
8513          Ptr != PtrEnd; ++Ptr) {
8514       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8515       QualType PointeeType = (*Ptr)->getPointeeType();
8516       if (!PointeeType->isObjectType())
8517         continue;
8518 
8519       // T& operator[](ptrdiff_t, T*)
8520       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8521     }
8522   }
8523 
8524   // C++ [over.built]p11:
8525   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8526   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8527   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8528   //    there exist candidate operator functions of the form
8529   //
8530   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8531   //
8532   //    where CV12 is the union of CV1 and CV2.
8533   void addArrowStarOverloads() {
8534     for (BuiltinCandidateTypeSet::iterator
8535              Ptr = CandidateTypes[0].pointer_begin(),
8536            PtrEnd = CandidateTypes[0].pointer_end();
8537          Ptr != PtrEnd; ++Ptr) {
8538       QualType C1Ty = (*Ptr);
8539       QualType C1;
8540       QualifierCollector Q1;
8541       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8542       if (!isa<RecordType>(C1))
8543         continue;
8544       // heuristic to reduce number of builtin candidates in the set.
8545       // Add volatile/restrict version only if there are conversions to a
8546       // volatile/restrict type.
8547       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8548         continue;
8549       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8550         continue;
8551       for (BuiltinCandidateTypeSet::iterator
8552                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8553              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8554            MemPtr != MemPtrEnd; ++MemPtr) {
8555         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8556         QualType C2 = QualType(mptr->getClass(), 0);
8557         C2 = C2.getUnqualifiedType();
8558         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8559           break;
8560         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8561         // build CV12 T&
8562         QualType T = mptr->getPointeeType();
8563         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8564             T.isVolatileQualified())
8565           continue;
8566         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8567             T.isRestrictQualified())
8568           continue;
8569         T = Q1.apply(S.Context, T);
8570         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8571       }
8572     }
8573   }
8574 
8575   // Note that we don't consider the first argument, since it has been
8576   // contextually converted to bool long ago. The candidates below are
8577   // therefore added as binary.
8578   //
8579   // C++ [over.built]p25:
8580   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8581   //   enumeration type, there exist candidate operator functions of the form
8582   //
8583   //        T        operator?(bool, T, T);
8584   //
8585   void addConditionalOperatorOverloads() {
8586     /// Set of (canonical) types that we've already handled.
8587     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8588 
8589     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8590       for (BuiltinCandidateTypeSet::iterator
8591                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8592              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8593            Ptr != PtrEnd; ++Ptr) {
8594         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8595           continue;
8596 
8597         QualType ParamTypes[2] = { *Ptr, *Ptr };
8598         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8599       }
8600 
8601       for (BuiltinCandidateTypeSet::iterator
8602                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8603              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8604            MemPtr != MemPtrEnd; ++MemPtr) {
8605         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8606           continue;
8607 
8608         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8609         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8610       }
8611 
8612       if (S.getLangOpts().CPlusPlus11) {
8613         for (BuiltinCandidateTypeSet::iterator
8614                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8615                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8616              Enum != EnumEnd; ++Enum) {
8617           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8618             continue;
8619 
8620           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8621             continue;
8622 
8623           QualType ParamTypes[2] = { *Enum, *Enum };
8624           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8625         }
8626       }
8627     }
8628   }
8629 };
8630 
8631 } // end anonymous namespace
8632 
8633 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8634 /// operator overloads to the candidate set (C++ [over.built]), based
8635 /// on the operator @p Op and the arguments given. For example, if the
8636 /// operator is a binary '+', this routine might add "int
8637 /// operator+(int, int)" to cover integer addition.
8638 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8639                                         SourceLocation OpLoc,
8640                                         ArrayRef<Expr *> Args,
8641                                         OverloadCandidateSet &CandidateSet) {
8642   // Find all of the types that the arguments can convert to, but only
8643   // if the operator we're looking at has built-in operator candidates
8644   // that make use of these types. Also record whether we encounter non-record
8645   // candidate types or either arithmetic or enumeral candidate types.
8646   Qualifiers VisibleTypeConversionsQuals;
8647   VisibleTypeConversionsQuals.addConst();
8648   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8649     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8650 
8651   bool HasNonRecordCandidateType = false;
8652   bool HasArithmeticOrEnumeralCandidateType = false;
8653   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8654   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8655     CandidateTypes.emplace_back(*this);
8656     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8657                                                  OpLoc,
8658                                                  true,
8659                                                  (Op == OO_Exclaim ||
8660                                                   Op == OO_AmpAmp ||
8661                                                   Op == OO_PipePipe),
8662                                                  VisibleTypeConversionsQuals);
8663     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8664         CandidateTypes[ArgIdx].hasNonRecordTypes();
8665     HasArithmeticOrEnumeralCandidateType =
8666         HasArithmeticOrEnumeralCandidateType ||
8667         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8668   }
8669 
8670   // Exit early when no non-record types have been added to the candidate set
8671   // for any of the arguments to the operator.
8672   //
8673   // We can't exit early for !, ||, or &&, since there we have always have
8674   // 'bool' overloads.
8675   if (!HasNonRecordCandidateType &&
8676       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8677     return;
8678 
8679   // Setup an object to manage the common state for building overloads.
8680   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8681                                            VisibleTypeConversionsQuals,
8682                                            HasArithmeticOrEnumeralCandidateType,
8683                                            CandidateTypes, CandidateSet);
8684 
8685   // Dispatch over the operation to add in only those overloads which apply.
8686   switch (Op) {
8687   case OO_None:
8688   case NUM_OVERLOADED_OPERATORS:
8689     llvm_unreachable("Expected an overloaded operator");
8690 
8691   case OO_New:
8692   case OO_Delete:
8693   case OO_Array_New:
8694   case OO_Array_Delete:
8695   case OO_Call:
8696     llvm_unreachable(
8697                     "Special operators don't use AddBuiltinOperatorCandidates");
8698 
8699   case OO_Comma:
8700   case OO_Arrow:
8701   case OO_Coawait:
8702     // C++ [over.match.oper]p3:
8703     //   -- For the operator ',', the unary operator '&', the
8704     //      operator '->', or the operator 'co_await', the
8705     //      built-in candidates set is empty.
8706     break;
8707 
8708   case OO_Plus: // '+' is either unary or binary
8709     if (Args.size() == 1)
8710       OpBuilder.addUnaryPlusPointerOverloads();
8711     LLVM_FALLTHROUGH;
8712 
8713   case OO_Minus: // '-' is either unary or binary
8714     if (Args.size() == 1) {
8715       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8716     } else {
8717       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8718       OpBuilder.addGenericBinaryArithmeticOverloads();
8719     }
8720     break;
8721 
8722   case OO_Star: // '*' is either unary or binary
8723     if (Args.size() == 1)
8724       OpBuilder.addUnaryStarPointerOverloads();
8725     else
8726       OpBuilder.addGenericBinaryArithmeticOverloads();
8727     break;
8728 
8729   case OO_Slash:
8730     OpBuilder.addGenericBinaryArithmeticOverloads();
8731     break;
8732 
8733   case OO_PlusPlus:
8734   case OO_MinusMinus:
8735     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8736     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8737     break;
8738 
8739   case OO_EqualEqual:
8740   case OO_ExclaimEqual:
8741     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8742     LLVM_FALLTHROUGH;
8743 
8744   case OO_Less:
8745   case OO_Greater:
8746   case OO_LessEqual:
8747   case OO_GreaterEqual:
8748     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8749     OpBuilder.addGenericBinaryArithmeticOverloads();
8750     break;
8751 
8752   case OO_Spaceship:
8753     llvm_unreachable("<=> expressions not supported yet");
8754 
8755   case OO_Percent:
8756   case OO_Caret:
8757   case OO_Pipe:
8758   case OO_LessLess:
8759   case OO_GreaterGreater:
8760     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8761     break;
8762 
8763   case OO_Amp: // '&' is either unary or binary
8764     if (Args.size() == 1)
8765       // C++ [over.match.oper]p3:
8766       //   -- For the operator ',', the unary operator '&', or the
8767       //      operator '->', the built-in candidates set is empty.
8768       break;
8769 
8770     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8771     break;
8772 
8773   case OO_Tilde:
8774     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8775     break;
8776 
8777   case OO_Equal:
8778     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8779     LLVM_FALLTHROUGH;
8780 
8781   case OO_PlusEqual:
8782   case OO_MinusEqual:
8783     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8784     LLVM_FALLTHROUGH;
8785 
8786   case OO_StarEqual:
8787   case OO_SlashEqual:
8788     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8789     break;
8790 
8791   case OO_PercentEqual:
8792   case OO_LessLessEqual:
8793   case OO_GreaterGreaterEqual:
8794   case OO_AmpEqual:
8795   case OO_CaretEqual:
8796   case OO_PipeEqual:
8797     OpBuilder.addAssignmentIntegralOverloads();
8798     break;
8799 
8800   case OO_Exclaim:
8801     OpBuilder.addExclaimOverload();
8802     break;
8803 
8804   case OO_AmpAmp:
8805   case OO_PipePipe:
8806     OpBuilder.addAmpAmpOrPipePipeOverload();
8807     break;
8808 
8809   case OO_Subscript:
8810     OpBuilder.addSubscriptOverloads();
8811     break;
8812 
8813   case OO_ArrowStar:
8814     OpBuilder.addArrowStarOverloads();
8815     break;
8816 
8817   case OO_Conditional:
8818     OpBuilder.addConditionalOperatorOverloads();
8819     OpBuilder.addGenericBinaryArithmeticOverloads();
8820     break;
8821   }
8822 }
8823 
8824 /// \brief Add function candidates found via argument-dependent lookup
8825 /// to the set of overloading candidates.
8826 ///
8827 /// This routine performs argument-dependent name lookup based on the
8828 /// given function name (which may also be an operator name) and adds
8829 /// all of the overload candidates found by ADL to the overload
8830 /// candidate set (C++ [basic.lookup.argdep]).
8831 void
8832 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8833                                            SourceLocation Loc,
8834                                            ArrayRef<Expr *> Args,
8835                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8836                                            OverloadCandidateSet& CandidateSet,
8837                                            bool PartialOverloading) {
8838   ADLResult Fns;
8839 
8840   // FIXME: This approach for uniquing ADL results (and removing
8841   // redundant candidates from the set) relies on pointer-equality,
8842   // which means we need to key off the canonical decl.  However,
8843   // always going back to the canonical decl might not get us the
8844   // right set of default arguments.  What default arguments are
8845   // we supposed to consider on ADL candidates, anyway?
8846 
8847   // FIXME: Pass in the explicit template arguments?
8848   ArgumentDependentLookup(Name, Loc, Args, Fns);
8849 
8850   // Erase all of the candidates we already knew about.
8851   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8852                                    CandEnd = CandidateSet.end();
8853        Cand != CandEnd; ++Cand)
8854     if (Cand->Function) {
8855       Fns.erase(Cand->Function);
8856       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8857         Fns.erase(FunTmpl);
8858     }
8859 
8860   // For each of the ADL candidates we found, add it to the overload
8861   // set.
8862   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8863     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8864     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8865       if (ExplicitTemplateArgs)
8866         continue;
8867 
8868       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8869                            PartialOverloading);
8870     } else
8871       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8872                                    FoundDecl, ExplicitTemplateArgs,
8873                                    Args, CandidateSet, PartialOverloading);
8874   }
8875 }
8876 
8877 namespace {
8878 enum class Comparison { Equal, Better, Worse };
8879 }
8880 
8881 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8882 /// overload resolution.
8883 ///
8884 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8885 /// Cand1's first N enable_if attributes have precisely the same conditions as
8886 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8887 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8888 ///
8889 /// Note that you can have a pair of candidates such that Cand1's enable_if
8890 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8891 /// worse than Cand1's.
8892 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8893                                        const FunctionDecl *Cand2) {
8894   // Common case: One (or both) decls don't have enable_if attrs.
8895   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8896   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8897   if (!Cand1Attr || !Cand2Attr) {
8898     if (Cand1Attr == Cand2Attr)
8899       return Comparison::Equal;
8900     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8901   }
8902 
8903   // FIXME: The next several lines are just
8904   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8905   // instead of reverse order which is how they're stored in the AST.
8906   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8907   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8908 
8909   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8910   // has fewer enable_if attributes than Cand2.
8911   if (Cand1Attrs.size() < Cand2Attrs.size())
8912     return Comparison::Worse;
8913 
8914   auto Cand1I = Cand1Attrs.begin();
8915   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8916   for (auto &Cand2A : Cand2Attrs) {
8917     Cand1ID.clear();
8918     Cand2ID.clear();
8919 
8920     auto &Cand1A = *Cand1I++;
8921     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8922     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8923     if (Cand1ID != Cand2ID)
8924       return Comparison::Worse;
8925   }
8926 
8927   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8928 }
8929 
8930 /// isBetterOverloadCandidate - Determines whether the first overload
8931 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8932 bool clang::isBetterOverloadCandidate(
8933     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8934     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8935   // Define viable functions to be better candidates than non-viable
8936   // functions.
8937   if (!Cand2.Viable)
8938     return Cand1.Viable;
8939   else if (!Cand1.Viable)
8940     return false;
8941 
8942   // C++ [over.match.best]p1:
8943   //
8944   //   -- if F is a static member function, ICS1(F) is defined such
8945   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8946   //      any function G, and, symmetrically, ICS1(G) is neither
8947   //      better nor worse than ICS1(F).
8948   unsigned StartArg = 0;
8949   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8950     StartArg = 1;
8951 
8952   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8953     // We don't allow incompatible pointer conversions in C++.
8954     if (!S.getLangOpts().CPlusPlus)
8955       return ICS.isStandard() &&
8956              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8957 
8958     // The only ill-formed conversion we allow in C++ is the string literal to
8959     // char* conversion, which is only considered ill-formed after C++11.
8960     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8961            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8962   };
8963 
8964   // Define functions that don't require ill-formed conversions for a given
8965   // argument to be better candidates than functions that do.
8966   unsigned NumArgs = Cand1.Conversions.size();
8967   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8968   bool HasBetterConversion = false;
8969   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8970     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8971     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8972     if (Cand1Bad != Cand2Bad) {
8973       if (Cand1Bad)
8974         return false;
8975       HasBetterConversion = true;
8976     }
8977   }
8978 
8979   if (HasBetterConversion)
8980     return true;
8981 
8982   // C++ [over.match.best]p1:
8983   //   A viable function F1 is defined to be a better function than another
8984   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8985   //   conversion sequence than ICSi(F2), and then...
8986   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8987     switch (CompareImplicitConversionSequences(S, Loc,
8988                                                Cand1.Conversions[ArgIdx],
8989                                                Cand2.Conversions[ArgIdx])) {
8990     case ImplicitConversionSequence::Better:
8991       // Cand1 has a better conversion sequence.
8992       HasBetterConversion = true;
8993       break;
8994 
8995     case ImplicitConversionSequence::Worse:
8996       // Cand1 can't be better than Cand2.
8997       return false;
8998 
8999     case ImplicitConversionSequence::Indistinguishable:
9000       // Do nothing.
9001       break;
9002     }
9003   }
9004 
9005   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9006   //       ICSj(F2), or, if not that,
9007   if (HasBetterConversion)
9008     return true;
9009 
9010   //   -- the context is an initialization by user-defined conversion
9011   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9012   //      from the return type of F1 to the destination type (i.e.,
9013   //      the type of the entity being initialized) is a better
9014   //      conversion sequence than the standard conversion sequence
9015   //      from the return type of F2 to the destination type.
9016   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9017       Cand1.Function && Cand2.Function &&
9018       isa<CXXConversionDecl>(Cand1.Function) &&
9019       isa<CXXConversionDecl>(Cand2.Function)) {
9020     // First check whether we prefer one of the conversion functions over the
9021     // other. This only distinguishes the results in non-standard, extension
9022     // cases such as the conversion from a lambda closure type to a function
9023     // pointer or block.
9024     ImplicitConversionSequence::CompareKind Result =
9025         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9026     if (Result == ImplicitConversionSequence::Indistinguishable)
9027       Result = CompareStandardConversionSequences(S, Loc,
9028                                                   Cand1.FinalConversion,
9029                                                   Cand2.FinalConversion);
9030 
9031     if (Result != ImplicitConversionSequence::Indistinguishable)
9032       return Result == ImplicitConversionSequence::Better;
9033 
9034     // FIXME: Compare kind of reference binding if conversion functions
9035     // convert to a reference type used in direct reference binding, per
9036     // C++14 [over.match.best]p1 section 2 bullet 3.
9037   }
9038 
9039   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9040   // as combined with the resolution to CWG issue 243.
9041   //
9042   // When the context is initialization by constructor ([over.match.ctor] or
9043   // either phase of [over.match.list]), a constructor is preferred over
9044   // a conversion function.
9045   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9046       Cand1.Function && Cand2.Function &&
9047       isa<CXXConstructorDecl>(Cand1.Function) !=
9048           isa<CXXConstructorDecl>(Cand2.Function))
9049     return isa<CXXConstructorDecl>(Cand1.Function);
9050 
9051   //    -- F1 is a non-template function and F2 is a function template
9052   //       specialization, or, if not that,
9053   bool Cand1IsSpecialization = Cand1.Function &&
9054                                Cand1.Function->getPrimaryTemplate();
9055   bool Cand2IsSpecialization = Cand2.Function &&
9056                                Cand2.Function->getPrimaryTemplate();
9057   if (Cand1IsSpecialization != Cand2IsSpecialization)
9058     return Cand2IsSpecialization;
9059 
9060   //   -- F1 and F2 are function template specializations, and the function
9061   //      template for F1 is more specialized than the template for F2
9062   //      according to the partial ordering rules described in 14.5.5.2, or,
9063   //      if not that,
9064   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9065     if (FunctionTemplateDecl *BetterTemplate
9066           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9067                                          Cand2.Function->getPrimaryTemplate(),
9068                                          Loc,
9069                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9070                                                              : TPOC_Call,
9071                                          Cand1.ExplicitCallArguments,
9072                                          Cand2.ExplicitCallArguments))
9073       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9074   }
9075 
9076   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9077   // A derived-class constructor beats an (inherited) base class constructor.
9078   bool Cand1IsInherited =
9079       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9080   bool Cand2IsInherited =
9081       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9082   if (Cand1IsInherited != Cand2IsInherited)
9083     return Cand2IsInherited;
9084   else if (Cand1IsInherited) {
9085     assert(Cand2IsInherited);
9086     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9087     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9088     if (Cand1Class->isDerivedFrom(Cand2Class))
9089       return true;
9090     if (Cand2Class->isDerivedFrom(Cand1Class))
9091       return false;
9092     // Inherited from sibling base classes: still ambiguous.
9093   }
9094 
9095   // Check C++17 tie-breakers for deduction guides.
9096   {
9097     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9098     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9099     if (Guide1 && Guide2) {
9100       //  -- F1 is generated from a deduction-guide and F2 is not
9101       if (Guide1->isImplicit() != Guide2->isImplicit())
9102         return Guide2->isImplicit();
9103 
9104       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9105       if (Guide1->isCopyDeductionCandidate())
9106         return true;
9107     }
9108   }
9109 
9110   // Check for enable_if value-based overload resolution.
9111   if (Cand1.Function && Cand2.Function) {
9112     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9113     if (Cmp != Comparison::Equal)
9114       return Cmp == Comparison::Better;
9115   }
9116 
9117   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9118     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9119     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9120            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9121   }
9122 
9123   bool HasPS1 = Cand1.Function != nullptr &&
9124                 functionHasPassObjectSizeParams(Cand1.Function);
9125   bool HasPS2 = Cand2.Function != nullptr &&
9126                 functionHasPassObjectSizeParams(Cand2.Function);
9127   return HasPS1 != HasPS2 && HasPS1;
9128 }
9129 
9130 /// Determine whether two declarations are "equivalent" for the purposes of
9131 /// name lookup and overload resolution. This applies when the same internal/no
9132 /// linkage entity is defined by two modules (probably by textually including
9133 /// the same header). In such a case, we don't consider the declarations to
9134 /// declare the same entity, but we also don't want lookups with both
9135 /// declarations visible to be ambiguous in some cases (this happens when using
9136 /// a modularized libstdc++).
9137 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9138                                                   const NamedDecl *B) {
9139   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9140   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9141   if (!VA || !VB)
9142     return false;
9143 
9144   // The declarations must be declaring the same name as an internal linkage
9145   // entity in different modules.
9146   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9147           VB->getDeclContext()->getRedeclContext()) ||
9148       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9149           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9150       VA->isExternallyVisible() || VB->isExternallyVisible())
9151     return false;
9152 
9153   // Check that the declarations appear to be equivalent.
9154   //
9155   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9156   // For constants and functions, we should check the initializer or body is
9157   // the same. For non-constant variables, we shouldn't allow it at all.
9158   if (Context.hasSameType(VA->getType(), VB->getType()))
9159     return true;
9160 
9161   // Enum constants within unnamed enumerations will have different types, but
9162   // may still be similar enough to be interchangeable for our purposes.
9163   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9164     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9165       // Only handle anonymous enums. If the enumerations were named and
9166       // equivalent, they would have been merged to the same type.
9167       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9168       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9169       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9170           !Context.hasSameType(EnumA->getIntegerType(),
9171                                EnumB->getIntegerType()))
9172         return false;
9173       // Allow this only if the value is the same for both enumerators.
9174       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9175     }
9176   }
9177 
9178   // Nothing else is sufficiently similar.
9179   return false;
9180 }
9181 
9182 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9183     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9184   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9185 
9186   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9187   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9188       << !M << (M ? M->getFullModuleName() : "");
9189 
9190   for (auto *E : Equiv) {
9191     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9192     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9193         << !M << (M ? M->getFullModuleName() : "");
9194   }
9195 }
9196 
9197 /// \brief Computes the best viable function (C++ 13.3.3)
9198 /// within an overload candidate set.
9199 ///
9200 /// \param Loc The location of the function name (or operator symbol) for
9201 /// which overload resolution occurs.
9202 ///
9203 /// \param Best If overload resolution was successful or found a deleted
9204 /// function, \p Best points to the candidate function found.
9205 ///
9206 /// \returns The result of overload resolution.
9207 OverloadingResult
9208 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9209                                          iterator &Best) {
9210   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9211   std::transform(begin(), end(), std::back_inserter(Candidates),
9212                  [](OverloadCandidate &Cand) { return &Cand; });
9213 
9214   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9215   // are accepted by both clang and NVCC. However, during a particular
9216   // compilation mode only one call variant is viable. We need to
9217   // exclude non-viable overload candidates from consideration based
9218   // only on their host/device attributes. Specifically, if one
9219   // candidate call is WrongSide and the other is SameSide, we ignore
9220   // the WrongSide candidate.
9221   if (S.getLangOpts().CUDA) {
9222     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9223     bool ContainsSameSideCandidate =
9224         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9225           return Cand->Function &&
9226                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9227                      Sema::CFP_SameSide;
9228         });
9229     if (ContainsSameSideCandidate) {
9230       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9231         return Cand->Function &&
9232                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9233                    Sema::CFP_WrongSide;
9234       };
9235       llvm::erase_if(Candidates, IsWrongSideCandidate);
9236     }
9237   }
9238 
9239   // Find the best viable function.
9240   Best = end();
9241   for (auto *Cand : Candidates)
9242     if (Cand->Viable)
9243       if (Best == end() ||
9244           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9245         Best = Cand;
9246 
9247   // If we didn't find any viable functions, abort.
9248   if (Best == end())
9249     return OR_No_Viable_Function;
9250 
9251   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9252 
9253   // Make sure that this function is better than every other viable
9254   // function. If not, we have an ambiguity.
9255   for (auto *Cand : Candidates) {
9256     if (Cand->Viable && Cand != Best &&
9257         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9258       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9259                                                    Cand->Function)) {
9260         EquivalentCands.push_back(Cand->Function);
9261         continue;
9262       }
9263 
9264       Best = end();
9265       return OR_Ambiguous;
9266     }
9267   }
9268 
9269   // Best is the best viable function.
9270   if (Best->Function &&
9271       (Best->Function->isDeleted() ||
9272        S.isFunctionConsideredUnavailable(Best->Function)))
9273     return OR_Deleted;
9274 
9275   if (!EquivalentCands.empty())
9276     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9277                                                     EquivalentCands);
9278 
9279   return OR_Success;
9280 }
9281 
9282 namespace {
9283 
9284 enum OverloadCandidateKind {
9285   oc_function,
9286   oc_method,
9287   oc_constructor,
9288   oc_function_template,
9289   oc_method_template,
9290   oc_constructor_template,
9291   oc_implicit_default_constructor,
9292   oc_implicit_copy_constructor,
9293   oc_implicit_move_constructor,
9294   oc_implicit_copy_assignment,
9295   oc_implicit_move_assignment,
9296   oc_inherited_constructor,
9297   oc_inherited_constructor_template
9298 };
9299 
9300 static OverloadCandidateKind
9301 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9302                           std::string &Description) {
9303   bool isTemplate = false;
9304 
9305   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9306     isTemplate = true;
9307     Description = S.getTemplateArgumentBindingsText(
9308       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9309   }
9310 
9311   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9312     if (!Ctor->isImplicit()) {
9313       if (isa<ConstructorUsingShadowDecl>(Found))
9314         return isTemplate ? oc_inherited_constructor_template
9315                           : oc_inherited_constructor;
9316       else
9317         return isTemplate ? oc_constructor_template : oc_constructor;
9318     }
9319 
9320     if (Ctor->isDefaultConstructor())
9321       return oc_implicit_default_constructor;
9322 
9323     if (Ctor->isMoveConstructor())
9324       return oc_implicit_move_constructor;
9325 
9326     assert(Ctor->isCopyConstructor() &&
9327            "unexpected sort of implicit constructor");
9328     return oc_implicit_copy_constructor;
9329   }
9330 
9331   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9332     // This actually gets spelled 'candidate function' for now, but
9333     // it doesn't hurt to split it out.
9334     if (!Meth->isImplicit())
9335       return isTemplate ? oc_method_template : oc_method;
9336 
9337     if (Meth->isMoveAssignmentOperator())
9338       return oc_implicit_move_assignment;
9339 
9340     if (Meth->isCopyAssignmentOperator())
9341       return oc_implicit_copy_assignment;
9342 
9343     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9344     return oc_method;
9345   }
9346 
9347   return isTemplate ? oc_function_template : oc_function;
9348 }
9349 
9350 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9351   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9352   // set.
9353   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9354     S.Diag(FoundDecl->getLocation(),
9355            diag::note_ovl_candidate_inherited_constructor)
9356       << Shadow->getNominatedBaseClass();
9357 }
9358 
9359 } // end anonymous namespace
9360 
9361 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9362                                     const FunctionDecl *FD) {
9363   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9364     bool AlwaysTrue;
9365     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9366       return false;
9367     if (!AlwaysTrue)
9368       return false;
9369   }
9370   return true;
9371 }
9372 
9373 /// \brief Returns true if we can take the address of the function.
9374 ///
9375 /// \param Complain - If true, we'll emit a diagnostic
9376 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9377 ///   we in overload resolution?
9378 /// \param Loc - The location of the statement we're complaining about. Ignored
9379 ///   if we're not complaining, or if we're in overload resolution.
9380 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9381                                               bool Complain,
9382                                               bool InOverloadResolution,
9383                                               SourceLocation Loc) {
9384   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9385     if (Complain) {
9386       if (InOverloadResolution)
9387         S.Diag(FD->getLocStart(),
9388                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9389       else
9390         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9391     }
9392     return false;
9393   }
9394 
9395   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9396     return P->hasAttr<PassObjectSizeAttr>();
9397   });
9398   if (I == FD->param_end())
9399     return true;
9400 
9401   if (Complain) {
9402     // Add one to ParamNo because it's user-facing
9403     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9404     if (InOverloadResolution)
9405       S.Diag(FD->getLocation(),
9406              diag::note_ovl_candidate_has_pass_object_size_params)
9407           << ParamNo;
9408     else
9409       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9410           << FD << ParamNo;
9411   }
9412   return false;
9413 }
9414 
9415 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9416                                                const FunctionDecl *FD) {
9417   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9418                                            /*InOverloadResolution=*/true,
9419                                            /*Loc=*/SourceLocation());
9420 }
9421 
9422 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9423                                              bool Complain,
9424                                              SourceLocation Loc) {
9425   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9426                                              /*InOverloadResolution=*/false,
9427                                              Loc);
9428 }
9429 
9430 // Notes the location of an overload candidate.
9431 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9432                                  QualType DestType, bool TakingAddress) {
9433   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9434     return;
9435   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9436     return;
9437 
9438   std::string FnDesc;
9439   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9440   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9441                              << (unsigned) K << Fn << FnDesc;
9442 
9443   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9444   Diag(Fn->getLocation(), PD);
9445   MaybeEmitInheritedConstructorNote(*this, Found);
9446 }
9447 
9448 // Notes the location of all overload candidates designated through
9449 // OverloadedExpr
9450 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9451                                      bool TakingAddress) {
9452   assert(OverloadedExpr->getType() == Context.OverloadTy);
9453 
9454   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9455   OverloadExpr *OvlExpr = Ovl.Expression;
9456 
9457   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9458                             IEnd = OvlExpr->decls_end();
9459        I != IEnd; ++I) {
9460     if (FunctionTemplateDecl *FunTmpl =
9461                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9462       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9463                             TakingAddress);
9464     } else if (FunctionDecl *Fun
9465                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9466       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9467     }
9468   }
9469 }
9470 
9471 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9472 /// "lead" diagnostic; it will be given two arguments, the source and
9473 /// target types of the conversion.
9474 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9475                                  Sema &S,
9476                                  SourceLocation CaretLoc,
9477                                  const PartialDiagnostic &PDiag) const {
9478   S.Diag(CaretLoc, PDiag)
9479     << Ambiguous.getFromType() << Ambiguous.getToType();
9480   // FIXME: The note limiting machinery is borrowed from
9481   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9482   // refactoring here.
9483   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9484   unsigned CandsShown = 0;
9485   AmbiguousConversionSequence::const_iterator I, E;
9486   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9487     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9488       break;
9489     ++CandsShown;
9490     S.NoteOverloadCandidate(I->first, I->second);
9491   }
9492   if (I != E)
9493     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9494 }
9495 
9496 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9497                                   unsigned I, bool TakingCandidateAddress) {
9498   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9499   assert(Conv.isBad());
9500   assert(Cand->Function && "for now, candidate must be a function");
9501   FunctionDecl *Fn = Cand->Function;
9502 
9503   // There's a conversion slot for the object argument if this is a
9504   // non-constructor method.  Note that 'I' corresponds the
9505   // conversion-slot index.
9506   bool isObjectArgument = false;
9507   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9508     if (I == 0)
9509       isObjectArgument = true;
9510     else
9511       I--;
9512   }
9513 
9514   std::string FnDesc;
9515   OverloadCandidateKind FnKind =
9516       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9517 
9518   Expr *FromExpr = Conv.Bad.FromExpr;
9519   QualType FromTy = Conv.Bad.getFromType();
9520   QualType ToTy = Conv.Bad.getToType();
9521 
9522   if (FromTy == S.Context.OverloadTy) {
9523     assert(FromExpr && "overload set argument came from implicit argument?");
9524     Expr *E = FromExpr->IgnoreParens();
9525     if (isa<UnaryOperator>(E))
9526       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9527     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9528 
9529     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9530       << (unsigned) FnKind << FnDesc
9531       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9532       << ToTy << Name << I+1;
9533     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9534     return;
9535   }
9536 
9537   // Do some hand-waving analysis to see if the non-viability is due
9538   // to a qualifier mismatch.
9539   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9540   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9541   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9542     CToTy = RT->getPointeeType();
9543   else {
9544     // TODO: detect and diagnose the full richness of const mismatches.
9545     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9546       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9547         CFromTy = FromPT->getPointeeType();
9548         CToTy = ToPT->getPointeeType();
9549       }
9550   }
9551 
9552   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9553       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9554     Qualifiers FromQs = CFromTy.getQualifiers();
9555     Qualifiers ToQs = CToTy.getQualifiers();
9556 
9557     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9558       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9559         << (unsigned) FnKind << FnDesc
9560         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9561         << FromTy
9562         << FromQs.getAddressSpaceAttributePrintValue()
9563         << ToQs.getAddressSpaceAttributePrintValue()
9564         << (unsigned) isObjectArgument << I+1;
9565       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9566       return;
9567     }
9568 
9569     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9570       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9571         << (unsigned) FnKind << FnDesc
9572         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9573         << FromTy
9574         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9575         << (unsigned) isObjectArgument << I+1;
9576       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9577       return;
9578     }
9579 
9580     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9581       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9582       << (unsigned) FnKind << FnDesc
9583       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9584       << FromTy
9585       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9586       << (unsigned) isObjectArgument << I+1;
9587       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9588       return;
9589     }
9590 
9591     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9592       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9593         << (unsigned) FnKind << FnDesc
9594         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9595         << FromTy << FromQs.hasUnaligned() << I+1;
9596       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9597       return;
9598     }
9599 
9600     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9601     assert(CVR && "unexpected qualifiers mismatch");
9602 
9603     if (isObjectArgument) {
9604       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9605         << (unsigned) FnKind << FnDesc
9606         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9607         << FromTy << (CVR - 1);
9608     } else {
9609       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9610         << (unsigned) FnKind << FnDesc
9611         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9612         << FromTy << (CVR - 1) << I+1;
9613     }
9614     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9615     return;
9616   }
9617 
9618   // Special diagnostic for failure to convert an initializer list, since
9619   // telling the user that it has type void is not useful.
9620   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9621     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9622       << (unsigned) FnKind << FnDesc
9623       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9624       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9625     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9626     return;
9627   }
9628 
9629   // Diagnose references or pointers to incomplete types differently,
9630   // since it's far from impossible that the incompleteness triggered
9631   // the failure.
9632   QualType TempFromTy = FromTy.getNonReferenceType();
9633   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9634     TempFromTy = PTy->getPointeeType();
9635   if (TempFromTy->isIncompleteType()) {
9636     // Emit the generic diagnostic and, optionally, add the hints to it.
9637     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9638       << (unsigned) FnKind << FnDesc
9639       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9640       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9641       << (unsigned) (Cand->Fix.Kind);
9642 
9643     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9644     return;
9645   }
9646 
9647   // Diagnose base -> derived pointer conversions.
9648   unsigned BaseToDerivedConversion = 0;
9649   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9650     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9651       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9652                                                FromPtrTy->getPointeeType()) &&
9653           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9654           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9655           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9656                           FromPtrTy->getPointeeType()))
9657         BaseToDerivedConversion = 1;
9658     }
9659   } else if (const ObjCObjectPointerType *FromPtrTy
9660                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9661     if (const ObjCObjectPointerType *ToPtrTy
9662                                         = ToTy->getAs<ObjCObjectPointerType>())
9663       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9664         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9665           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9666                                                 FromPtrTy->getPointeeType()) &&
9667               FromIface->isSuperClassOf(ToIface))
9668             BaseToDerivedConversion = 2;
9669   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9670     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9671         !FromTy->isIncompleteType() &&
9672         !ToRefTy->getPointeeType()->isIncompleteType() &&
9673         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9674       BaseToDerivedConversion = 3;
9675     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9676                ToTy.getNonReferenceType().getCanonicalType() ==
9677                FromTy.getNonReferenceType().getCanonicalType()) {
9678       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9679         << (unsigned) FnKind << FnDesc
9680         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9681         << (unsigned) isObjectArgument << I + 1;
9682       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9683       return;
9684     }
9685   }
9686 
9687   if (BaseToDerivedConversion) {
9688     S.Diag(Fn->getLocation(),
9689            diag::note_ovl_candidate_bad_base_to_derived_conv)
9690       << (unsigned) FnKind << FnDesc
9691       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9692       << (BaseToDerivedConversion - 1)
9693       << FromTy << ToTy << I+1;
9694     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9695     return;
9696   }
9697 
9698   if (isa<ObjCObjectPointerType>(CFromTy) &&
9699       isa<PointerType>(CToTy)) {
9700       Qualifiers FromQs = CFromTy.getQualifiers();
9701       Qualifiers ToQs = CToTy.getQualifiers();
9702       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9703         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9704         << (unsigned) FnKind << FnDesc
9705         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9706         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9707         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9708         return;
9709       }
9710   }
9711 
9712   if (TakingCandidateAddress &&
9713       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9714     return;
9715 
9716   // Emit the generic diagnostic and, optionally, add the hints to it.
9717   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9718   FDiag << (unsigned) FnKind << FnDesc
9719     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9720     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9721     << (unsigned) (Cand->Fix.Kind);
9722 
9723   // If we can fix the conversion, suggest the FixIts.
9724   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9725        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9726     FDiag << *HI;
9727   S.Diag(Fn->getLocation(), FDiag);
9728 
9729   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9730 }
9731 
9732 /// Additional arity mismatch diagnosis specific to a function overload
9733 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9734 /// over a candidate in any candidate set.
9735 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9736                                unsigned NumArgs) {
9737   FunctionDecl *Fn = Cand->Function;
9738   unsigned MinParams = Fn->getMinRequiredArguments();
9739 
9740   // With invalid overloaded operators, it's possible that we think we
9741   // have an arity mismatch when in fact it looks like we have the
9742   // right number of arguments, because only overloaded operators have
9743   // the weird behavior of overloading member and non-member functions.
9744   // Just don't report anything.
9745   if (Fn->isInvalidDecl() &&
9746       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9747     return true;
9748 
9749   if (NumArgs < MinParams) {
9750     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9751            (Cand->FailureKind == ovl_fail_bad_deduction &&
9752             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9753   } else {
9754     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9755            (Cand->FailureKind == ovl_fail_bad_deduction &&
9756             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9757   }
9758 
9759   return false;
9760 }
9761 
9762 /// General arity mismatch diagnosis over a candidate in a candidate set.
9763 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9764                                   unsigned NumFormalArgs) {
9765   assert(isa<FunctionDecl>(D) &&
9766       "The templated declaration should at least be a function"
9767       " when diagnosing bad template argument deduction due to too many"
9768       " or too few arguments");
9769 
9770   FunctionDecl *Fn = cast<FunctionDecl>(D);
9771 
9772   // TODO: treat calls to a missing default constructor as a special case
9773   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9774   unsigned MinParams = Fn->getMinRequiredArguments();
9775 
9776   // at least / at most / exactly
9777   unsigned mode, modeCount;
9778   if (NumFormalArgs < MinParams) {
9779     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9780         FnTy->isTemplateVariadic())
9781       mode = 0; // "at least"
9782     else
9783       mode = 2; // "exactly"
9784     modeCount = MinParams;
9785   } else {
9786     if (MinParams != FnTy->getNumParams())
9787       mode = 1; // "at most"
9788     else
9789       mode = 2; // "exactly"
9790     modeCount = FnTy->getNumParams();
9791   }
9792 
9793   std::string Description;
9794   OverloadCandidateKind FnKind =
9795       ClassifyOverloadCandidate(S, Found, Fn, Description);
9796 
9797   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9798     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9799       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9800       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9801   else
9802     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9803       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9804       << mode << modeCount << NumFormalArgs;
9805   MaybeEmitInheritedConstructorNote(S, Found);
9806 }
9807 
9808 /// Arity mismatch diagnosis specific to a function overload candidate.
9809 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9810                                   unsigned NumFormalArgs) {
9811   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9812     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9813 }
9814 
9815 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9816   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9817     return TD;
9818   llvm_unreachable("Unsupported: Getting the described template declaration"
9819                    " for bad deduction diagnosis");
9820 }
9821 
9822 /// Diagnose a failed template-argument deduction.
9823 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9824                                  DeductionFailureInfo &DeductionFailure,
9825                                  unsigned NumArgs,
9826                                  bool TakingCandidateAddress) {
9827   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9828   NamedDecl *ParamD;
9829   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9830   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9831   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9832   switch (DeductionFailure.Result) {
9833   case Sema::TDK_Success:
9834     llvm_unreachable("TDK_success while diagnosing bad deduction");
9835 
9836   case Sema::TDK_Incomplete: {
9837     assert(ParamD && "no parameter found for incomplete deduction result");
9838     S.Diag(Templated->getLocation(),
9839            diag::note_ovl_candidate_incomplete_deduction)
9840         << ParamD->getDeclName();
9841     MaybeEmitInheritedConstructorNote(S, Found);
9842     return;
9843   }
9844 
9845   case Sema::TDK_Underqualified: {
9846     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9847     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9848 
9849     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9850 
9851     // Param will have been canonicalized, but it should just be a
9852     // qualified version of ParamD, so move the qualifiers to that.
9853     QualifierCollector Qs;
9854     Qs.strip(Param);
9855     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9856     assert(S.Context.hasSameType(Param, NonCanonParam));
9857 
9858     // Arg has also been canonicalized, but there's nothing we can do
9859     // about that.  It also doesn't matter as much, because it won't
9860     // have any template parameters in it (because deduction isn't
9861     // done on dependent types).
9862     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9863 
9864     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9865         << ParamD->getDeclName() << Arg << NonCanonParam;
9866     MaybeEmitInheritedConstructorNote(S, Found);
9867     return;
9868   }
9869 
9870   case Sema::TDK_Inconsistent: {
9871     assert(ParamD && "no parameter found for inconsistent deduction result");
9872     int which = 0;
9873     if (isa<TemplateTypeParmDecl>(ParamD))
9874       which = 0;
9875     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9876       // Deduction might have failed because we deduced arguments of two
9877       // different types for a non-type template parameter.
9878       // FIXME: Use a different TDK value for this.
9879       QualType T1 =
9880           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9881       QualType T2 =
9882           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9883       if (!S.Context.hasSameType(T1, T2)) {
9884         S.Diag(Templated->getLocation(),
9885                diag::note_ovl_candidate_inconsistent_deduction_types)
9886           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9887           << *DeductionFailure.getSecondArg() << T2;
9888         MaybeEmitInheritedConstructorNote(S, Found);
9889         return;
9890       }
9891 
9892       which = 1;
9893     } else {
9894       which = 2;
9895     }
9896 
9897     S.Diag(Templated->getLocation(),
9898            diag::note_ovl_candidate_inconsistent_deduction)
9899         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9900         << *DeductionFailure.getSecondArg();
9901     MaybeEmitInheritedConstructorNote(S, Found);
9902     return;
9903   }
9904 
9905   case Sema::TDK_InvalidExplicitArguments:
9906     assert(ParamD && "no parameter found for invalid explicit arguments");
9907     if (ParamD->getDeclName())
9908       S.Diag(Templated->getLocation(),
9909              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9910           << ParamD->getDeclName();
9911     else {
9912       int index = 0;
9913       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9914         index = TTP->getIndex();
9915       else if (NonTypeTemplateParmDecl *NTTP
9916                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9917         index = NTTP->getIndex();
9918       else
9919         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9920       S.Diag(Templated->getLocation(),
9921              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9922           << (index + 1);
9923     }
9924     MaybeEmitInheritedConstructorNote(S, Found);
9925     return;
9926 
9927   case Sema::TDK_TooManyArguments:
9928   case Sema::TDK_TooFewArguments:
9929     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9930     return;
9931 
9932   case Sema::TDK_InstantiationDepth:
9933     S.Diag(Templated->getLocation(),
9934            diag::note_ovl_candidate_instantiation_depth);
9935     MaybeEmitInheritedConstructorNote(S, Found);
9936     return;
9937 
9938   case Sema::TDK_SubstitutionFailure: {
9939     // Format the template argument list into the argument string.
9940     SmallString<128> TemplateArgString;
9941     if (TemplateArgumentList *Args =
9942             DeductionFailure.getTemplateArgumentList()) {
9943       TemplateArgString = " ";
9944       TemplateArgString += S.getTemplateArgumentBindingsText(
9945           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9946     }
9947 
9948     // If this candidate was disabled by enable_if, say so.
9949     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9950     if (PDiag && PDiag->second.getDiagID() ==
9951           diag::err_typename_nested_not_found_enable_if) {
9952       // FIXME: Use the source range of the condition, and the fully-qualified
9953       //        name of the enable_if template. These are both present in PDiag.
9954       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9955         << "'enable_if'" << TemplateArgString;
9956       return;
9957     }
9958 
9959     // We found a specific requirement that disabled the enable_if.
9960     if (PDiag && PDiag->second.getDiagID() ==
9961         diag::err_typename_nested_not_found_requirement) {
9962       S.Diag(Templated->getLocation(),
9963              diag::note_ovl_candidate_disabled_by_requirement)
9964         << PDiag->second.getStringArg(0) << TemplateArgString;
9965       return;
9966     }
9967 
9968     // Format the SFINAE diagnostic into the argument string.
9969     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9970     //        formatted message in another diagnostic.
9971     SmallString<128> SFINAEArgString;
9972     SourceRange R;
9973     if (PDiag) {
9974       SFINAEArgString = ": ";
9975       R = SourceRange(PDiag->first, PDiag->first);
9976       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9977     }
9978 
9979     S.Diag(Templated->getLocation(),
9980            diag::note_ovl_candidate_substitution_failure)
9981         << TemplateArgString << SFINAEArgString << R;
9982     MaybeEmitInheritedConstructorNote(S, Found);
9983     return;
9984   }
9985 
9986   case Sema::TDK_DeducedMismatch:
9987   case Sema::TDK_DeducedMismatchNested: {
9988     // Format the template argument list into the argument string.
9989     SmallString<128> TemplateArgString;
9990     if (TemplateArgumentList *Args =
9991             DeductionFailure.getTemplateArgumentList()) {
9992       TemplateArgString = " ";
9993       TemplateArgString += S.getTemplateArgumentBindingsText(
9994           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9995     }
9996 
9997     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9998         << (*DeductionFailure.getCallArgIndex() + 1)
9999         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10000         << TemplateArgString
10001         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10002     break;
10003   }
10004 
10005   case Sema::TDK_NonDeducedMismatch: {
10006     // FIXME: Provide a source location to indicate what we couldn't match.
10007     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10008     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10009     if (FirstTA.getKind() == TemplateArgument::Template &&
10010         SecondTA.getKind() == TemplateArgument::Template) {
10011       TemplateName FirstTN = FirstTA.getAsTemplate();
10012       TemplateName SecondTN = SecondTA.getAsTemplate();
10013       if (FirstTN.getKind() == TemplateName::Template &&
10014           SecondTN.getKind() == TemplateName::Template) {
10015         if (FirstTN.getAsTemplateDecl()->getName() ==
10016             SecondTN.getAsTemplateDecl()->getName()) {
10017           // FIXME: This fixes a bad diagnostic where both templates are named
10018           // the same.  This particular case is a bit difficult since:
10019           // 1) It is passed as a string to the diagnostic printer.
10020           // 2) The diagnostic printer only attempts to find a better
10021           //    name for types, not decls.
10022           // Ideally, this should folded into the diagnostic printer.
10023           S.Diag(Templated->getLocation(),
10024                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10025               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10026           return;
10027         }
10028       }
10029     }
10030 
10031     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10032         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10033       return;
10034 
10035     // FIXME: For generic lambda parameters, check if the function is a lambda
10036     // call operator, and if so, emit a prettier and more informative
10037     // diagnostic that mentions 'auto' and lambda in addition to
10038     // (or instead of?) the canonical template type parameters.
10039     S.Diag(Templated->getLocation(),
10040            diag::note_ovl_candidate_non_deduced_mismatch)
10041         << FirstTA << SecondTA;
10042     return;
10043   }
10044   // TODO: diagnose these individually, then kill off
10045   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10046   case Sema::TDK_MiscellaneousDeductionFailure:
10047     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10048     MaybeEmitInheritedConstructorNote(S, Found);
10049     return;
10050   case Sema::TDK_CUDATargetMismatch:
10051     S.Diag(Templated->getLocation(),
10052            diag::note_cuda_ovl_candidate_target_mismatch);
10053     return;
10054   }
10055 }
10056 
10057 /// Diagnose a failed template-argument deduction, for function calls.
10058 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10059                                  unsigned NumArgs,
10060                                  bool TakingCandidateAddress) {
10061   unsigned TDK = Cand->DeductionFailure.Result;
10062   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10063     if (CheckArityMismatch(S, Cand, NumArgs))
10064       return;
10065   }
10066   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10067                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10068 }
10069 
10070 /// CUDA: diagnose an invalid call across targets.
10071 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10072   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10073   FunctionDecl *Callee = Cand->Function;
10074 
10075   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10076                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10077 
10078   std::string FnDesc;
10079   OverloadCandidateKind FnKind =
10080       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10081 
10082   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10083       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10084 
10085   // This could be an implicit constructor for which we could not infer the
10086   // target due to a collsion. Diagnose that case.
10087   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10088   if (Meth != nullptr && Meth->isImplicit()) {
10089     CXXRecordDecl *ParentClass = Meth->getParent();
10090     Sema::CXXSpecialMember CSM;
10091 
10092     switch (FnKind) {
10093     default:
10094       return;
10095     case oc_implicit_default_constructor:
10096       CSM = Sema::CXXDefaultConstructor;
10097       break;
10098     case oc_implicit_copy_constructor:
10099       CSM = Sema::CXXCopyConstructor;
10100       break;
10101     case oc_implicit_move_constructor:
10102       CSM = Sema::CXXMoveConstructor;
10103       break;
10104     case oc_implicit_copy_assignment:
10105       CSM = Sema::CXXCopyAssignment;
10106       break;
10107     case oc_implicit_move_assignment:
10108       CSM = Sema::CXXMoveAssignment;
10109       break;
10110     };
10111 
10112     bool ConstRHS = false;
10113     if (Meth->getNumParams()) {
10114       if (const ReferenceType *RT =
10115               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10116         ConstRHS = RT->getPointeeType().isConstQualified();
10117       }
10118     }
10119 
10120     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10121                                               /* ConstRHS */ ConstRHS,
10122                                               /* Diagnose */ true);
10123   }
10124 }
10125 
10126 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10127   FunctionDecl *Callee = Cand->Function;
10128   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10129 
10130   S.Diag(Callee->getLocation(),
10131          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10132       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10133 }
10134 
10135 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10136   FunctionDecl *Callee = Cand->Function;
10137 
10138   S.Diag(Callee->getLocation(),
10139          diag::note_ovl_candidate_disabled_by_extension);
10140 }
10141 
10142 /// Generates a 'note' diagnostic for an overload candidate.  We've
10143 /// already generated a primary error at the call site.
10144 ///
10145 /// It really does need to be a single diagnostic with its caret
10146 /// pointed at the candidate declaration.  Yes, this creates some
10147 /// major challenges of technical writing.  Yes, this makes pointing
10148 /// out problems with specific arguments quite awkward.  It's still
10149 /// better than generating twenty screens of text for every failed
10150 /// overload.
10151 ///
10152 /// It would be great to be able to express per-candidate problems
10153 /// more richly for those diagnostic clients that cared, but we'd
10154 /// still have to be just as careful with the default diagnostics.
10155 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10156                                   unsigned NumArgs,
10157                                   bool TakingCandidateAddress) {
10158   FunctionDecl *Fn = Cand->Function;
10159 
10160   // Note deleted candidates, but only if they're viable.
10161   if (Cand->Viable) {
10162     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10163       std::string FnDesc;
10164       OverloadCandidateKind FnKind =
10165         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10166 
10167       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10168         << FnKind << FnDesc
10169         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10170       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10171       return;
10172     }
10173 
10174     // We don't really have anything else to say about viable candidates.
10175     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10176     return;
10177   }
10178 
10179   switch (Cand->FailureKind) {
10180   case ovl_fail_too_many_arguments:
10181   case ovl_fail_too_few_arguments:
10182     return DiagnoseArityMismatch(S, Cand, NumArgs);
10183 
10184   case ovl_fail_bad_deduction:
10185     return DiagnoseBadDeduction(S, Cand, NumArgs,
10186                                 TakingCandidateAddress);
10187 
10188   case ovl_fail_illegal_constructor: {
10189     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10190       << (Fn->getPrimaryTemplate() ? 1 : 0);
10191     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10192     return;
10193   }
10194 
10195   case ovl_fail_trivial_conversion:
10196   case ovl_fail_bad_final_conversion:
10197   case ovl_fail_final_conversion_not_exact:
10198     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10199 
10200   case ovl_fail_bad_conversion: {
10201     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10202     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10203       if (Cand->Conversions[I].isBad())
10204         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10205 
10206     // FIXME: this currently happens when we're called from SemaInit
10207     // when user-conversion overload fails.  Figure out how to handle
10208     // those conditions and diagnose them well.
10209     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10210   }
10211 
10212   case ovl_fail_bad_target:
10213     return DiagnoseBadTarget(S, Cand);
10214 
10215   case ovl_fail_enable_if:
10216     return DiagnoseFailedEnableIfAttr(S, Cand);
10217 
10218   case ovl_fail_ext_disabled:
10219     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10220 
10221   case ovl_fail_inhctor_slice:
10222     // It's generally not interesting to note copy/move constructors here.
10223     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10224       return;
10225     S.Diag(Fn->getLocation(),
10226            diag::note_ovl_candidate_inherited_constructor_slice)
10227       << (Fn->getPrimaryTemplate() ? 1 : 0)
10228       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10229     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10230     return;
10231 
10232   case ovl_fail_addr_not_available: {
10233     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10234     (void)Available;
10235     assert(!Available);
10236     break;
10237   }
10238   case ovl_non_default_multiversion_function:
10239     // Do nothing, these should simply be ignored.
10240     break;
10241   }
10242 }
10243 
10244 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10245   // Desugar the type of the surrogate down to a function type,
10246   // retaining as many typedefs as possible while still showing
10247   // the function type (and, therefore, its parameter types).
10248   QualType FnType = Cand->Surrogate->getConversionType();
10249   bool isLValueReference = false;
10250   bool isRValueReference = false;
10251   bool isPointer = false;
10252   if (const LValueReferenceType *FnTypeRef =
10253         FnType->getAs<LValueReferenceType>()) {
10254     FnType = FnTypeRef->getPointeeType();
10255     isLValueReference = true;
10256   } else if (const RValueReferenceType *FnTypeRef =
10257                FnType->getAs<RValueReferenceType>()) {
10258     FnType = FnTypeRef->getPointeeType();
10259     isRValueReference = true;
10260   }
10261   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10262     FnType = FnTypePtr->getPointeeType();
10263     isPointer = true;
10264   }
10265   // Desugar down to a function type.
10266   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10267   // Reconstruct the pointer/reference as appropriate.
10268   if (isPointer) FnType = S.Context.getPointerType(FnType);
10269   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10270   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10271 
10272   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10273     << FnType;
10274 }
10275 
10276 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10277                                          SourceLocation OpLoc,
10278                                          OverloadCandidate *Cand) {
10279   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10280   std::string TypeStr("operator");
10281   TypeStr += Opc;
10282   TypeStr += "(";
10283   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10284   if (Cand->Conversions.size() == 1) {
10285     TypeStr += ")";
10286     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10287   } else {
10288     TypeStr += ", ";
10289     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10290     TypeStr += ")";
10291     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10292   }
10293 }
10294 
10295 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10296                                          OverloadCandidate *Cand) {
10297   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10298     if (ICS.isBad()) break; // all meaningless after first invalid
10299     if (!ICS.isAmbiguous()) continue;
10300 
10301     ICS.DiagnoseAmbiguousConversion(
10302         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10303   }
10304 }
10305 
10306 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10307   if (Cand->Function)
10308     return Cand->Function->getLocation();
10309   if (Cand->IsSurrogate)
10310     return Cand->Surrogate->getLocation();
10311   return SourceLocation();
10312 }
10313 
10314 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10315   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10316   case Sema::TDK_Success:
10317   case Sema::TDK_NonDependentConversionFailure:
10318     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10319 
10320   case Sema::TDK_Invalid:
10321   case Sema::TDK_Incomplete:
10322     return 1;
10323 
10324   case Sema::TDK_Underqualified:
10325   case Sema::TDK_Inconsistent:
10326     return 2;
10327 
10328   case Sema::TDK_SubstitutionFailure:
10329   case Sema::TDK_DeducedMismatch:
10330   case Sema::TDK_DeducedMismatchNested:
10331   case Sema::TDK_NonDeducedMismatch:
10332   case Sema::TDK_MiscellaneousDeductionFailure:
10333   case Sema::TDK_CUDATargetMismatch:
10334     return 3;
10335 
10336   case Sema::TDK_InstantiationDepth:
10337     return 4;
10338 
10339   case Sema::TDK_InvalidExplicitArguments:
10340     return 5;
10341 
10342   case Sema::TDK_TooManyArguments:
10343   case Sema::TDK_TooFewArguments:
10344     return 6;
10345   }
10346   llvm_unreachable("Unhandled deduction result");
10347 }
10348 
10349 namespace {
10350 struct CompareOverloadCandidatesForDisplay {
10351   Sema &S;
10352   SourceLocation Loc;
10353   size_t NumArgs;
10354   OverloadCandidateSet::CandidateSetKind CSK;
10355 
10356   CompareOverloadCandidatesForDisplay(
10357       Sema &S, SourceLocation Loc, size_t NArgs,
10358       OverloadCandidateSet::CandidateSetKind CSK)
10359       : S(S), NumArgs(NArgs), CSK(CSK) {}
10360 
10361   bool operator()(const OverloadCandidate *L,
10362                   const OverloadCandidate *R) {
10363     // Fast-path this check.
10364     if (L == R) return false;
10365 
10366     // Order first by viability.
10367     if (L->Viable) {
10368       if (!R->Viable) return true;
10369 
10370       // TODO: introduce a tri-valued comparison for overload
10371       // candidates.  Would be more worthwhile if we had a sort
10372       // that could exploit it.
10373       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10374         return true;
10375       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10376         return false;
10377     } else if (R->Viable)
10378       return false;
10379 
10380     assert(L->Viable == R->Viable);
10381 
10382     // Criteria by which we can sort non-viable candidates:
10383     if (!L->Viable) {
10384       // 1. Arity mismatches come after other candidates.
10385       if (L->FailureKind == ovl_fail_too_many_arguments ||
10386           L->FailureKind == ovl_fail_too_few_arguments) {
10387         if (R->FailureKind == ovl_fail_too_many_arguments ||
10388             R->FailureKind == ovl_fail_too_few_arguments) {
10389           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10390           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10391           if (LDist == RDist) {
10392             if (L->FailureKind == R->FailureKind)
10393               // Sort non-surrogates before surrogates.
10394               return !L->IsSurrogate && R->IsSurrogate;
10395             // Sort candidates requiring fewer parameters than there were
10396             // arguments given after candidates requiring more parameters
10397             // than there were arguments given.
10398             return L->FailureKind == ovl_fail_too_many_arguments;
10399           }
10400           return LDist < RDist;
10401         }
10402         return false;
10403       }
10404       if (R->FailureKind == ovl_fail_too_many_arguments ||
10405           R->FailureKind == ovl_fail_too_few_arguments)
10406         return true;
10407 
10408       // 2. Bad conversions come first and are ordered by the number
10409       // of bad conversions and quality of good conversions.
10410       if (L->FailureKind == ovl_fail_bad_conversion) {
10411         if (R->FailureKind != ovl_fail_bad_conversion)
10412           return true;
10413 
10414         // The conversion that can be fixed with a smaller number of changes,
10415         // comes first.
10416         unsigned numLFixes = L->Fix.NumConversionsFixed;
10417         unsigned numRFixes = R->Fix.NumConversionsFixed;
10418         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10419         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10420         if (numLFixes != numRFixes) {
10421           return numLFixes < numRFixes;
10422         }
10423 
10424         // If there's any ordering between the defined conversions...
10425         // FIXME: this might not be transitive.
10426         assert(L->Conversions.size() == R->Conversions.size());
10427 
10428         int leftBetter = 0;
10429         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10430         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10431           switch (CompareImplicitConversionSequences(S, Loc,
10432                                                      L->Conversions[I],
10433                                                      R->Conversions[I])) {
10434           case ImplicitConversionSequence::Better:
10435             leftBetter++;
10436             break;
10437 
10438           case ImplicitConversionSequence::Worse:
10439             leftBetter--;
10440             break;
10441 
10442           case ImplicitConversionSequence::Indistinguishable:
10443             break;
10444           }
10445         }
10446         if (leftBetter > 0) return true;
10447         if (leftBetter < 0) return false;
10448 
10449       } else if (R->FailureKind == ovl_fail_bad_conversion)
10450         return false;
10451 
10452       if (L->FailureKind == ovl_fail_bad_deduction) {
10453         if (R->FailureKind != ovl_fail_bad_deduction)
10454           return true;
10455 
10456         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10457           return RankDeductionFailure(L->DeductionFailure)
10458                < RankDeductionFailure(R->DeductionFailure);
10459       } else if (R->FailureKind == ovl_fail_bad_deduction)
10460         return false;
10461 
10462       // TODO: others?
10463     }
10464 
10465     // Sort everything else by location.
10466     SourceLocation LLoc = GetLocationForCandidate(L);
10467     SourceLocation RLoc = GetLocationForCandidate(R);
10468 
10469     // Put candidates without locations (e.g. builtins) at the end.
10470     if (LLoc.isInvalid()) return false;
10471     if (RLoc.isInvalid()) return true;
10472 
10473     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10474   }
10475 };
10476 }
10477 
10478 /// CompleteNonViableCandidate - Normally, overload resolution only
10479 /// computes up to the first bad conversion. Produces the FixIt set if
10480 /// possible.
10481 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10482                                        ArrayRef<Expr *> Args) {
10483   assert(!Cand->Viable);
10484 
10485   // Don't do anything on failures other than bad conversion.
10486   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10487 
10488   // We only want the FixIts if all the arguments can be corrected.
10489   bool Unfixable = false;
10490   // Use a implicit copy initialization to check conversion fixes.
10491   Cand->Fix.setConversionChecker(TryCopyInitialization);
10492 
10493   // Attempt to fix the bad conversion.
10494   unsigned ConvCount = Cand->Conversions.size();
10495   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10496        ++ConvIdx) {
10497     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10498     if (Cand->Conversions[ConvIdx].isInitialized() &&
10499         Cand->Conversions[ConvIdx].isBad()) {
10500       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10501       break;
10502     }
10503   }
10504 
10505   // FIXME: this should probably be preserved from the overload
10506   // operation somehow.
10507   bool SuppressUserConversions = false;
10508 
10509   unsigned ConvIdx = 0;
10510   ArrayRef<QualType> ParamTypes;
10511 
10512   if (Cand->IsSurrogate) {
10513     QualType ConvType
10514       = Cand->Surrogate->getConversionType().getNonReferenceType();
10515     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10516       ConvType = ConvPtrType->getPointeeType();
10517     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10518     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10519     ConvIdx = 1;
10520   } else if (Cand->Function) {
10521     ParamTypes =
10522         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10523     if (isa<CXXMethodDecl>(Cand->Function) &&
10524         !isa<CXXConstructorDecl>(Cand->Function)) {
10525       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10526       ConvIdx = 1;
10527     }
10528   } else {
10529     // Builtin operator.
10530     assert(ConvCount <= 3);
10531     ParamTypes = Cand->BuiltinParamTypes;
10532   }
10533 
10534   // Fill in the rest of the conversions.
10535   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10536     if (Cand->Conversions[ConvIdx].isInitialized()) {
10537       // We've already checked this conversion.
10538     } else if (ArgIdx < ParamTypes.size()) {
10539       if (ParamTypes[ArgIdx]->isDependentType())
10540         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10541             Args[ArgIdx]->getType());
10542       else {
10543         Cand->Conversions[ConvIdx] =
10544             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10545                                   SuppressUserConversions,
10546                                   /*InOverloadResolution=*/true,
10547                                   /*AllowObjCWritebackConversion=*/
10548                                   S.getLangOpts().ObjCAutoRefCount);
10549         // Store the FixIt in the candidate if it exists.
10550         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10551           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10552       }
10553     } else
10554       Cand->Conversions[ConvIdx].setEllipsis();
10555   }
10556 }
10557 
10558 /// When overload resolution fails, prints diagnostic messages containing the
10559 /// candidates in the candidate set.
10560 void OverloadCandidateSet::NoteCandidates(
10561     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10562     StringRef Opc, SourceLocation OpLoc,
10563     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10564   // Sort the candidates by viability and position.  Sorting directly would
10565   // be prohibitive, so we make a set of pointers and sort those.
10566   SmallVector<OverloadCandidate*, 32> Cands;
10567   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10568   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10569     if (!Filter(*Cand))
10570       continue;
10571     if (Cand->Viable)
10572       Cands.push_back(Cand);
10573     else if (OCD == OCD_AllCandidates) {
10574       CompleteNonViableCandidate(S, Cand, Args);
10575       if (Cand->Function || Cand->IsSurrogate)
10576         Cands.push_back(Cand);
10577       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10578       // want to list every possible builtin candidate.
10579     }
10580   }
10581 
10582   std::stable_sort(Cands.begin(), Cands.end(),
10583             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10584 
10585   bool ReportedAmbiguousConversions = false;
10586 
10587   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10588   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10589   unsigned CandsShown = 0;
10590   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10591     OverloadCandidate *Cand = *I;
10592 
10593     // Set an arbitrary limit on the number of candidate functions we'll spam
10594     // the user with.  FIXME: This limit should depend on details of the
10595     // candidate list.
10596     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10597       break;
10598     }
10599     ++CandsShown;
10600 
10601     if (Cand->Function)
10602       NoteFunctionCandidate(S, Cand, Args.size(),
10603                             /*TakingCandidateAddress=*/false);
10604     else if (Cand->IsSurrogate)
10605       NoteSurrogateCandidate(S, Cand);
10606     else {
10607       assert(Cand->Viable &&
10608              "Non-viable built-in candidates are not added to Cands.");
10609       // Generally we only see ambiguities including viable builtin
10610       // operators if overload resolution got screwed up by an
10611       // ambiguous user-defined conversion.
10612       //
10613       // FIXME: It's quite possible for different conversions to see
10614       // different ambiguities, though.
10615       if (!ReportedAmbiguousConversions) {
10616         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10617         ReportedAmbiguousConversions = true;
10618       }
10619 
10620       // If this is a viable builtin, print it.
10621       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10622     }
10623   }
10624 
10625   if (I != E)
10626     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10627 }
10628 
10629 static SourceLocation
10630 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10631   return Cand->Specialization ? Cand->Specialization->getLocation()
10632                               : SourceLocation();
10633 }
10634 
10635 namespace {
10636 struct CompareTemplateSpecCandidatesForDisplay {
10637   Sema &S;
10638   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10639 
10640   bool operator()(const TemplateSpecCandidate *L,
10641                   const TemplateSpecCandidate *R) {
10642     // Fast-path this check.
10643     if (L == R)
10644       return false;
10645 
10646     // Assuming that both candidates are not matches...
10647 
10648     // Sort by the ranking of deduction failures.
10649     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10650       return RankDeductionFailure(L->DeductionFailure) <
10651              RankDeductionFailure(R->DeductionFailure);
10652 
10653     // Sort everything else by location.
10654     SourceLocation LLoc = GetLocationForCandidate(L);
10655     SourceLocation RLoc = GetLocationForCandidate(R);
10656 
10657     // Put candidates without locations (e.g. builtins) at the end.
10658     if (LLoc.isInvalid())
10659       return false;
10660     if (RLoc.isInvalid())
10661       return true;
10662 
10663     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10664   }
10665 };
10666 }
10667 
10668 /// Diagnose a template argument deduction failure.
10669 /// We are treating these failures as overload failures due to bad
10670 /// deductions.
10671 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10672                                                  bool ForTakingAddress) {
10673   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10674                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10675 }
10676 
10677 void TemplateSpecCandidateSet::destroyCandidates() {
10678   for (iterator i = begin(), e = end(); i != e; ++i) {
10679     i->DeductionFailure.Destroy();
10680   }
10681 }
10682 
10683 void TemplateSpecCandidateSet::clear() {
10684   destroyCandidates();
10685   Candidates.clear();
10686 }
10687 
10688 /// NoteCandidates - When no template specialization match is found, prints
10689 /// diagnostic messages containing the non-matching specializations that form
10690 /// the candidate set.
10691 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10692 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10693 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10694   // Sort the candidates by position (assuming no candidate is a match).
10695   // Sorting directly would be prohibitive, so we make a set of pointers
10696   // and sort those.
10697   SmallVector<TemplateSpecCandidate *, 32> Cands;
10698   Cands.reserve(size());
10699   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10700     if (Cand->Specialization)
10701       Cands.push_back(Cand);
10702     // Otherwise, this is a non-matching builtin candidate.  We do not,
10703     // in general, want to list every possible builtin candidate.
10704   }
10705 
10706   llvm::sort(Cands.begin(), Cands.end(),
10707              CompareTemplateSpecCandidatesForDisplay(S));
10708 
10709   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10710   // for generalization purposes (?).
10711   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10712 
10713   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10714   unsigned CandsShown = 0;
10715   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10716     TemplateSpecCandidate *Cand = *I;
10717 
10718     // Set an arbitrary limit on the number of candidates we'll spam
10719     // the user with.  FIXME: This limit should depend on details of the
10720     // candidate list.
10721     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10722       break;
10723     ++CandsShown;
10724 
10725     assert(Cand->Specialization &&
10726            "Non-matching built-in candidates are not added to Cands.");
10727     Cand->NoteDeductionFailure(S, ForTakingAddress);
10728   }
10729 
10730   if (I != E)
10731     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10732 }
10733 
10734 // [PossiblyAFunctionType]  -->   [Return]
10735 // NonFunctionType --> NonFunctionType
10736 // R (A) --> R(A)
10737 // R (*)(A) --> R (A)
10738 // R (&)(A) --> R (A)
10739 // R (S::*)(A) --> R (A)
10740 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10741   QualType Ret = PossiblyAFunctionType;
10742   if (const PointerType *ToTypePtr =
10743     PossiblyAFunctionType->getAs<PointerType>())
10744     Ret = ToTypePtr->getPointeeType();
10745   else if (const ReferenceType *ToTypeRef =
10746     PossiblyAFunctionType->getAs<ReferenceType>())
10747     Ret = ToTypeRef->getPointeeType();
10748   else if (const MemberPointerType *MemTypePtr =
10749     PossiblyAFunctionType->getAs<MemberPointerType>())
10750     Ret = MemTypePtr->getPointeeType();
10751   Ret =
10752     Context.getCanonicalType(Ret).getUnqualifiedType();
10753   return Ret;
10754 }
10755 
10756 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10757                                  bool Complain = true) {
10758   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10759       S.DeduceReturnType(FD, Loc, Complain))
10760     return true;
10761 
10762   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10763   if (S.getLangOpts().CPlusPlus17 &&
10764       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10765       !S.ResolveExceptionSpec(Loc, FPT))
10766     return true;
10767 
10768   return false;
10769 }
10770 
10771 namespace {
10772 // A helper class to help with address of function resolution
10773 // - allows us to avoid passing around all those ugly parameters
10774 class AddressOfFunctionResolver {
10775   Sema& S;
10776   Expr* SourceExpr;
10777   const QualType& TargetType;
10778   QualType TargetFunctionType; // Extracted function type from target type
10779 
10780   bool Complain;
10781   //DeclAccessPair& ResultFunctionAccessPair;
10782   ASTContext& Context;
10783 
10784   bool TargetTypeIsNonStaticMemberFunction;
10785   bool FoundNonTemplateFunction;
10786   bool StaticMemberFunctionFromBoundPointer;
10787   bool HasComplained;
10788 
10789   OverloadExpr::FindResult OvlExprInfo;
10790   OverloadExpr *OvlExpr;
10791   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10792   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10793   TemplateSpecCandidateSet FailedCandidates;
10794 
10795 public:
10796   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10797                             const QualType &TargetType, bool Complain)
10798       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10799         Complain(Complain), Context(S.getASTContext()),
10800         TargetTypeIsNonStaticMemberFunction(
10801             !!TargetType->getAs<MemberPointerType>()),
10802         FoundNonTemplateFunction(false),
10803         StaticMemberFunctionFromBoundPointer(false),
10804         HasComplained(false),
10805         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10806         OvlExpr(OvlExprInfo.Expression),
10807         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10808     ExtractUnqualifiedFunctionTypeFromTargetType();
10809 
10810     if (TargetFunctionType->isFunctionType()) {
10811       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10812         if (!UME->isImplicitAccess() &&
10813             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10814           StaticMemberFunctionFromBoundPointer = true;
10815     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10816       DeclAccessPair dap;
10817       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10818               OvlExpr, false, &dap)) {
10819         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10820           if (!Method->isStatic()) {
10821             // If the target type is a non-function type and the function found
10822             // is a non-static member function, pretend as if that was the
10823             // target, it's the only possible type to end up with.
10824             TargetTypeIsNonStaticMemberFunction = true;
10825 
10826             // And skip adding the function if its not in the proper form.
10827             // We'll diagnose this due to an empty set of functions.
10828             if (!OvlExprInfo.HasFormOfMemberPointer)
10829               return;
10830           }
10831 
10832         Matches.push_back(std::make_pair(dap, Fn));
10833       }
10834       return;
10835     }
10836 
10837     if (OvlExpr->hasExplicitTemplateArgs())
10838       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10839 
10840     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10841       // C++ [over.over]p4:
10842       //   If more than one function is selected, [...]
10843       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10844         if (FoundNonTemplateFunction)
10845           EliminateAllTemplateMatches();
10846         else
10847           EliminateAllExceptMostSpecializedTemplate();
10848       }
10849     }
10850 
10851     if (S.getLangOpts().CUDA && Matches.size() > 1)
10852       EliminateSuboptimalCudaMatches();
10853   }
10854 
10855   bool hasComplained() const { return HasComplained; }
10856 
10857 private:
10858   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10859     QualType Discard;
10860     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10861            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10862   }
10863 
10864   /// \return true if A is considered a better overload candidate for the
10865   /// desired type than B.
10866   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10867     // If A doesn't have exactly the correct type, we don't want to classify it
10868     // as "better" than anything else. This way, the user is required to
10869     // disambiguate for us if there are multiple candidates and no exact match.
10870     return candidateHasExactlyCorrectType(A) &&
10871            (!candidateHasExactlyCorrectType(B) ||
10872             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10873   }
10874 
10875   /// \return true if we were able to eliminate all but one overload candidate,
10876   /// false otherwise.
10877   bool eliminiateSuboptimalOverloadCandidates() {
10878     // Same algorithm as overload resolution -- one pass to pick the "best",
10879     // another pass to be sure that nothing is better than the best.
10880     auto Best = Matches.begin();
10881     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10882       if (isBetterCandidate(I->second, Best->second))
10883         Best = I;
10884 
10885     const FunctionDecl *BestFn = Best->second;
10886     auto IsBestOrInferiorToBest = [this, BestFn](
10887         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10888       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10889     };
10890 
10891     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10892     // option, so we can potentially give the user a better error
10893     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10894       return false;
10895     Matches[0] = *Best;
10896     Matches.resize(1);
10897     return true;
10898   }
10899 
10900   bool isTargetTypeAFunction() const {
10901     return TargetFunctionType->isFunctionType();
10902   }
10903 
10904   // [ToType]     [Return]
10905 
10906   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10907   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10908   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10909   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10910     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10911   }
10912 
10913   // return true if any matching specializations were found
10914   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10915                                    const DeclAccessPair& CurAccessFunPair) {
10916     if (CXXMethodDecl *Method
10917               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10918       // Skip non-static function templates when converting to pointer, and
10919       // static when converting to member pointer.
10920       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10921         return false;
10922     }
10923     else if (TargetTypeIsNonStaticMemberFunction)
10924       return false;
10925 
10926     // C++ [over.over]p2:
10927     //   If the name is a function template, template argument deduction is
10928     //   done (14.8.2.2), and if the argument deduction succeeds, the
10929     //   resulting template argument list is used to generate a single
10930     //   function template specialization, which is added to the set of
10931     //   overloaded functions considered.
10932     FunctionDecl *Specialization = nullptr;
10933     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10934     if (Sema::TemplateDeductionResult Result
10935           = S.DeduceTemplateArguments(FunctionTemplate,
10936                                       &OvlExplicitTemplateArgs,
10937                                       TargetFunctionType, Specialization,
10938                                       Info, /*IsAddressOfFunction*/true)) {
10939       // Make a note of the failed deduction for diagnostics.
10940       FailedCandidates.addCandidate()
10941           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10942                MakeDeductionFailureInfo(Context, Result, Info));
10943       return false;
10944     }
10945 
10946     // Template argument deduction ensures that we have an exact match or
10947     // compatible pointer-to-function arguments that would be adjusted by ICS.
10948     // This function template specicalization works.
10949     assert(S.isSameOrCompatibleFunctionType(
10950               Context.getCanonicalType(Specialization->getType()),
10951               Context.getCanonicalType(TargetFunctionType)));
10952 
10953     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10954       return false;
10955 
10956     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10957     return true;
10958   }
10959 
10960   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10961                                       const DeclAccessPair& CurAccessFunPair) {
10962     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10963       // Skip non-static functions when converting to pointer, and static
10964       // when converting to member pointer.
10965       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10966         return false;
10967     }
10968     else if (TargetTypeIsNonStaticMemberFunction)
10969       return false;
10970 
10971     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10972       if (S.getLangOpts().CUDA)
10973         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10974           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10975             return false;
10976       if (FunDecl->isMultiVersion()) {
10977         const auto *TA = FunDecl->getAttr<TargetAttr>();
10978         assert(TA && "Multiversioned functions require a target attribute");
10979         if (!TA->isDefaultVersion())
10980           return false;
10981       }
10982 
10983       // If any candidate has a placeholder return type, trigger its deduction
10984       // now.
10985       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10986                                Complain)) {
10987         HasComplained |= Complain;
10988         return false;
10989       }
10990 
10991       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10992         return false;
10993 
10994       // If we're in C, we need to support types that aren't exactly identical.
10995       if (!S.getLangOpts().CPlusPlus ||
10996           candidateHasExactlyCorrectType(FunDecl)) {
10997         Matches.push_back(std::make_pair(
10998             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10999         FoundNonTemplateFunction = true;
11000         return true;
11001       }
11002     }
11003 
11004     return false;
11005   }
11006 
11007   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11008     bool Ret = false;
11009 
11010     // If the overload expression doesn't have the form of a pointer to
11011     // member, don't try to convert it to a pointer-to-member type.
11012     if (IsInvalidFormOfPointerToMemberFunction())
11013       return false;
11014 
11015     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11016                                E = OvlExpr->decls_end();
11017          I != E; ++I) {
11018       // Look through any using declarations to find the underlying function.
11019       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11020 
11021       // C++ [over.over]p3:
11022       //   Non-member functions and static member functions match
11023       //   targets of type "pointer-to-function" or "reference-to-function."
11024       //   Nonstatic member functions match targets of
11025       //   type "pointer-to-member-function."
11026       // Note that according to DR 247, the containing class does not matter.
11027       if (FunctionTemplateDecl *FunctionTemplate
11028                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11029         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11030           Ret = true;
11031       }
11032       // If we have explicit template arguments supplied, skip non-templates.
11033       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11034                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11035         Ret = true;
11036     }
11037     assert(Ret || Matches.empty());
11038     return Ret;
11039   }
11040 
11041   void EliminateAllExceptMostSpecializedTemplate() {
11042     //   [...] and any given function template specialization F1 is
11043     //   eliminated if the set contains a second function template
11044     //   specialization whose function template is more specialized
11045     //   than the function template of F1 according to the partial
11046     //   ordering rules of 14.5.5.2.
11047 
11048     // The algorithm specified above is quadratic. We instead use a
11049     // two-pass algorithm (similar to the one used to identify the
11050     // best viable function in an overload set) that identifies the
11051     // best function template (if it exists).
11052 
11053     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11054     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11055       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11056 
11057     // TODO: It looks like FailedCandidates does not serve much purpose
11058     // here, since the no_viable diagnostic has index 0.
11059     UnresolvedSetIterator Result = S.getMostSpecialized(
11060         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11061         SourceExpr->getLocStart(), S.PDiag(),
11062         S.PDiag(diag::err_addr_ovl_ambiguous)
11063           << Matches[0].second->getDeclName(),
11064         S.PDiag(diag::note_ovl_candidate)
11065           << (unsigned)oc_function_template,
11066         Complain, TargetFunctionType);
11067 
11068     if (Result != MatchesCopy.end()) {
11069       // Make it the first and only element
11070       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11071       Matches[0].second = cast<FunctionDecl>(*Result);
11072       Matches.resize(1);
11073     } else
11074       HasComplained |= Complain;
11075   }
11076 
11077   void EliminateAllTemplateMatches() {
11078     //   [...] any function template specializations in the set are
11079     //   eliminated if the set also contains a non-template function, [...]
11080     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11081       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11082         ++I;
11083       else {
11084         Matches[I] = Matches[--N];
11085         Matches.resize(N);
11086       }
11087     }
11088   }
11089 
11090   void EliminateSuboptimalCudaMatches() {
11091     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11092   }
11093 
11094 public:
11095   void ComplainNoMatchesFound() const {
11096     assert(Matches.empty());
11097     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11098         << OvlExpr->getName() << TargetFunctionType
11099         << OvlExpr->getSourceRange();
11100     if (FailedCandidates.empty())
11101       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11102                                   /*TakingAddress=*/true);
11103     else {
11104       // We have some deduction failure messages. Use them to diagnose
11105       // the function templates, and diagnose the non-template candidates
11106       // normally.
11107       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11108                                  IEnd = OvlExpr->decls_end();
11109            I != IEnd; ++I)
11110         if (FunctionDecl *Fun =
11111                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11112           if (!functionHasPassObjectSizeParams(Fun))
11113             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11114                                     /*TakingAddress=*/true);
11115       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11116     }
11117   }
11118 
11119   bool IsInvalidFormOfPointerToMemberFunction() const {
11120     return TargetTypeIsNonStaticMemberFunction &&
11121       !OvlExprInfo.HasFormOfMemberPointer;
11122   }
11123 
11124   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11125       // TODO: Should we condition this on whether any functions might
11126       // have matched, or is it more appropriate to do that in callers?
11127       // TODO: a fixit wouldn't hurt.
11128       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11129         << TargetType << OvlExpr->getSourceRange();
11130   }
11131 
11132   bool IsStaticMemberFunctionFromBoundPointer() const {
11133     return StaticMemberFunctionFromBoundPointer;
11134   }
11135 
11136   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11137     S.Diag(OvlExpr->getLocStart(),
11138            diag::err_invalid_form_pointer_member_function)
11139       << OvlExpr->getSourceRange();
11140   }
11141 
11142   void ComplainOfInvalidConversion() const {
11143     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11144       << OvlExpr->getName() << TargetType;
11145   }
11146 
11147   void ComplainMultipleMatchesFound() const {
11148     assert(Matches.size() > 1);
11149     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11150       << OvlExpr->getName()
11151       << OvlExpr->getSourceRange();
11152     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11153                                 /*TakingAddress=*/true);
11154   }
11155 
11156   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11157 
11158   int getNumMatches() const { return Matches.size(); }
11159 
11160   FunctionDecl* getMatchingFunctionDecl() const {
11161     if (Matches.size() != 1) return nullptr;
11162     return Matches[0].second;
11163   }
11164 
11165   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11166     if (Matches.size() != 1) return nullptr;
11167     return &Matches[0].first;
11168   }
11169 };
11170 }
11171 
11172 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11173 /// an overloaded function (C++ [over.over]), where @p From is an
11174 /// expression with overloaded function type and @p ToType is the type
11175 /// we're trying to resolve to. For example:
11176 ///
11177 /// @code
11178 /// int f(double);
11179 /// int f(int);
11180 ///
11181 /// int (*pfd)(double) = f; // selects f(double)
11182 /// @endcode
11183 ///
11184 /// This routine returns the resulting FunctionDecl if it could be
11185 /// resolved, and NULL otherwise. When @p Complain is true, this
11186 /// routine will emit diagnostics if there is an error.
11187 FunctionDecl *
11188 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11189                                          QualType TargetType,
11190                                          bool Complain,
11191                                          DeclAccessPair &FoundResult,
11192                                          bool *pHadMultipleCandidates) {
11193   assert(AddressOfExpr->getType() == Context.OverloadTy);
11194 
11195   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11196                                      Complain);
11197   int NumMatches = Resolver.getNumMatches();
11198   FunctionDecl *Fn = nullptr;
11199   bool ShouldComplain = Complain && !Resolver.hasComplained();
11200   if (NumMatches == 0 && ShouldComplain) {
11201     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11202       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11203     else
11204       Resolver.ComplainNoMatchesFound();
11205   }
11206   else if (NumMatches > 1 && ShouldComplain)
11207     Resolver.ComplainMultipleMatchesFound();
11208   else if (NumMatches == 1) {
11209     Fn = Resolver.getMatchingFunctionDecl();
11210     assert(Fn);
11211     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11212       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11213     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11214     if (Complain) {
11215       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11216         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11217       else
11218         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11219     }
11220   }
11221 
11222   if (pHadMultipleCandidates)
11223     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11224   return Fn;
11225 }
11226 
11227 /// \brief Given an expression that refers to an overloaded function, try to
11228 /// resolve that function to a single function that can have its address taken.
11229 /// This will modify `Pair` iff it returns non-null.
11230 ///
11231 /// This routine can only realistically succeed if all but one candidates in the
11232 /// overload set for SrcExpr cannot have their addresses taken.
11233 FunctionDecl *
11234 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11235                                                   DeclAccessPair &Pair) {
11236   OverloadExpr::FindResult R = OverloadExpr::find(E);
11237   OverloadExpr *Ovl = R.Expression;
11238   FunctionDecl *Result = nullptr;
11239   DeclAccessPair DAP;
11240   // Don't use the AddressOfResolver because we're specifically looking for
11241   // cases where we have one overload candidate that lacks
11242   // enable_if/pass_object_size/...
11243   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11244     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11245     if (!FD)
11246       return nullptr;
11247 
11248     if (!checkAddressOfFunctionIsAvailable(FD))
11249       continue;
11250 
11251     // We have more than one result; quit.
11252     if (Result)
11253       return nullptr;
11254     DAP = I.getPair();
11255     Result = FD;
11256   }
11257 
11258   if (Result)
11259     Pair = DAP;
11260   return Result;
11261 }
11262 
11263 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11264 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11265 /// will perform access checks, diagnose the use of the resultant decl, and, if
11266 /// requested, potentially perform a function-to-pointer decay.
11267 ///
11268 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11269 /// Otherwise, returns true. This may emit diagnostics and return true.
11270 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11271     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11272   Expr *E = SrcExpr.get();
11273   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11274 
11275   DeclAccessPair DAP;
11276   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11277   if (!Found)
11278     return false;
11279 
11280   // Emitting multiple diagnostics for a function that is both inaccessible and
11281   // unavailable is consistent with our behavior elsewhere. So, always check
11282   // for both.
11283   DiagnoseUseOfDecl(Found, E->getExprLoc());
11284   CheckAddressOfMemberAccess(E, DAP);
11285   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11286   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11287     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11288   else
11289     SrcExpr = Fixed;
11290   return true;
11291 }
11292 
11293 /// \brief Given an expression that refers to an overloaded function, try to
11294 /// resolve that overloaded function expression down to a single function.
11295 ///
11296 /// This routine can only resolve template-ids that refer to a single function
11297 /// template, where that template-id refers to a single template whose template
11298 /// arguments are either provided by the template-id or have defaults,
11299 /// as described in C++0x [temp.arg.explicit]p3.
11300 ///
11301 /// If no template-ids are found, no diagnostics are emitted and NULL is
11302 /// returned.
11303 FunctionDecl *
11304 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11305                                                   bool Complain,
11306                                                   DeclAccessPair *FoundResult) {
11307   // C++ [over.over]p1:
11308   //   [...] [Note: any redundant set of parentheses surrounding the
11309   //   overloaded function name is ignored (5.1). ]
11310   // C++ [over.over]p1:
11311   //   [...] The overloaded function name can be preceded by the &
11312   //   operator.
11313 
11314   // If we didn't actually find any template-ids, we're done.
11315   if (!ovl->hasExplicitTemplateArgs())
11316     return nullptr;
11317 
11318   TemplateArgumentListInfo ExplicitTemplateArgs;
11319   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11320   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11321 
11322   // Look through all of the overloaded functions, searching for one
11323   // whose type matches exactly.
11324   FunctionDecl *Matched = nullptr;
11325   for (UnresolvedSetIterator I = ovl->decls_begin(),
11326          E = ovl->decls_end(); I != E; ++I) {
11327     // C++0x [temp.arg.explicit]p3:
11328     //   [...] In contexts where deduction is done and fails, or in contexts
11329     //   where deduction is not done, if a template argument list is
11330     //   specified and it, along with any default template arguments,
11331     //   identifies a single function template specialization, then the
11332     //   template-id is an lvalue for the function template specialization.
11333     FunctionTemplateDecl *FunctionTemplate
11334       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11335 
11336     // C++ [over.over]p2:
11337     //   If the name is a function template, template argument deduction is
11338     //   done (14.8.2.2), and if the argument deduction succeeds, the
11339     //   resulting template argument list is used to generate a single
11340     //   function template specialization, which is added to the set of
11341     //   overloaded functions considered.
11342     FunctionDecl *Specialization = nullptr;
11343     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11344     if (TemplateDeductionResult Result
11345           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11346                                     Specialization, Info,
11347                                     /*IsAddressOfFunction*/true)) {
11348       // Make a note of the failed deduction for diagnostics.
11349       // TODO: Actually use the failed-deduction info?
11350       FailedCandidates.addCandidate()
11351           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11352                MakeDeductionFailureInfo(Context, Result, Info));
11353       continue;
11354     }
11355 
11356     assert(Specialization && "no specialization and no error?");
11357 
11358     // Multiple matches; we can't resolve to a single declaration.
11359     if (Matched) {
11360       if (Complain) {
11361         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11362           << ovl->getName();
11363         NoteAllOverloadCandidates(ovl);
11364       }
11365       return nullptr;
11366     }
11367 
11368     Matched = Specialization;
11369     if (FoundResult) *FoundResult = I.getPair();
11370   }
11371 
11372   if (Matched &&
11373       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11374     return nullptr;
11375 
11376   return Matched;
11377 }
11378 
11379 // Resolve and fix an overloaded expression that can be resolved
11380 // because it identifies a single function template specialization.
11381 //
11382 // Last three arguments should only be supplied if Complain = true
11383 //
11384 // Return true if it was logically possible to so resolve the
11385 // expression, regardless of whether or not it succeeded.  Always
11386 // returns true if 'complain' is set.
11387 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11388                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11389                       bool complain, SourceRange OpRangeForComplaining,
11390                                            QualType DestTypeForComplaining,
11391                                             unsigned DiagIDForComplaining) {
11392   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11393 
11394   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11395 
11396   DeclAccessPair found;
11397   ExprResult SingleFunctionExpression;
11398   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11399                            ovl.Expression, /*complain*/ false, &found)) {
11400     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11401       SrcExpr = ExprError();
11402       return true;
11403     }
11404 
11405     // It is only correct to resolve to an instance method if we're
11406     // resolving a form that's permitted to be a pointer to member.
11407     // Otherwise we'll end up making a bound member expression, which
11408     // is illegal in all the contexts we resolve like this.
11409     if (!ovl.HasFormOfMemberPointer &&
11410         isa<CXXMethodDecl>(fn) &&
11411         cast<CXXMethodDecl>(fn)->isInstance()) {
11412       if (!complain) return false;
11413 
11414       Diag(ovl.Expression->getExprLoc(),
11415            diag::err_bound_member_function)
11416         << 0 << ovl.Expression->getSourceRange();
11417 
11418       // TODO: I believe we only end up here if there's a mix of
11419       // static and non-static candidates (otherwise the expression
11420       // would have 'bound member' type, not 'overload' type).
11421       // Ideally we would note which candidate was chosen and why
11422       // the static candidates were rejected.
11423       SrcExpr = ExprError();
11424       return true;
11425     }
11426 
11427     // Fix the expression to refer to 'fn'.
11428     SingleFunctionExpression =
11429         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11430 
11431     // If desired, do function-to-pointer decay.
11432     if (doFunctionPointerConverion) {
11433       SingleFunctionExpression =
11434         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11435       if (SingleFunctionExpression.isInvalid()) {
11436         SrcExpr = ExprError();
11437         return true;
11438       }
11439     }
11440   }
11441 
11442   if (!SingleFunctionExpression.isUsable()) {
11443     if (complain) {
11444       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11445         << ovl.Expression->getName()
11446         << DestTypeForComplaining
11447         << OpRangeForComplaining
11448         << ovl.Expression->getQualifierLoc().getSourceRange();
11449       NoteAllOverloadCandidates(SrcExpr.get());
11450 
11451       SrcExpr = ExprError();
11452       return true;
11453     }
11454 
11455     return false;
11456   }
11457 
11458   SrcExpr = SingleFunctionExpression;
11459   return true;
11460 }
11461 
11462 /// \brief Add a single candidate to the overload set.
11463 static void AddOverloadedCallCandidate(Sema &S,
11464                                        DeclAccessPair FoundDecl,
11465                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11466                                        ArrayRef<Expr *> Args,
11467                                        OverloadCandidateSet &CandidateSet,
11468                                        bool PartialOverloading,
11469                                        bool KnownValid) {
11470   NamedDecl *Callee = FoundDecl.getDecl();
11471   if (isa<UsingShadowDecl>(Callee))
11472     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11473 
11474   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11475     if (ExplicitTemplateArgs) {
11476       assert(!KnownValid && "Explicit template arguments?");
11477       return;
11478     }
11479     // Prevent ill-formed function decls to be added as overload candidates.
11480     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11481       return;
11482 
11483     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11484                            /*SuppressUsedConversions=*/false,
11485                            PartialOverloading);
11486     return;
11487   }
11488 
11489   if (FunctionTemplateDecl *FuncTemplate
11490       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11491     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11492                                    ExplicitTemplateArgs, Args, CandidateSet,
11493                                    /*SuppressUsedConversions=*/false,
11494                                    PartialOverloading);
11495     return;
11496   }
11497 
11498   assert(!KnownValid && "unhandled case in overloaded call candidate");
11499 }
11500 
11501 /// \brief Add the overload candidates named by callee and/or found by argument
11502 /// dependent lookup to the given overload set.
11503 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11504                                        ArrayRef<Expr *> Args,
11505                                        OverloadCandidateSet &CandidateSet,
11506                                        bool PartialOverloading) {
11507 
11508 #ifndef NDEBUG
11509   // Verify that ArgumentDependentLookup is consistent with the rules
11510   // in C++0x [basic.lookup.argdep]p3:
11511   //
11512   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11513   //   and let Y be the lookup set produced by argument dependent
11514   //   lookup (defined as follows). If X contains
11515   //
11516   //     -- a declaration of a class member, or
11517   //
11518   //     -- a block-scope function declaration that is not a
11519   //        using-declaration, or
11520   //
11521   //     -- a declaration that is neither a function or a function
11522   //        template
11523   //
11524   //   then Y is empty.
11525 
11526   if (ULE->requiresADL()) {
11527     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11528            E = ULE->decls_end(); I != E; ++I) {
11529       assert(!(*I)->getDeclContext()->isRecord());
11530       assert(isa<UsingShadowDecl>(*I) ||
11531              !(*I)->getDeclContext()->isFunctionOrMethod());
11532       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11533     }
11534   }
11535 #endif
11536 
11537   // It would be nice to avoid this copy.
11538   TemplateArgumentListInfo TABuffer;
11539   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11540   if (ULE->hasExplicitTemplateArgs()) {
11541     ULE->copyTemplateArgumentsInto(TABuffer);
11542     ExplicitTemplateArgs = &TABuffer;
11543   }
11544 
11545   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11546          E = ULE->decls_end(); I != E; ++I)
11547     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11548                                CandidateSet, PartialOverloading,
11549                                /*KnownValid*/ true);
11550 
11551   if (ULE->requiresADL())
11552     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11553                                          Args, ExplicitTemplateArgs,
11554                                          CandidateSet, PartialOverloading);
11555 }
11556 
11557 /// Determine whether a declaration with the specified name could be moved into
11558 /// a different namespace.
11559 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11560   switch (Name.getCXXOverloadedOperator()) {
11561   case OO_New: case OO_Array_New:
11562   case OO_Delete: case OO_Array_Delete:
11563     return false;
11564 
11565   default:
11566     return true;
11567   }
11568 }
11569 
11570 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11571 /// template, where the non-dependent name was declared after the template
11572 /// was defined. This is common in code written for a compilers which do not
11573 /// correctly implement two-stage name lookup.
11574 ///
11575 /// Returns true if a viable candidate was found and a diagnostic was issued.
11576 static bool
11577 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11578                        const CXXScopeSpec &SS, LookupResult &R,
11579                        OverloadCandidateSet::CandidateSetKind CSK,
11580                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11581                        ArrayRef<Expr *> Args,
11582                        bool *DoDiagnoseEmptyLookup = nullptr) {
11583   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11584     return false;
11585 
11586   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11587     if (DC->isTransparentContext())
11588       continue;
11589 
11590     SemaRef.LookupQualifiedName(R, DC);
11591 
11592     if (!R.empty()) {
11593       R.suppressDiagnostics();
11594 
11595       if (isa<CXXRecordDecl>(DC)) {
11596         // Don't diagnose names we find in classes; we get much better
11597         // diagnostics for these from DiagnoseEmptyLookup.
11598         R.clear();
11599         if (DoDiagnoseEmptyLookup)
11600           *DoDiagnoseEmptyLookup = true;
11601         return false;
11602       }
11603 
11604       OverloadCandidateSet Candidates(FnLoc, CSK);
11605       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11606         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11607                                    ExplicitTemplateArgs, Args,
11608                                    Candidates, false, /*KnownValid*/ false);
11609 
11610       OverloadCandidateSet::iterator Best;
11611       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11612         // No viable functions. Don't bother the user with notes for functions
11613         // which don't work and shouldn't be found anyway.
11614         R.clear();
11615         return false;
11616       }
11617 
11618       // Find the namespaces where ADL would have looked, and suggest
11619       // declaring the function there instead.
11620       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11621       Sema::AssociatedClassSet AssociatedClasses;
11622       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11623                                                  AssociatedNamespaces,
11624                                                  AssociatedClasses);
11625       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11626       if (canBeDeclaredInNamespace(R.getLookupName())) {
11627         DeclContext *Std = SemaRef.getStdNamespace();
11628         for (Sema::AssociatedNamespaceSet::iterator
11629                it = AssociatedNamespaces.begin(),
11630                end = AssociatedNamespaces.end(); it != end; ++it) {
11631           // Never suggest declaring a function within namespace 'std'.
11632           if (Std && Std->Encloses(*it))
11633             continue;
11634 
11635           // Never suggest declaring a function within a namespace with a
11636           // reserved name, like __gnu_cxx.
11637           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11638           if (NS &&
11639               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11640             continue;
11641 
11642           SuggestedNamespaces.insert(*it);
11643         }
11644       }
11645 
11646       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11647         << R.getLookupName();
11648       if (SuggestedNamespaces.empty()) {
11649         SemaRef.Diag(Best->Function->getLocation(),
11650                      diag::note_not_found_by_two_phase_lookup)
11651           << R.getLookupName() << 0;
11652       } else if (SuggestedNamespaces.size() == 1) {
11653         SemaRef.Diag(Best->Function->getLocation(),
11654                      diag::note_not_found_by_two_phase_lookup)
11655           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11656       } else {
11657         // FIXME: It would be useful to list the associated namespaces here,
11658         // but the diagnostics infrastructure doesn't provide a way to produce
11659         // a localized representation of a list of items.
11660         SemaRef.Diag(Best->Function->getLocation(),
11661                      diag::note_not_found_by_two_phase_lookup)
11662           << R.getLookupName() << 2;
11663       }
11664 
11665       // Try to recover by calling this function.
11666       return true;
11667     }
11668 
11669     R.clear();
11670   }
11671 
11672   return false;
11673 }
11674 
11675 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11676 /// template, where the non-dependent operator was declared after the template
11677 /// was defined.
11678 ///
11679 /// Returns true if a viable candidate was found and a diagnostic was issued.
11680 static bool
11681 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11682                                SourceLocation OpLoc,
11683                                ArrayRef<Expr *> Args) {
11684   DeclarationName OpName =
11685     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11686   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11687   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11688                                 OverloadCandidateSet::CSK_Operator,
11689                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11690 }
11691 
11692 namespace {
11693 class BuildRecoveryCallExprRAII {
11694   Sema &SemaRef;
11695 public:
11696   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11697     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11698     SemaRef.IsBuildingRecoveryCallExpr = true;
11699   }
11700 
11701   ~BuildRecoveryCallExprRAII() {
11702     SemaRef.IsBuildingRecoveryCallExpr = false;
11703   }
11704 };
11705 
11706 }
11707 
11708 static std::unique_ptr<CorrectionCandidateCallback>
11709 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11710               bool HasTemplateArgs, bool AllowTypoCorrection) {
11711   if (!AllowTypoCorrection)
11712     return llvm::make_unique<NoTypoCorrectionCCC>();
11713   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11714                                                   HasTemplateArgs, ME);
11715 }
11716 
11717 /// Attempts to recover from a call where no functions were found.
11718 ///
11719 /// Returns true if new candidates were found.
11720 static ExprResult
11721 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11722                       UnresolvedLookupExpr *ULE,
11723                       SourceLocation LParenLoc,
11724                       MutableArrayRef<Expr *> Args,
11725                       SourceLocation RParenLoc,
11726                       bool EmptyLookup, bool AllowTypoCorrection) {
11727   // Do not try to recover if it is already building a recovery call.
11728   // This stops infinite loops for template instantiations like
11729   //
11730   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11731   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11732   //
11733   if (SemaRef.IsBuildingRecoveryCallExpr)
11734     return ExprError();
11735   BuildRecoveryCallExprRAII RCE(SemaRef);
11736 
11737   CXXScopeSpec SS;
11738   SS.Adopt(ULE->getQualifierLoc());
11739   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11740 
11741   TemplateArgumentListInfo TABuffer;
11742   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11743   if (ULE->hasExplicitTemplateArgs()) {
11744     ULE->copyTemplateArgumentsInto(TABuffer);
11745     ExplicitTemplateArgs = &TABuffer;
11746   }
11747 
11748   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11749                  Sema::LookupOrdinaryName);
11750   bool DoDiagnoseEmptyLookup = EmptyLookup;
11751   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11752                               OverloadCandidateSet::CSK_Normal,
11753                               ExplicitTemplateArgs, Args,
11754                               &DoDiagnoseEmptyLookup) &&
11755     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11756         S, SS, R,
11757         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11758                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11759         ExplicitTemplateArgs, Args)))
11760     return ExprError();
11761 
11762   assert(!R.empty() && "lookup results empty despite recovery");
11763 
11764   // If recovery created an ambiguity, just bail out.
11765   if (R.isAmbiguous()) {
11766     R.suppressDiagnostics();
11767     return ExprError();
11768   }
11769 
11770   // Build an implicit member call if appropriate.  Just drop the
11771   // casts and such from the call, we don't really care.
11772   ExprResult NewFn = ExprError();
11773   if ((*R.begin())->isCXXClassMember())
11774     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11775                                                     ExplicitTemplateArgs, S);
11776   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11777     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11778                                         ExplicitTemplateArgs);
11779   else
11780     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11781 
11782   if (NewFn.isInvalid())
11783     return ExprError();
11784 
11785   // This shouldn't cause an infinite loop because we're giving it
11786   // an expression with viable lookup results, which should never
11787   // end up here.
11788   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11789                                MultiExprArg(Args.data(), Args.size()),
11790                                RParenLoc);
11791 }
11792 
11793 /// \brief Constructs and populates an OverloadedCandidateSet from
11794 /// the given function.
11795 /// \returns true when an the ExprResult output parameter has been set.
11796 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11797                                   UnresolvedLookupExpr *ULE,
11798                                   MultiExprArg Args,
11799                                   SourceLocation RParenLoc,
11800                                   OverloadCandidateSet *CandidateSet,
11801                                   ExprResult *Result) {
11802 #ifndef NDEBUG
11803   if (ULE->requiresADL()) {
11804     // To do ADL, we must have found an unqualified name.
11805     assert(!ULE->getQualifier() && "qualified name with ADL");
11806 
11807     // We don't perform ADL for implicit declarations of builtins.
11808     // Verify that this was correctly set up.
11809     FunctionDecl *F;
11810     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11811         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11812         F->getBuiltinID() && F->isImplicit())
11813       llvm_unreachable("performing ADL for builtin");
11814 
11815     // We don't perform ADL in C.
11816     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11817   }
11818 #endif
11819 
11820   UnbridgedCastsSet UnbridgedCasts;
11821   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11822     *Result = ExprError();
11823     return true;
11824   }
11825 
11826   // Add the functions denoted by the callee to the set of candidate
11827   // functions, including those from argument-dependent lookup.
11828   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11829 
11830   if (getLangOpts().MSVCCompat &&
11831       CurContext->isDependentContext() && !isSFINAEContext() &&
11832       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11833 
11834     OverloadCandidateSet::iterator Best;
11835     if (CandidateSet->empty() ||
11836         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11837             OR_No_Viable_Function) {
11838       // In Microsoft mode, if we are inside a template class member function then
11839       // create a type dependent CallExpr. The goal is to postpone name lookup
11840       // to instantiation time to be able to search into type dependent base
11841       // classes.
11842       CallExpr *CE = new (Context) CallExpr(
11843           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11844       CE->setTypeDependent(true);
11845       CE->setValueDependent(true);
11846       CE->setInstantiationDependent(true);
11847       *Result = CE;
11848       return true;
11849     }
11850   }
11851 
11852   if (CandidateSet->empty())
11853     return false;
11854 
11855   UnbridgedCasts.restore();
11856   return false;
11857 }
11858 
11859 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11860 /// the completed call expression. If overload resolution fails, emits
11861 /// diagnostics and returns ExprError()
11862 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11863                                            UnresolvedLookupExpr *ULE,
11864                                            SourceLocation LParenLoc,
11865                                            MultiExprArg Args,
11866                                            SourceLocation RParenLoc,
11867                                            Expr *ExecConfig,
11868                                            OverloadCandidateSet *CandidateSet,
11869                                            OverloadCandidateSet::iterator *Best,
11870                                            OverloadingResult OverloadResult,
11871                                            bool AllowTypoCorrection) {
11872   if (CandidateSet->empty())
11873     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11874                                  RParenLoc, /*EmptyLookup=*/true,
11875                                  AllowTypoCorrection);
11876 
11877   switch (OverloadResult) {
11878   case OR_Success: {
11879     FunctionDecl *FDecl = (*Best)->Function;
11880     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11881     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11882       return ExprError();
11883     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11884     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11885                                          ExecConfig);
11886   }
11887 
11888   case OR_No_Viable_Function: {
11889     // Try to recover by looking for viable functions which the user might
11890     // have meant to call.
11891     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11892                                                 Args, RParenLoc,
11893                                                 /*EmptyLookup=*/false,
11894                                                 AllowTypoCorrection);
11895     if (!Recovery.isInvalid())
11896       return Recovery;
11897 
11898     // If the user passes in a function that we can't take the address of, we
11899     // generally end up emitting really bad error messages. Here, we attempt to
11900     // emit better ones.
11901     for (const Expr *Arg : Args) {
11902       if (!Arg->getType()->isFunctionType())
11903         continue;
11904       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11905         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11906         if (FD &&
11907             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11908                                                        Arg->getExprLoc()))
11909           return ExprError();
11910       }
11911     }
11912 
11913     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11914         << ULE->getName() << Fn->getSourceRange();
11915     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11916     break;
11917   }
11918 
11919   case OR_Ambiguous:
11920     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11921       << ULE->getName() << Fn->getSourceRange();
11922     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11923     break;
11924 
11925   case OR_Deleted: {
11926     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11927       << (*Best)->Function->isDeleted()
11928       << ULE->getName()
11929       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11930       << Fn->getSourceRange();
11931     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11932 
11933     // We emitted an error for the unavailable/deleted function call but keep
11934     // the call in the AST.
11935     FunctionDecl *FDecl = (*Best)->Function;
11936     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11937     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11938                                          ExecConfig);
11939   }
11940   }
11941 
11942   // Overload resolution failed.
11943   return ExprError();
11944 }
11945 
11946 static void markUnaddressableCandidatesUnviable(Sema &S,
11947                                                 OverloadCandidateSet &CS) {
11948   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11949     if (I->Viable &&
11950         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11951       I->Viable = false;
11952       I->FailureKind = ovl_fail_addr_not_available;
11953     }
11954   }
11955 }
11956 
11957 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11958 /// (which eventually refers to the declaration Func) and the call
11959 /// arguments Args/NumArgs, attempt to resolve the function call down
11960 /// to a specific function. If overload resolution succeeds, returns
11961 /// the call expression produced by overload resolution.
11962 /// Otherwise, emits diagnostics and returns ExprError.
11963 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11964                                          UnresolvedLookupExpr *ULE,
11965                                          SourceLocation LParenLoc,
11966                                          MultiExprArg Args,
11967                                          SourceLocation RParenLoc,
11968                                          Expr *ExecConfig,
11969                                          bool AllowTypoCorrection,
11970                                          bool CalleesAddressIsTaken) {
11971   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11972                                     OverloadCandidateSet::CSK_Normal);
11973   ExprResult result;
11974 
11975   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11976                              &result))
11977     return result;
11978 
11979   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11980   // functions that aren't addressible are considered unviable.
11981   if (CalleesAddressIsTaken)
11982     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11983 
11984   OverloadCandidateSet::iterator Best;
11985   OverloadingResult OverloadResult =
11986       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11987 
11988   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11989                                   RParenLoc, ExecConfig, &CandidateSet,
11990                                   &Best, OverloadResult,
11991                                   AllowTypoCorrection);
11992 }
11993 
11994 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11995   return Functions.size() > 1 ||
11996     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11997 }
11998 
11999 /// \brief Create a unary operation that may resolve to an overloaded
12000 /// operator.
12001 ///
12002 /// \param OpLoc The location of the operator itself (e.g., '*').
12003 ///
12004 /// \param Opc The UnaryOperatorKind that describes this operator.
12005 ///
12006 /// \param Fns The set of non-member functions that will be
12007 /// considered by overload resolution. The caller needs to build this
12008 /// set based on the context using, e.g.,
12009 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12010 /// set should not contain any member functions; those will be added
12011 /// by CreateOverloadedUnaryOp().
12012 ///
12013 /// \param Input The input argument.
12014 ExprResult
12015 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12016                               const UnresolvedSetImpl &Fns,
12017                               Expr *Input, bool PerformADL) {
12018   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12019   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12020   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12021   // TODO: provide better source location info.
12022   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12023 
12024   if (checkPlaceholderForOverload(*this, Input))
12025     return ExprError();
12026 
12027   Expr *Args[2] = { Input, nullptr };
12028   unsigned NumArgs = 1;
12029 
12030   // For post-increment and post-decrement, add the implicit '0' as
12031   // the second argument, so that we know this is a post-increment or
12032   // post-decrement.
12033   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12034     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12035     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12036                                      SourceLocation());
12037     NumArgs = 2;
12038   }
12039 
12040   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12041 
12042   if (Input->isTypeDependent()) {
12043     if (Fns.empty())
12044       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12045                                          VK_RValue, OK_Ordinary, OpLoc, false);
12046 
12047     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12048     UnresolvedLookupExpr *Fn
12049       = UnresolvedLookupExpr::Create(Context, NamingClass,
12050                                      NestedNameSpecifierLoc(), OpNameInfo,
12051                                      /*ADL*/ true, IsOverloaded(Fns),
12052                                      Fns.begin(), Fns.end());
12053     return new (Context)
12054         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12055                             VK_RValue, OpLoc, FPOptions());
12056   }
12057 
12058   // Build an empty overload set.
12059   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12060 
12061   // Add the candidates from the given function set.
12062   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12063 
12064   // Add operator candidates that are member functions.
12065   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12066 
12067   // Add candidates from ADL.
12068   if (PerformADL) {
12069     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12070                                          /*ExplicitTemplateArgs*/nullptr,
12071                                          CandidateSet);
12072   }
12073 
12074   // Add builtin operator candidates.
12075   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12076 
12077   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12078 
12079   // Perform overload resolution.
12080   OverloadCandidateSet::iterator Best;
12081   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12082   case OR_Success: {
12083     // We found a built-in operator or an overloaded operator.
12084     FunctionDecl *FnDecl = Best->Function;
12085 
12086     if (FnDecl) {
12087       Expr *Base = nullptr;
12088       // We matched an overloaded operator. Build a call to that
12089       // operator.
12090 
12091       // Convert the arguments.
12092       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12093         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12094 
12095         ExprResult InputRes =
12096           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12097                                               Best->FoundDecl, Method);
12098         if (InputRes.isInvalid())
12099           return ExprError();
12100         Base = Input = InputRes.get();
12101       } else {
12102         // Convert the arguments.
12103         ExprResult InputInit
12104           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12105                                                       Context,
12106                                                       FnDecl->getParamDecl(0)),
12107                                       SourceLocation(),
12108                                       Input);
12109         if (InputInit.isInvalid())
12110           return ExprError();
12111         Input = InputInit.get();
12112       }
12113 
12114       // Build the actual expression node.
12115       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12116                                                 Base, HadMultipleCandidates,
12117                                                 OpLoc);
12118       if (FnExpr.isInvalid())
12119         return ExprError();
12120 
12121       // Determine the result type.
12122       QualType ResultTy = FnDecl->getReturnType();
12123       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12124       ResultTy = ResultTy.getNonLValueExprType(Context);
12125 
12126       Args[0] = Input;
12127       CallExpr *TheCall =
12128         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12129                                           ResultTy, VK, OpLoc, FPOptions());
12130 
12131       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12132         return ExprError();
12133 
12134       if (CheckFunctionCall(FnDecl, TheCall,
12135                             FnDecl->getType()->castAs<FunctionProtoType>()))
12136         return ExprError();
12137 
12138       return MaybeBindToTemporary(TheCall);
12139     } else {
12140       // We matched a built-in operator. Convert the arguments, then
12141       // break out so that we will build the appropriate built-in
12142       // operator node.
12143       ExprResult InputRes = PerformImplicitConversion(
12144           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12145       if (InputRes.isInvalid())
12146         return ExprError();
12147       Input = InputRes.get();
12148       break;
12149     }
12150   }
12151 
12152   case OR_No_Viable_Function:
12153     // This is an erroneous use of an operator which can be overloaded by
12154     // a non-member function. Check for non-member operators which were
12155     // defined too late to be candidates.
12156     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12157       // FIXME: Recover by calling the found function.
12158       return ExprError();
12159 
12160     // No viable function; fall through to handling this as a
12161     // built-in operator, which will produce an error message for us.
12162     break;
12163 
12164   case OR_Ambiguous:
12165     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12166         << UnaryOperator::getOpcodeStr(Opc)
12167         << Input->getType()
12168         << Input->getSourceRange();
12169     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12170                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12171     return ExprError();
12172 
12173   case OR_Deleted:
12174     Diag(OpLoc, diag::err_ovl_deleted_oper)
12175       << Best->Function->isDeleted()
12176       << UnaryOperator::getOpcodeStr(Opc)
12177       << getDeletedOrUnavailableSuffix(Best->Function)
12178       << Input->getSourceRange();
12179     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12180                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12181     return ExprError();
12182   }
12183 
12184   // Either we found no viable overloaded operator or we matched a
12185   // built-in operator. In either case, fall through to trying to
12186   // build a built-in operation.
12187   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12188 }
12189 
12190 /// \brief Create a binary operation that may resolve to an overloaded
12191 /// operator.
12192 ///
12193 /// \param OpLoc The location of the operator itself (e.g., '+').
12194 ///
12195 /// \param Opc The BinaryOperatorKind that describes this operator.
12196 ///
12197 /// \param Fns The set of non-member functions that will be
12198 /// considered by overload resolution. The caller needs to build this
12199 /// set based on the context using, e.g.,
12200 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12201 /// set should not contain any member functions; those will be added
12202 /// by CreateOverloadedBinOp().
12203 ///
12204 /// \param LHS Left-hand argument.
12205 /// \param RHS Right-hand argument.
12206 ExprResult
12207 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12208                             BinaryOperatorKind Opc,
12209                             const UnresolvedSetImpl &Fns,
12210                             Expr *LHS, Expr *RHS, bool PerformADL) {
12211   Expr *Args[2] = { LHS, RHS };
12212   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12213 
12214   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12215   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12216 
12217   // If either side is type-dependent, create an appropriate dependent
12218   // expression.
12219   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12220     if (Fns.empty()) {
12221       // If there are no functions to store, just build a dependent
12222       // BinaryOperator or CompoundAssignment.
12223       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12224         return new (Context) BinaryOperator(
12225             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12226             OpLoc, FPFeatures);
12227 
12228       return new (Context) CompoundAssignOperator(
12229           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12230           Context.DependentTy, Context.DependentTy, OpLoc,
12231           FPFeatures);
12232     }
12233 
12234     // FIXME: save results of ADL from here?
12235     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12236     // TODO: provide better source location info in DNLoc component.
12237     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12238     UnresolvedLookupExpr *Fn
12239       = UnresolvedLookupExpr::Create(Context, NamingClass,
12240                                      NestedNameSpecifierLoc(), OpNameInfo,
12241                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12242                                      Fns.begin(), Fns.end());
12243     return new (Context)
12244         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12245                             VK_RValue, OpLoc, FPFeatures);
12246   }
12247 
12248   // Always do placeholder-like conversions on the RHS.
12249   if (checkPlaceholderForOverload(*this, Args[1]))
12250     return ExprError();
12251 
12252   // Do placeholder-like conversion on the LHS; note that we should
12253   // not get here with a PseudoObject LHS.
12254   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12255   if (checkPlaceholderForOverload(*this, Args[0]))
12256     return ExprError();
12257 
12258   // If this is the assignment operator, we only perform overload resolution
12259   // if the left-hand side is a class or enumeration type. This is actually
12260   // a hack. The standard requires that we do overload resolution between the
12261   // various built-in candidates, but as DR507 points out, this can lead to
12262   // problems. So we do it this way, which pretty much follows what GCC does.
12263   // Note that we go the traditional code path for compound assignment forms.
12264   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12265     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12266 
12267   // If this is the .* operator, which is not overloadable, just
12268   // create a built-in binary operator.
12269   if (Opc == BO_PtrMemD)
12270     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12271 
12272   // Build an empty overload set.
12273   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12274 
12275   // Add the candidates from the given function set.
12276   AddFunctionCandidates(Fns, Args, CandidateSet);
12277 
12278   // Add operator candidates that are member functions.
12279   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12280 
12281   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12282   // performed for an assignment operator (nor for operator[] nor operator->,
12283   // which don't get here).
12284   if (Opc != BO_Assign && PerformADL)
12285     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12286                                          /*ExplicitTemplateArgs*/ nullptr,
12287                                          CandidateSet);
12288 
12289   // Add builtin operator candidates.
12290   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12291 
12292   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12293 
12294   // Perform overload resolution.
12295   OverloadCandidateSet::iterator Best;
12296   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12297     case OR_Success: {
12298       // We found a built-in operator or an overloaded operator.
12299       FunctionDecl *FnDecl = Best->Function;
12300 
12301       if (FnDecl) {
12302         Expr *Base = nullptr;
12303         // We matched an overloaded operator. Build a call to that
12304         // operator.
12305 
12306         // Convert the arguments.
12307         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12308           // Best->Access is only meaningful for class members.
12309           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12310 
12311           ExprResult Arg1 =
12312             PerformCopyInitialization(
12313               InitializedEntity::InitializeParameter(Context,
12314                                                      FnDecl->getParamDecl(0)),
12315               SourceLocation(), Args[1]);
12316           if (Arg1.isInvalid())
12317             return ExprError();
12318 
12319           ExprResult Arg0 =
12320             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12321                                                 Best->FoundDecl, Method);
12322           if (Arg0.isInvalid())
12323             return ExprError();
12324           Base = Args[0] = Arg0.getAs<Expr>();
12325           Args[1] = RHS = Arg1.getAs<Expr>();
12326         } else {
12327           // Convert the arguments.
12328           ExprResult Arg0 = PerformCopyInitialization(
12329             InitializedEntity::InitializeParameter(Context,
12330                                                    FnDecl->getParamDecl(0)),
12331             SourceLocation(), Args[0]);
12332           if (Arg0.isInvalid())
12333             return ExprError();
12334 
12335           ExprResult Arg1 =
12336             PerformCopyInitialization(
12337               InitializedEntity::InitializeParameter(Context,
12338                                                      FnDecl->getParamDecl(1)),
12339               SourceLocation(), Args[1]);
12340           if (Arg1.isInvalid())
12341             return ExprError();
12342           Args[0] = LHS = Arg0.getAs<Expr>();
12343           Args[1] = RHS = Arg1.getAs<Expr>();
12344         }
12345 
12346         // Build the actual expression node.
12347         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12348                                                   Best->FoundDecl, Base,
12349                                                   HadMultipleCandidates, OpLoc);
12350         if (FnExpr.isInvalid())
12351           return ExprError();
12352 
12353         // Determine the result type.
12354         QualType ResultTy = FnDecl->getReturnType();
12355         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12356         ResultTy = ResultTy.getNonLValueExprType(Context);
12357 
12358         CXXOperatorCallExpr *TheCall =
12359           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12360                                             Args, ResultTy, VK, OpLoc,
12361                                             FPFeatures);
12362 
12363         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12364                                 FnDecl))
12365           return ExprError();
12366 
12367         ArrayRef<const Expr *> ArgsArray(Args, 2);
12368         const Expr *ImplicitThis = nullptr;
12369         // Cut off the implicit 'this'.
12370         if (isa<CXXMethodDecl>(FnDecl)) {
12371           ImplicitThis = ArgsArray[0];
12372           ArgsArray = ArgsArray.slice(1);
12373         }
12374 
12375         // Check for a self move.
12376         if (Op == OO_Equal)
12377           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12378 
12379         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12380                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12381                   VariadicDoesNotApply);
12382 
12383         return MaybeBindToTemporary(TheCall);
12384       } else {
12385         // We matched a built-in operator. Convert the arguments, then
12386         // break out so that we will build the appropriate built-in
12387         // operator node.
12388         ExprResult ArgsRes0 =
12389             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12390                                       Best->Conversions[0], AA_Passing);
12391         if (ArgsRes0.isInvalid())
12392           return ExprError();
12393         Args[0] = ArgsRes0.get();
12394 
12395         ExprResult ArgsRes1 =
12396             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12397                                       Best->Conversions[1], AA_Passing);
12398         if (ArgsRes1.isInvalid())
12399           return ExprError();
12400         Args[1] = ArgsRes1.get();
12401         break;
12402       }
12403     }
12404 
12405     case OR_No_Viable_Function: {
12406       // C++ [over.match.oper]p9:
12407       //   If the operator is the operator , [...] and there are no
12408       //   viable functions, then the operator is assumed to be the
12409       //   built-in operator and interpreted according to clause 5.
12410       if (Opc == BO_Comma)
12411         break;
12412 
12413       // For class as left operand for assignment or compound assignment
12414       // operator do not fall through to handling in built-in, but report that
12415       // no overloaded assignment operator found
12416       ExprResult Result = ExprError();
12417       if (Args[0]->getType()->isRecordType() &&
12418           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12419         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12420              << BinaryOperator::getOpcodeStr(Opc)
12421              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12422         if (Args[0]->getType()->isIncompleteType()) {
12423           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12424             << Args[0]->getType()
12425             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12426         }
12427       } else {
12428         // This is an erroneous use of an operator which can be overloaded by
12429         // a non-member function. Check for non-member operators which were
12430         // defined too late to be candidates.
12431         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12432           // FIXME: Recover by calling the found function.
12433           return ExprError();
12434 
12435         // No viable function; try to create a built-in operation, which will
12436         // produce an error. Then, show the non-viable candidates.
12437         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12438       }
12439       assert(Result.isInvalid() &&
12440              "C++ binary operator overloading is missing candidates!");
12441       if (Result.isInvalid())
12442         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12443                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12444       return Result;
12445     }
12446 
12447     case OR_Ambiguous:
12448       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12449           << BinaryOperator::getOpcodeStr(Opc)
12450           << Args[0]->getType() << Args[1]->getType()
12451           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12452       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12453                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12454       return ExprError();
12455 
12456     case OR_Deleted:
12457       if (isImplicitlyDeleted(Best->Function)) {
12458         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12459         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12460           << Context.getRecordType(Method->getParent())
12461           << getSpecialMember(Method);
12462 
12463         // The user probably meant to call this special member. Just
12464         // explain why it's deleted.
12465         NoteDeletedFunction(Method);
12466         return ExprError();
12467       } else {
12468         Diag(OpLoc, diag::err_ovl_deleted_oper)
12469           << Best->Function->isDeleted()
12470           << BinaryOperator::getOpcodeStr(Opc)
12471           << getDeletedOrUnavailableSuffix(Best->Function)
12472           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12473       }
12474       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12475                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12476       return ExprError();
12477   }
12478 
12479   // We matched a built-in operator; build it.
12480   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12481 }
12482 
12483 ExprResult
12484 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12485                                          SourceLocation RLoc,
12486                                          Expr *Base, Expr *Idx) {
12487   Expr *Args[2] = { Base, Idx };
12488   DeclarationName OpName =
12489       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12490 
12491   // If either side is type-dependent, create an appropriate dependent
12492   // expression.
12493   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12494 
12495     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12496     // CHECKME: no 'operator' keyword?
12497     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12498     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12499     UnresolvedLookupExpr *Fn
12500       = UnresolvedLookupExpr::Create(Context, NamingClass,
12501                                      NestedNameSpecifierLoc(), OpNameInfo,
12502                                      /*ADL*/ true, /*Overloaded*/ false,
12503                                      UnresolvedSetIterator(),
12504                                      UnresolvedSetIterator());
12505     // Can't add any actual overloads yet
12506 
12507     return new (Context)
12508         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12509                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12510   }
12511 
12512   // Handle placeholders on both operands.
12513   if (checkPlaceholderForOverload(*this, Args[0]))
12514     return ExprError();
12515   if (checkPlaceholderForOverload(*this, Args[1]))
12516     return ExprError();
12517 
12518   // Build an empty overload set.
12519   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12520 
12521   // Subscript can only be overloaded as a member function.
12522 
12523   // Add operator candidates that are member functions.
12524   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12525 
12526   // Add builtin operator candidates.
12527   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12528 
12529   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12530 
12531   // Perform overload resolution.
12532   OverloadCandidateSet::iterator Best;
12533   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12534     case OR_Success: {
12535       // We found a built-in operator or an overloaded operator.
12536       FunctionDecl *FnDecl = Best->Function;
12537 
12538       if (FnDecl) {
12539         // We matched an overloaded operator. Build a call to that
12540         // operator.
12541 
12542         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12543 
12544         // Convert the arguments.
12545         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12546         ExprResult Arg0 =
12547           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12548                                               Best->FoundDecl, Method);
12549         if (Arg0.isInvalid())
12550           return ExprError();
12551         Args[0] = Arg0.get();
12552 
12553         // Convert the arguments.
12554         ExprResult InputInit
12555           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12556                                                       Context,
12557                                                       FnDecl->getParamDecl(0)),
12558                                       SourceLocation(),
12559                                       Args[1]);
12560         if (InputInit.isInvalid())
12561           return ExprError();
12562 
12563         Args[1] = InputInit.getAs<Expr>();
12564 
12565         // Build the actual expression node.
12566         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12567         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12568         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12569                                                   Best->FoundDecl,
12570                                                   Base,
12571                                                   HadMultipleCandidates,
12572                                                   OpLocInfo.getLoc(),
12573                                                   OpLocInfo.getInfo());
12574         if (FnExpr.isInvalid())
12575           return ExprError();
12576 
12577         // Determine the result type
12578         QualType ResultTy = FnDecl->getReturnType();
12579         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12580         ResultTy = ResultTy.getNonLValueExprType(Context);
12581 
12582         CXXOperatorCallExpr *TheCall =
12583           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12584                                             FnExpr.get(), Args,
12585                                             ResultTy, VK, RLoc,
12586                                             FPOptions());
12587 
12588         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12589           return ExprError();
12590 
12591         if (CheckFunctionCall(Method, TheCall,
12592                               Method->getType()->castAs<FunctionProtoType>()))
12593           return ExprError();
12594 
12595         return MaybeBindToTemporary(TheCall);
12596       } else {
12597         // We matched a built-in operator. Convert the arguments, then
12598         // break out so that we will build the appropriate built-in
12599         // operator node.
12600         ExprResult ArgsRes0 =
12601             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12602                                       Best->Conversions[0], AA_Passing);
12603         if (ArgsRes0.isInvalid())
12604           return ExprError();
12605         Args[0] = ArgsRes0.get();
12606 
12607         ExprResult ArgsRes1 =
12608             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12609                                       Best->Conversions[1], AA_Passing);
12610         if (ArgsRes1.isInvalid())
12611           return ExprError();
12612         Args[1] = ArgsRes1.get();
12613 
12614         break;
12615       }
12616     }
12617 
12618     case OR_No_Viable_Function: {
12619       if (CandidateSet.empty())
12620         Diag(LLoc, diag::err_ovl_no_oper)
12621           << Args[0]->getType() << /*subscript*/ 0
12622           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12623       else
12624         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12625           << Args[0]->getType()
12626           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12627       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12628                                   "[]", LLoc);
12629       return ExprError();
12630     }
12631 
12632     case OR_Ambiguous:
12633       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12634           << "[]"
12635           << Args[0]->getType() << Args[1]->getType()
12636           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12637       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12638                                   "[]", LLoc);
12639       return ExprError();
12640 
12641     case OR_Deleted:
12642       Diag(LLoc, diag::err_ovl_deleted_oper)
12643         << Best->Function->isDeleted() << "[]"
12644         << getDeletedOrUnavailableSuffix(Best->Function)
12645         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12646       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12647                                   "[]", LLoc);
12648       return ExprError();
12649     }
12650 
12651   // We matched a built-in operator; build it.
12652   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12653 }
12654 
12655 /// BuildCallToMemberFunction - Build a call to a member
12656 /// function. MemExpr is the expression that refers to the member
12657 /// function (and includes the object parameter), Args/NumArgs are the
12658 /// arguments to the function call (not including the object
12659 /// parameter). The caller needs to validate that the member
12660 /// expression refers to a non-static member function or an overloaded
12661 /// member function.
12662 ExprResult
12663 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12664                                 SourceLocation LParenLoc,
12665                                 MultiExprArg Args,
12666                                 SourceLocation RParenLoc) {
12667   assert(MemExprE->getType() == Context.BoundMemberTy ||
12668          MemExprE->getType() == Context.OverloadTy);
12669 
12670   // Dig out the member expression. This holds both the object
12671   // argument and the member function we're referring to.
12672   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12673 
12674   // Determine whether this is a call to a pointer-to-member function.
12675   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12676     assert(op->getType() == Context.BoundMemberTy);
12677     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12678 
12679     QualType fnType =
12680       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12681 
12682     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12683     QualType resultType = proto->getCallResultType(Context);
12684     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12685 
12686     // Check that the object type isn't more qualified than the
12687     // member function we're calling.
12688     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12689 
12690     QualType objectType = op->getLHS()->getType();
12691     if (op->getOpcode() == BO_PtrMemI)
12692       objectType = objectType->castAs<PointerType>()->getPointeeType();
12693     Qualifiers objectQuals = objectType.getQualifiers();
12694 
12695     Qualifiers difference = objectQuals - funcQuals;
12696     difference.removeObjCGCAttr();
12697     difference.removeAddressSpace();
12698     if (difference) {
12699       std::string qualsString = difference.getAsString();
12700       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12701         << fnType.getUnqualifiedType()
12702         << qualsString
12703         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12704     }
12705 
12706     CXXMemberCallExpr *call
12707       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12708                                         resultType, valueKind, RParenLoc);
12709 
12710     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12711                             call, nullptr))
12712       return ExprError();
12713 
12714     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12715       return ExprError();
12716 
12717     if (CheckOtherCall(call, proto))
12718       return ExprError();
12719 
12720     return MaybeBindToTemporary(call);
12721   }
12722 
12723   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12724     return new (Context)
12725         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12726 
12727   UnbridgedCastsSet UnbridgedCasts;
12728   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12729     return ExprError();
12730 
12731   MemberExpr *MemExpr;
12732   CXXMethodDecl *Method = nullptr;
12733   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12734   NestedNameSpecifier *Qualifier = nullptr;
12735   if (isa<MemberExpr>(NakedMemExpr)) {
12736     MemExpr = cast<MemberExpr>(NakedMemExpr);
12737     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12738     FoundDecl = MemExpr->getFoundDecl();
12739     Qualifier = MemExpr->getQualifier();
12740     UnbridgedCasts.restore();
12741   } else {
12742     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12743     Qualifier = UnresExpr->getQualifier();
12744 
12745     QualType ObjectType = UnresExpr->getBaseType();
12746     Expr::Classification ObjectClassification
12747       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12748                             : UnresExpr->getBase()->Classify(Context);
12749 
12750     // Add overload candidates
12751     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12752                                       OverloadCandidateSet::CSK_Normal);
12753 
12754     // FIXME: avoid copy.
12755     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12756     if (UnresExpr->hasExplicitTemplateArgs()) {
12757       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12758       TemplateArgs = &TemplateArgsBuffer;
12759     }
12760 
12761     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12762            E = UnresExpr->decls_end(); I != E; ++I) {
12763 
12764       NamedDecl *Func = *I;
12765       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12766       if (isa<UsingShadowDecl>(Func))
12767         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12768 
12769 
12770       // Microsoft supports direct constructor calls.
12771       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12772         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12773                              Args, CandidateSet);
12774       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12775         // If explicit template arguments were provided, we can't call a
12776         // non-template member function.
12777         if (TemplateArgs)
12778           continue;
12779 
12780         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12781                            ObjectClassification, Args, CandidateSet,
12782                            /*SuppressUserConversions=*/false);
12783       } else {
12784         AddMethodTemplateCandidate(
12785             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12786             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12787             /*SuppressUsedConversions=*/false);
12788       }
12789     }
12790 
12791     DeclarationName DeclName = UnresExpr->getMemberName();
12792 
12793     UnbridgedCasts.restore();
12794 
12795     OverloadCandidateSet::iterator Best;
12796     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12797                                             Best)) {
12798     case OR_Success:
12799       Method = cast<CXXMethodDecl>(Best->Function);
12800       FoundDecl = Best->FoundDecl;
12801       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12802       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12803         return ExprError();
12804       // If FoundDecl is different from Method (such as if one is a template
12805       // and the other a specialization), make sure DiagnoseUseOfDecl is
12806       // called on both.
12807       // FIXME: This would be more comprehensively addressed by modifying
12808       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12809       // being used.
12810       if (Method != FoundDecl.getDecl() &&
12811                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12812         return ExprError();
12813       break;
12814 
12815     case OR_No_Viable_Function:
12816       Diag(UnresExpr->getMemberLoc(),
12817            diag::err_ovl_no_viable_member_function_in_call)
12818         << DeclName << MemExprE->getSourceRange();
12819       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12820       // FIXME: Leaking incoming expressions!
12821       return ExprError();
12822 
12823     case OR_Ambiguous:
12824       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12825         << DeclName << MemExprE->getSourceRange();
12826       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12827       // FIXME: Leaking incoming expressions!
12828       return ExprError();
12829 
12830     case OR_Deleted:
12831       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12832         << Best->Function->isDeleted()
12833         << DeclName
12834         << getDeletedOrUnavailableSuffix(Best->Function)
12835         << MemExprE->getSourceRange();
12836       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12837       // FIXME: Leaking incoming expressions!
12838       return ExprError();
12839     }
12840 
12841     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12842 
12843     // If overload resolution picked a static member, build a
12844     // non-member call based on that function.
12845     if (Method->isStatic()) {
12846       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12847                                    RParenLoc);
12848     }
12849 
12850     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12851   }
12852 
12853   QualType ResultType = Method->getReturnType();
12854   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12855   ResultType = ResultType.getNonLValueExprType(Context);
12856 
12857   assert(Method && "Member call to something that isn't a method?");
12858   CXXMemberCallExpr *TheCall =
12859     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12860                                     ResultType, VK, RParenLoc);
12861 
12862   // Check for a valid return type.
12863   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12864                           TheCall, Method))
12865     return ExprError();
12866 
12867   // Convert the object argument (for a non-static member function call).
12868   // We only need to do this if there was actually an overload; otherwise
12869   // it was done at lookup.
12870   if (!Method->isStatic()) {
12871     ExprResult ObjectArg =
12872       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12873                                           FoundDecl, Method);
12874     if (ObjectArg.isInvalid())
12875       return ExprError();
12876     MemExpr->setBase(ObjectArg.get());
12877   }
12878 
12879   // Convert the rest of the arguments
12880   const FunctionProtoType *Proto =
12881     Method->getType()->getAs<FunctionProtoType>();
12882   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12883                               RParenLoc))
12884     return ExprError();
12885 
12886   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12887 
12888   if (CheckFunctionCall(Method, TheCall, Proto))
12889     return ExprError();
12890 
12891   // In the case the method to call was not selected by the overloading
12892   // resolution process, we still need to handle the enable_if attribute. Do
12893   // that here, so it will not hide previous -- and more relevant -- errors.
12894   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12895     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12896       Diag(MemE->getMemberLoc(),
12897            diag::err_ovl_no_viable_member_function_in_call)
12898           << Method << Method->getSourceRange();
12899       Diag(Method->getLocation(),
12900            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12901           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12902       return ExprError();
12903     }
12904   }
12905 
12906   if ((isa<CXXConstructorDecl>(CurContext) ||
12907        isa<CXXDestructorDecl>(CurContext)) &&
12908       TheCall->getMethodDecl()->isPure()) {
12909     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12910 
12911     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12912         MemExpr->performsVirtualDispatch(getLangOpts())) {
12913       Diag(MemExpr->getLocStart(),
12914            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12915         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12916         << MD->getParent()->getDeclName();
12917 
12918       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12919       if (getLangOpts().AppleKext)
12920         Diag(MemExpr->getLocStart(),
12921              diag::note_pure_qualified_call_kext)
12922              << MD->getParent()->getDeclName()
12923              << MD->getDeclName();
12924     }
12925   }
12926 
12927   if (CXXDestructorDecl *DD =
12928           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12929     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12930     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12931     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12932                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12933                          MemExpr->getMemberLoc());
12934   }
12935 
12936   return MaybeBindToTemporary(TheCall);
12937 }
12938 
12939 /// BuildCallToObjectOfClassType - Build a call to an object of class
12940 /// type (C++ [over.call.object]), which can end up invoking an
12941 /// overloaded function call operator (@c operator()) or performing a
12942 /// user-defined conversion on the object argument.
12943 ExprResult
12944 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12945                                    SourceLocation LParenLoc,
12946                                    MultiExprArg Args,
12947                                    SourceLocation RParenLoc) {
12948   if (checkPlaceholderForOverload(*this, Obj))
12949     return ExprError();
12950   ExprResult Object = Obj;
12951 
12952   UnbridgedCastsSet UnbridgedCasts;
12953   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12954     return ExprError();
12955 
12956   assert(Object.get()->getType()->isRecordType() &&
12957          "Requires object type argument");
12958   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12959 
12960   // C++ [over.call.object]p1:
12961   //  If the primary-expression E in the function call syntax
12962   //  evaluates to a class object of type "cv T", then the set of
12963   //  candidate functions includes at least the function call
12964   //  operators of T. The function call operators of T are obtained by
12965   //  ordinary lookup of the name operator() in the context of
12966   //  (E).operator().
12967   OverloadCandidateSet CandidateSet(LParenLoc,
12968                                     OverloadCandidateSet::CSK_Operator);
12969   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12970 
12971   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12972                           diag::err_incomplete_object_call, Object.get()))
12973     return true;
12974 
12975   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12976   LookupQualifiedName(R, Record->getDecl());
12977   R.suppressDiagnostics();
12978 
12979   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12980        Oper != OperEnd; ++Oper) {
12981     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12982                        Object.get()->Classify(Context), Args, CandidateSet,
12983                        /*SuppressUserConversions=*/false);
12984   }
12985 
12986   // C++ [over.call.object]p2:
12987   //   In addition, for each (non-explicit in C++0x) conversion function
12988   //   declared in T of the form
12989   //
12990   //        operator conversion-type-id () cv-qualifier;
12991   //
12992   //   where cv-qualifier is the same cv-qualification as, or a
12993   //   greater cv-qualification than, cv, and where conversion-type-id
12994   //   denotes the type "pointer to function of (P1,...,Pn) returning
12995   //   R", or the type "reference to pointer to function of
12996   //   (P1,...,Pn) returning R", or the type "reference to function
12997   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12998   //   is also considered as a candidate function. Similarly,
12999   //   surrogate call functions are added to the set of candidate
13000   //   functions for each conversion function declared in an
13001   //   accessible base class provided the function is not hidden
13002   //   within T by another intervening declaration.
13003   const auto &Conversions =
13004       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13005   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13006     NamedDecl *D = *I;
13007     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13008     if (isa<UsingShadowDecl>(D))
13009       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13010 
13011     // Skip over templated conversion functions; they aren't
13012     // surrogates.
13013     if (isa<FunctionTemplateDecl>(D))
13014       continue;
13015 
13016     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13017     if (!Conv->isExplicit()) {
13018       // Strip the reference type (if any) and then the pointer type (if
13019       // any) to get down to what might be a function type.
13020       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13021       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13022         ConvType = ConvPtrType->getPointeeType();
13023 
13024       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13025       {
13026         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13027                               Object.get(), Args, CandidateSet);
13028       }
13029     }
13030   }
13031 
13032   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13033 
13034   // Perform overload resolution.
13035   OverloadCandidateSet::iterator Best;
13036   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13037                                           Best)) {
13038   case OR_Success:
13039     // Overload resolution succeeded; we'll build the appropriate call
13040     // below.
13041     break;
13042 
13043   case OR_No_Viable_Function:
13044     if (CandidateSet.empty())
13045       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13046         << Object.get()->getType() << /*call*/ 1
13047         << Object.get()->getSourceRange();
13048     else
13049       Diag(Object.get()->getLocStart(),
13050            diag::err_ovl_no_viable_object_call)
13051         << Object.get()->getType() << Object.get()->getSourceRange();
13052     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13053     break;
13054 
13055   case OR_Ambiguous:
13056     Diag(Object.get()->getLocStart(),
13057          diag::err_ovl_ambiguous_object_call)
13058       << Object.get()->getType() << Object.get()->getSourceRange();
13059     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13060     break;
13061 
13062   case OR_Deleted:
13063     Diag(Object.get()->getLocStart(),
13064          diag::err_ovl_deleted_object_call)
13065       << Best->Function->isDeleted()
13066       << Object.get()->getType()
13067       << getDeletedOrUnavailableSuffix(Best->Function)
13068       << Object.get()->getSourceRange();
13069     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13070     break;
13071   }
13072 
13073   if (Best == CandidateSet.end())
13074     return true;
13075 
13076   UnbridgedCasts.restore();
13077 
13078   if (Best->Function == nullptr) {
13079     // Since there is no function declaration, this is one of the
13080     // surrogate candidates. Dig out the conversion function.
13081     CXXConversionDecl *Conv
13082       = cast<CXXConversionDecl>(
13083                          Best->Conversions[0].UserDefined.ConversionFunction);
13084 
13085     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13086                               Best->FoundDecl);
13087     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13088       return ExprError();
13089     assert(Conv == Best->FoundDecl.getDecl() &&
13090              "Found Decl & conversion-to-functionptr should be same, right?!");
13091     // We selected one of the surrogate functions that converts the
13092     // object parameter to a function pointer. Perform the conversion
13093     // on the object argument, then let ActOnCallExpr finish the job.
13094 
13095     // Create an implicit member expr to refer to the conversion operator.
13096     // and then call it.
13097     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13098                                              Conv, HadMultipleCandidates);
13099     if (Call.isInvalid())
13100       return ExprError();
13101     // Record usage of conversion in an implicit cast.
13102     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13103                                     CK_UserDefinedConversion, Call.get(),
13104                                     nullptr, VK_RValue);
13105 
13106     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13107   }
13108 
13109   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13110 
13111   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13112   // that calls this method, using Object for the implicit object
13113   // parameter and passing along the remaining arguments.
13114   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13115 
13116   // An error diagnostic has already been printed when parsing the declaration.
13117   if (Method->isInvalidDecl())
13118     return ExprError();
13119 
13120   const FunctionProtoType *Proto =
13121     Method->getType()->getAs<FunctionProtoType>();
13122 
13123   unsigned NumParams = Proto->getNumParams();
13124 
13125   DeclarationNameInfo OpLocInfo(
13126                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13127   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13128   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13129                                            Obj, HadMultipleCandidates,
13130                                            OpLocInfo.getLoc(),
13131                                            OpLocInfo.getInfo());
13132   if (NewFn.isInvalid())
13133     return true;
13134 
13135   // Build the full argument list for the method call (the implicit object
13136   // parameter is placed at the beginning of the list).
13137   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13138   MethodArgs[0] = Object.get();
13139   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13140 
13141   // Once we've built TheCall, all of the expressions are properly
13142   // owned.
13143   QualType ResultTy = Method->getReturnType();
13144   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13145   ResultTy = ResultTy.getNonLValueExprType(Context);
13146 
13147   CXXOperatorCallExpr *TheCall = new (Context)
13148       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13149                           VK, RParenLoc, FPOptions());
13150 
13151   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13152     return true;
13153 
13154   // We may have default arguments. If so, we need to allocate more
13155   // slots in the call for them.
13156   if (Args.size() < NumParams)
13157     TheCall->setNumArgs(Context, NumParams + 1);
13158 
13159   bool IsError = false;
13160 
13161   // Initialize the implicit object parameter.
13162   ExprResult ObjRes =
13163     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13164                                         Best->FoundDecl, Method);
13165   if (ObjRes.isInvalid())
13166     IsError = true;
13167   else
13168     Object = ObjRes;
13169   TheCall->setArg(0, Object.get());
13170 
13171   // Check the argument types.
13172   for (unsigned i = 0; i != NumParams; i++) {
13173     Expr *Arg;
13174     if (i < Args.size()) {
13175       Arg = Args[i];
13176 
13177       // Pass the argument.
13178 
13179       ExprResult InputInit
13180         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13181                                                     Context,
13182                                                     Method->getParamDecl(i)),
13183                                     SourceLocation(), Arg);
13184 
13185       IsError |= InputInit.isInvalid();
13186       Arg = InputInit.getAs<Expr>();
13187     } else {
13188       ExprResult DefArg
13189         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13190       if (DefArg.isInvalid()) {
13191         IsError = true;
13192         break;
13193       }
13194 
13195       Arg = DefArg.getAs<Expr>();
13196     }
13197 
13198     TheCall->setArg(i + 1, Arg);
13199   }
13200 
13201   // If this is a variadic call, handle args passed through "...".
13202   if (Proto->isVariadic()) {
13203     // Promote the arguments (C99 6.5.2.2p7).
13204     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13205       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13206                                                         nullptr);
13207       IsError |= Arg.isInvalid();
13208       TheCall->setArg(i + 1, Arg.get());
13209     }
13210   }
13211 
13212   if (IsError) return true;
13213 
13214   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13215 
13216   if (CheckFunctionCall(Method, TheCall, Proto))
13217     return true;
13218 
13219   return MaybeBindToTemporary(TheCall);
13220 }
13221 
13222 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13223 ///  (if one exists), where @c Base is an expression of class type and
13224 /// @c Member is the name of the member we're trying to find.
13225 ExprResult
13226 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13227                                bool *NoArrowOperatorFound) {
13228   assert(Base->getType()->isRecordType() &&
13229          "left-hand side must have class type");
13230 
13231   if (checkPlaceholderForOverload(*this, Base))
13232     return ExprError();
13233 
13234   SourceLocation Loc = Base->getExprLoc();
13235 
13236   // C++ [over.ref]p1:
13237   //
13238   //   [...] An expression x->m is interpreted as (x.operator->())->m
13239   //   for a class object x of type T if T::operator->() exists and if
13240   //   the operator is selected as the best match function by the
13241   //   overload resolution mechanism (13.3).
13242   DeclarationName OpName =
13243     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13244   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13245   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13246 
13247   if (RequireCompleteType(Loc, Base->getType(),
13248                           diag::err_typecheck_incomplete_tag, Base))
13249     return ExprError();
13250 
13251   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13252   LookupQualifiedName(R, BaseRecord->getDecl());
13253   R.suppressDiagnostics();
13254 
13255   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13256        Oper != OperEnd; ++Oper) {
13257     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13258                        None, CandidateSet, /*SuppressUserConversions=*/false);
13259   }
13260 
13261   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13262 
13263   // Perform overload resolution.
13264   OverloadCandidateSet::iterator Best;
13265   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13266   case OR_Success:
13267     // Overload resolution succeeded; we'll build the call below.
13268     break;
13269 
13270   case OR_No_Viable_Function:
13271     if (CandidateSet.empty()) {
13272       QualType BaseType = Base->getType();
13273       if (NoArrowOperatorFound) {
13274         // Report this specific error to the caller instead of emitting a
13275         // diagnostic, as requested.
13276         *NoArrowOperatorFound = true;
13277         return ExprError();
13278       }
13279       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13280         << BaseType << Base->getSourceRange();
13281       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13282         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13283           << FixItHint::CreateReplacement(OpLoc, ".");
13284       }
13285     } else
13286       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13287         << "operator->" << Base->getSourceRange();
13288     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13289     return ExprError();
13290 
13291   case OR_Ambiguous:
13292     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13293       << "->" << Base->getType() << Base->getSourceRange();
13294     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13295     return ExprError();
13296 
13297   case OR_Deleted:
13298     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13299       << Best->Function->isDeleted()
13300       << "->"
13301       << getDeletedOrUnavailableSuffix(Best->Function)
13302       << Base->getSourceRange();
13303     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13304     return ExprError();
13305   }
13306 
13307   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13308 
13309   // Convert the object parameter.
13310   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13311   ExprResult BaseResult =
13312     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13313                                         Best->FoundDecl, Method);
13314   if (BaseResult.isInvalid())
13315     return ExprError();
13316   Base = BaseResult.get();
13317 
13318   // Build the operator call.
13319   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13320                                             Base, HadMultipleCandidates, OpLoc);
13321   if (FnExpr.isInvalid())
13322     return ExprError();
13323 
13324   QualType ResultTy = Method->getReturnType();
13325   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13326   ResultTy = ResultTy.getNonLValueExprType(Context);
13327   CXXOperatorCallExpr *TheCall =
13328     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13329                                       Base, ResultTy, VK, OpLoc, FPOptions());
13330 
13331   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13332     return ExprError();
13333 
13334   if (CheckFunctionCall(Method, TheCall,
13335                         Method->getType()->castAs<FunctionProtoType>()))
13336     return ExprError();
13337 
13338   return MaybeBindToTemporary(TheCall);
13339 }
13340 
13341 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13342 /// a literal operator described by the provided lookup results.
13343 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13344                                           DeclarationNameInfo &SuffixInfo,
13345                                           ArrayRef<Expr*> Args,
13346                                           SourceLocation LitEndLoc,
13347                                        TemplateArgumentListInfo *TemplateArgs) {
13348   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13349 
13350   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13351                                     OverloadCandidateSet::CSK_Normal);
13352   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13353                         /*SuppressUserConversions=*/true);
13354 
13355   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13356 
13357   // Perform overload resolution. This will usually be trivial, but might need
13358   // to perform substitutions for a literal operator template.
13359   OverloadCandidateSet::iterator Best;
13360   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13361   case OR_Success:
13362   case OR_Deleted:
13363     break;
13364 
13365   case OR_No_Viable_Function:
13366     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13367       << R.getLookupName();
13368     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13369     return ExprError();
13370 
13371   case OR_Ambiguous:
13372     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13373     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13374     return ExprError();
13375   }
13376 
13377   FunctionDecl *FD = Best->Function;
13378   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13379                                         nullptr, HadMultipleCandidates,
13380                                         SuffixInfo.getLoc(),
13381                                         SuffixInfo.getInfo());
13382   if (Fn.isInvalid())
13383     return true;
13384 
13385   // Check the argument types. This should almost always be a no-op, except
13386   // that array-to-pointer decay is applied to string literals.
13387   Expr *ConvArgs[2];
13388   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13389     ExprResult InputInit = PerformCopyInitialization(
13390       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13391       SourceLocation(), Args[ArgIdx]);
13392     if (InputInit.isInvalid())
13393       return true;
13394     ConvArgs[ArgIdx] = InputInit.get();
13395   }
13396 
13397   QualType ResultTy = FD->getReturnType();
13398   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13399   ResultTy = ResultTy.getNonLValueExprType(Context);
13400 
13401   UserDefinedLiteral *UDL =
13402     new (Context) UserDefinedLiteral(Context, Fn.get(),
13403                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13404                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13405 
13406   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13407     return ExprError();
13408 
13409   if (CheckFunctionCall(FD, UDL, nullptr))
13410     return ExprError();
13411 
13412   return MaybeBindToTemporary(UDL);
13413 }
13414 
13415 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13416 /// given LookupResult is non-empty, it is assumed to describe a member which
13417 /// will be invoked. Otherwise, the function will be found via argument
13418 /// dependent lookup.
13419 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13420 /// otherwise CallExpr is set to ExprError() and some non-success value
13421 /// is returned.
13422 Sema::ForRangeStatus
13423 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13424                                 SourceLocation RangeLoc,
13425                                 const DeclarationNameInfo &NameInfo,
13426                                 LookupResult &MemberLookup,
13427                                 OverloadCandidateSet *CandidateSet,
13428                                 Expr *Range, ExprResult *CallExpr) {
13429   Scope *S = nullptr;
13430 
13431   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13432   if (!MemberLookup.empty()) {
13433     ExprResult MemberRef =
13434         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13435                                  /*IsPtr=*/false, CXXScopeSpec(),
13436                                  /*TemplateKWLoc=*/SourceLocation(),
13437                                  /*FirstQualifierInScope=*/nullptr,
13438                                  MemberLookup,
13439                                  /*TemplateArgs=*/nullptr, S);
13440     if (MemberRef.isInvalid()) {
13441       *CallExpr = ExprError();
13442       return FRS_DiagnosticIssued;
13443     }
13444     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13445     if (CallExpr->isInvalid()) {
13446       *CallExpr = ExprError();
13447       return FRS_DiagnosticIssued;
13448     }
13449   } else {
13450     UnresolvedSet<0> FoundNames;
13451     UnresolvedLookupExpr *Fn =
13452       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13453                                    NestedNameSpecifierLoc(), NameInfo,
13454                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13455                                    FoundNames.begin(), FoundNames.end());
13456 
13457     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13458                                                     CandidateSet, CallExpr);
13459     if (CandidateSet->empty() || CandidateSetError) {
13460       *CallExpr = ExprError();
13461       return FRS_NoViableFunction;
13462     }
13463     OverloadCandidateSet::iterator Best;
13464     OverloadingResult OverloadResult =
13465         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13466 
13467     if (OverloadResult == OR_No_Viable_Function) {
13468       *CallExpr = ExprError();
13469       return FRS_NoViableFunction;
13470     }
13471     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13472                                          Loc, nullptr, CandidateSet, &Best,
13473                                          OverloadResult,
13474                                          /*AllowTypoCorrection=*/false);
13475     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13476       *CallExpr = ExprError();
13477       return FRS_DiagnosticIssued;
13478     }
13479   }
13480   return FRS_Success;
13481 }
13482 
13483 
13484 /// FixOverloadedFunctionReference - E is an expression that refers to
13485 /// a C++ overloaded function (possibly with some parentheses and
13486 /// perhaps a '&' around it). We have resolved the overloaded function
13487 /// to the function declaration Fn, so patch up the expression E to
13488 /// refer (possibly indirectly) to Fn. Returns the new expr.
13489 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13490                                            FunctionDecl *Fn) {
13491   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13492     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13493                                                    Found, Fn);
13494     if (SubExpr == PE->getSubExpr())
13495       return PE;
13496 
13497     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13498   }
13499 
13500   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13501     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13502                                                    Found, Fn);
13503     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13504                                SubExpr->getType()) &&
13505            "Implicit cast type cannot be determined from overload");
13506     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13507     if (SubExpr == ICE->getSubExpr())
13508       return ICE;
13509 
13510     return ImplicitCastExpr::Create(Context, ICE->getType(),
13511                                     ICE->getCastKind(),
13512                                     SubExpr, nullptr,
13513                                     ICE->getValueKind());
13514   }
13515 
13516   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13517     if (!GSE->isResultDependent()) {
13518       Expr *SubExpr =
13519           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13520       if (SubExpr == GSE->getResultExpr())
13521         return GSE;
13522 
13523       // Replace the resulting type information before rebuilding the generic
13524       // selection expression.
13525       ArrayRef<Expr *> A = GSE->getAssocExprs();
13526       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13527       unsigned ResultIdx = GSE->getResultIndex();
13528       AssocExprs[ResultIdx] = SubExpr;
13529 
13530       return new (Context) GenericSelectionExpr(
13531           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13532           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13533           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13534           ResultIdx);
13535     }
13536     // Rather than fall through to the unreachable, return the original generic
13537     // selection expression.
13538     return GSE;
13539   }
13540 
13541   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13542     assert(UnOp->getOpcode() == UO_AddrOf &&
13543            "Can only take the address of an overloaded function");
13544     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13545       if (Method->isStatic()) {
13546         // Do nothing: static member functions aren't any different
13547         // from non-member functions.
13548       } else {
13549         // Fix the subexpression, which really has to be an
13550         // UnresolvedLookupExpr holding an overloaded member function
13551         // or template.
13552         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13553                                                        Found, Fn);
13554         if (SubExpr == UnOp->getSubExpr())
13555           return UnOp;
13556 
13557         assert(isa<DeclRefExpr>(SubExpr)
13558                && "fixed to something other than a decl ref");
13559         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13560                && "fixed to a member ref with no nested name qualifier");
13561 
13562         // We have taken the address of a pointer to member
13563         // function. Perform the computation here so that we get the
13564         // appropriate pointer to member type.
13565         QualType ClassType
13566           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13567         QualType MemPtrType
13568           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13569         // Under the MS ABI, lock down the inheritance model now.
13570         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13571           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13572 
13573         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13574                                            VK_RValue, OK_Ordinary,
13575                                            UnOp->getOperatorLoc(), false);
13576       }
13577     }
13578     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13579                                                    Found, Fn);
13580     if (SubExpr == UnOp->getSubExpr())
13581       return UnOp;
13582 
13583     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13584                                      Context.getPointerType(SubExpr->getType()),
13585                                        VK_RValue, OK_Ordinary,
13586                                        UnOp->getOperatorLoc(), false);
13587   }
13588 
13589   // C++ [except.spec]p17:
13590   //   An exception-specification is considered to be needed when:
13591   //   - in an expression the function is the unique lookup result or the
13592   //     selected member of a set of overloaded functions
13593   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13594     ResolveExceptionSpec(E->getExprLoc(), FPT);
13595 
13596   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13597     // FIXME: avoid copy.
13598     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13599     if (ULE->hasExplicitTemplateArgs()) {
13600       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13601       TemplateArgs = &TemplateArgsBuffer;
13602     }
13603 
13604     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13605                                            ULE->getQualifierLoc(),
13606                                            ULE->getTemplateKeywordLoc(),
13607                                            Fn,
13608                                            /*enclosing*/ false, // FIXME?
13609                                            ULE->getNameLoc(),
13610                                            Fn->getType(),
13611                                            VK_LValue,
13612                                            Found.getDecl(),
13613                                            TemplateArgs);
13614     MarkDeclRefReferenced(DRE);
13615     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13616     return DRE;
13617   }
13618 
13619   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13620     // FIXME: avoid copy.
13621     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13622     if (MemExpr->hasExplicitTemplateArgs()) {
13623       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13624       TemplateArgs = &TemplateArgsBuffer;
13625     }
13626 
13627     Expr *Base;
13628 
13629     // If we're filling in a static method where we used to have an
13630     // implicit member access, rewrite to a simple decl ref.
13631     if (MemExpr->isImplicitAccess()) {
13632       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13633         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13634                                                MemExpr->getQualifierLoc(),
13635                                                MemExpr->getTemplateKeywordLoc(),
13636                                                Fn,
13637                                                /*enclosing*/ false,
13638                                                MemExpr->getMemberLoc(),
13639                                                Fn->getType(),
13640                                                VK_LValue,
13641                                                Found.getDecl(),
13642                                                TemplateArgs);
13643         MarkDeclRefReferenced(DRE);
13644         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13645         return DRE;
13646       } else {
13647         SourceLocation Loc = MemExpr->getMemberLoc();
13648         if (MemExpr->getQualifier())
13649           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13650         CheckCXXThisCapture(Loc);
13651         Base = new (Context) CXXThisExpr(Loc,
13652                                          MemExpr->getBaseType(),
13653                                          /*isImplicit=*/true);
13654       }
13655     } else
13656       Base = MemExpr->getBase();
13657 
13658     ExprValueKind valueKind;
13659     QualType type;
13660     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13661       valueKind = VK_LValue;
13662       type = Fn->getType();
13663     } else {
13664       valueKind = VK_RValue;
13665       type = Context.BoundMemberTy;
13666     }
13667 
13668     MemberExpr *ME = MemberExpr::Create(
13669         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13670         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13671         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13672         OK_Ordinary);
13673     ME->setHadMultipleCandidates(true);
13674     MarkMemberReferenced(ME);
13675     return ME;
13676   }
13677 
13678   llvm_unreachable("Invalid reference to overloaded function");
13679 }
13680 
13681 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13682                                                 DeclAccessPair Found,
13683                                                 FunctionDecl *Fn) {
13684   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13685 }
13686