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     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1002       // We can overload with these, which can show up when doing
1003       // redeclaration checks for UsingDecls.
1004       assert(Old.getLookupKind() == LookupUsingDeclName);
1005     } else if (isa<TagDecl>(OldD)) {
1006       // We can always overload with tags by hiding them.
1007     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1008       // Optimistically assume that an unresolved using decl will
1009       // overload; if it doesn't, we'll have to diagnose during
1010       // template instantiation.
1011       //
1012       // Exception: if the scope is dependent and this is not a class
1013       // member, the using declaration can only introduce an enumerator.
1014       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1015         Match = *I;
1016         return Ovl_NonFunction;
1017       }
1018     } else {
1019       // (C++ 13p1):
1020       //   Only function declarations can be overloaded; object and type
1021       //   declarations cannot be overloaded.
1022       Match = *I;
1023       return Ovl_NonFunction;
1024     }
1025   }
1026 
1027   return Ovl_Overload;
1028 }
1029 
1030 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1031                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1032   // C++ [basic.start.main]p2: This function shall not be overloaded.
1033   if (New->isMain())
1034     return false;
1035 
1036   // MSVCRT user defined entry points cannot be overloaded.
1037   if (New->isMSVCRTEntryPoint())
1038     return false;
1039 
1040   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1041   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1042 
1043   // C++ [temp.fct]p2:
1044   //   A function template can be overloaded with other function templates
1045   //   and with normal (non-template) functions.
1046   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1047     return true;
1048 
1049   // Is the function New an overload of the function Old?
1050   QualType OldQType = Context.getCanonicalType(Old->getType());
1051   QualType NewQType = Context.getCanonicalType(New->getType());
1052 
1053   // Compare the signatures (C++ 1.3.10) of the two functions to
1054   // determine whether they are overloads. If we find any mismatch
1055   // in the signature, they are overloads.
1056 
1057   // If either of these functions is a K&R-style function (no
1058   // prototype), then we consider them to have matching signatures.
1059   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1060       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1061     return false;
1062 
1063   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1064   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1065 
1066   // The signature of a function includes the types of its
1067   // parameters (C++ 1.3.10), which includes the presence or absence
1068   // of the ellipsis; see C++ DR 357).
1069   if (OldQType != NewQType &&
1070       (OldType->getNumParams() != NewType->getNumParams() ||
1071        OldType->isVariadic() != NewType->isVariadic() ||
1072        !FunctionParamTypesAreEqual(OldType, NewType)))
1073     return true;
1074 
1075   // C++ [temp.over.link]p4:
1076   //   The signature of a function template consists of its function
1077   //   signature, its return type and its template parameter list. The names
1078   //   of the template parameters are significant only for establishing the
1079   //   relationship between the template parameters and the rest of the
1080   //   signature.
1081   //
1082   // We check the return type and template parameter lists for function
1083   // templates first; the remaining checks follow.
1084   //
1085   // However, we don't consider either of these when deciding whether
1086   // a member introduced by a shadow declaration is hidden.
1087   if (!UseMemberUsingDeclRules && NewTemplate &&
1088       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1089                                        OldTemplate->getTemplateParameters(),
1090                                        false, TPL_TemplateMatch) ||
1091        OldType->getReturnType() != NewType->getReturnType()))
1092     return true;
1093 
1094   // If the function is a class member, its signature includes the
1095   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1096   //
1097   // As part of this, also check whether one of the member functions
1098   // is static, in which case they are not overloads (C++
1099   // 13.1p2). While not part of the definition of the signature,
1100   // this check is important to determine whether these functions
1101   // can be overloaded.
1102   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1103   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1104   if (OldMethod && NewMethod &&
1105       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1106     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1107       if (!UseMemberUsingDeclRules &&
1108           (OldMethod->getRefQualifier() == RQ_None ||
1109            NewMethod->getRefQualifier() == RQ_None)) {
1110         // C++0x [over.load]p2:
1111         //   - Member function declarations with the same name and the same
1112         //     parameter-type-list as well as member function template
1113         //     declarations with the same name, the same parameter-type-list, and
1114         //     the same template parameter lists cannot be overloaded if any of
1115         //     them, but not all, have a ref-qualifier (8.3.5).
1116         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1117           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1118         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1119       }
1120       return true;
1121     }
1122 
1123     // We may not have applied the implicit const for a constexpr member
1124     // function yet (because we haven't yet resolved whether this is a static
1125     // or non-static member function). Add it now, on the assumption that this
1126     // is a redeclaration of OldMethod.
1127     unsigned OldQuals = OldMethod->getTypeQualifiers();
1128     unsigned NewQuals = NewMethod->getTypeQualifiers();
1129     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1130         !isa<CXXConstructorDecl>(NewMethod))
1131       NewQuals |= Qualifiers::Const;
1132 
1133     // We do not allow overloading based off of '__restrict'.
1134     OldQuals &= ~Qualifiers::Restrict;
1135     NewQuals &= ~Qualifiers::Restrict;
1136     if (OldQuals != NewQuals)
1137       return true;
1138   }
1139 
1140   // Though pass_object_size is placed on parameters and takes an argument, we
1141   // consider it to be a function-level modifier for the sake of function
1142   // identity. Either the function has one or more parameters with
1143   // pass_object_size or it doesn't.
1144   if (functionHasPassObjectSizeParams(New) !=
1145       functionHasPassObjectSizeParams(Old))
1146     return true;
1147 
1148   // enable_if attributes are an order-sensitive part of the signature.
1149   for (specific_attr_iterator<EnableIfAttr>
1150          NewI = New->specific_attr_begin<EnableIfAttr>(),
1151          NewE = New->specific_attr_end<EnableIfAttr>(),
1152          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1153          OldE = Old->specific_attr_end<EnableIfAttr>();
1154        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1155     if (NewI == NewE || OldI == OldE)
1156       return true;
1157     llvm::FoldingSetNodeID NewID, OldID;
1158     NewI->getCond()->Profile(NewID, Context, true);
1159     OldI->getCond()->Profile(OldID, Context, true);
1160     if (NewID != OldID)
1161       return true;
1162   }
1163 
1164   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1165     // Don't allow overloading of destructors.  (In theory we could, but it
1166     // would be a giant change to clang.)
1167     if (isa<CXXDestructorDecl>(New))
1168       return false;
1169 
1170     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1171                        OldTarget = IdentifyCUDATarget(Old);
1172     if (NewTarget == CFT_InvalidTarget)
1173       return false;
1174 
1175     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1176 
1177     // Allow overloading of functions with same signature and different CUDA
1178     // target attributes.
1179     return NewTarget != OldTarget;
1180   }
1181 
1182   // The signatures match; this is not an overload.
1183   return false;
1184 }
1185 
1186 /// \brief Checks availability of the function depending on the current
1187 /// function context. Inside an unavailable function, unavailability is ignored.
1188 ///
1189 /// \returns true if \arg FD is unavailable and current context is inside
1190 /// an available function, false otherwise.
1191 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1192   if (!FD->isUnavailable())
1193     return false;
1194 
1195   // Walk up the context of the caller.
1196   Decl *C = cast<Decl>(CurContext);
1197   do {
1198     if (C->isUnavailable())
1199       return false;
1200   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1201   return true;
1202 }
1203 
1204 /// \brief Tries a user-defined conversion from From to ToType.
1205 ///
1206 /// Produces an implicit conversion sequence for when a standard conversion
1207 /// is not an option. See TryImplicitConversion for more information.
1208 static ImplicitConversionSequence
1209 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1210                          bool SuppressUserConversions,
1211                          bool AllowExplicit,
1212                          bool InOverloadResolution,
1213                          bool CStyle,
1214                          bool AllowObjCWritebackConversion,
1215                          bool AllowObjCConversionOnExplicit) {
1216   ImplicitConversionSequence ICS;
1217 
1218   if (SuppressUserConversions) {
1219     // We're not in the case above, so there is no conversion that
1220     // we can perform.
1221     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1222     return ICS;
1223   }
1224 
1225   // Attempt user-defined conversion.
1226   OverloadCandidateSet Conversions(From->getExprLoc(),
1227                                    OverloadCandidateSet::CSK_Normal);
1228   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1229                                   Conversions, AllowExplicit,
1230                                   AllowObjCConversionOnExplicit)) {
1231   case OR_Success:
1232   case OR_Deleted:
1233     ICS.setUserDefined();
1234     // C++ [over.ics.user]p4:
1235     //   A conversion of an expression of class type to the same class
1236     //   type is given Exact Match rank, and a conversion of an
1237     //   expression of class type to a base class of that type is
1238     //   given Conversion rank, in spite of the fact that a copy
1239     //   constructor (i.e., a user-defined conversion function) is
1240     //   called for those cases.
1241     if (CXXConstructorDecl *Constructor
1242           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1243       QualType FromCanon
1244         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1245       QualType ToCanon
1246         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1247       if (Constructor->isCopyConstructor() &&
1248           (FromCanon == ToCanon ||
1249            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1250         // Turn this into a "standard" conversion sequence, so that it
1251         // gets ranked with standard conversion sequences.
1252         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1253         ICS.setStandard();
1254         ICS.Standard.setAsIdentityConversion();
1255         ICS.Standard.setFromType(From->getType());
1256         ICS.Standard.setAllToTypes(ToType);
1257         ICS.Standard.CopyConstructor = Constructor;
1258         ICS.Standard.FoundCopyConstructor = Found;
1259         if (ToCanon != FromCanon)
1260           ICS.Standard.Second = ICK_Derived_To_Base;
1261       }
1262     }
1263     break;
1264 
1265   case OR_Ambiguous:
1266     ICS.setAmbiguous();
1267     ICS.Ambiguous.setFromType(From->getType());
1268     ICS.Ambiguous.setToType(ToType);
1269     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1270          Cand != Conversions.end(); ++Cand)
1271       if (Cand->Viable)
1272         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1273     break;
1274 
1275     // Fall through.
1276   case OR_No_Viable_Function:
1277     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1278     break;
1279   }
1280 
1281   return ICS;
1282 }
1283 
1284 /// TryImplicitConversion - Attempt to perform an implicit conversion
1285 /// from the given expression (Expr) to the given type (ToType). This
1286 /// function returns an implicit conversion sequence that can be used
1287 /// to perform the initialization. Given
1288 ///
1289 ///   void f(float f);
1290 ///   void g(int i) { f(i); }
1291 ///
1292 /// this routine would produce an implicit conversion sequence to
1293 /// describe the initialization of f from i, which will be a standard
1294 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1295 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1296 //
1297 /// Note that this routine only determines how the conversion can be
1298 /// performed; it does not actually perform the conversion. As such,
1299 /// it will not produce any diagnostics if no conversion is available,
1300 /// but will instead return an implicit conversion sequence of kind
1301 /// "BadConversion".
1302 ///
1303 /// If @p SuppressUserConversions, then user-defined conversions are
1304 /// not permitted.
1305 /// If @p AllowExplicit, then explicit user-defined conversions are
1306 /// permitted.
1307 ///
1308 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1309 /// writeback conversion, which allows __autoreleasing id* parameters to
1310 /// be initialized with __strong id* or __weak id* arguments.
1311 static ImplicitConversionSequence
1312 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1313                       bool SuppressUserConversions,
1314                       bool AllowExplicit,
1315                       bool InOverloadResolution,
1316                       bool CStyle,
1317                       bool AllowObjCWritebackConversion,
1318                       bool AllowObjCConversionOnExplicit) {
1319   ImplicitConversionSequence ICS;
1320   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1321                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1322     ICS.setStandard();
1323     return ICS;
1324   }
1325 
1326   if (!S.getLangOpts().CPlusPlus) {
1327     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1328     return ICS;
1329   }
1330 
1331   // C++ [over.ics.user]p4:
1332   //   A conversion of an expression of class type to the same class
1333   //   type is given Exact Match rank, and a conversion of an
1334   //   expression of class type to a base class of that type is
1335   //   given Conversion rank, in spite of the fact that a copy/move
1336   //   constructor (i.e., a user-defined conversion function) is
1337   //   called for those cases.
1338   QualType FromType = From->getType();
1339   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1340       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1341        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1342     ICS.setStandard();
1343     ICS.Standard.setAsIdentityConversion();
1344     ICS.Standard.setFromType(FromType);
1345     ICS.Standard.setAllToTypes(ToType);
1346 
1347     // We don't actually check at this point whether there is a valid
1348     // copy/move constructor, since overloading just assumes that it
1349     // exists. When we actually perform initialization, we'll find the
1350     // appropriate constructor to copy the returned object, if needed.
1351     ICS.Standard.CopyConstructor = nullptr;
1352 
1353     // Determine whether this is considered a derived-to-base conversion.
1354     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1355       ICS.Standard.Second = ICK_Derived_To_Base;
1356 
1357     return ICS;
1358   }
1359 
1360   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1361                                   AllowExplicit, InOverloadResolution, CStyle,
1362                                   AllowObjCWritebackConversion,
1363                                   AllowObjCConversionOnExplicit);
1364 }
1365 
1366 ImplicitConversionSequence
1367 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1368                             bool SuppressUserConversions,
1369                             bool AllowExplicit,
1370                             bool InOverloadResolution,
1371                             bool CStyle,
1372                             bool AllowObjCWritebackConversion) {
1373   return ::TryImplicitConversion(*this, From, ToType,
1374                                  SuppressUserConversions, AllowExplicit,
1375                                  InOverloadResolution, CStyle,
1376                                  AllowObjCWritebackConversion,
1377                                  /*AllowObjCConversionOnExplicit=*/false);
1378 }
1379 
1380 /// PerformImplicitConversion - Perform an implicit conversion of the
1381 /// expression From to the type ToType. Returns the
1382 /// converted expression. Flavor is the kind of conversion we're
1383 /// performing, used in the error message. If @p AllowExplicit,
1384 /// explicit user-defined conversions are permitted.
1385 ExprResult
1386 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1387                                 AssignmentAction Action, bool AllowExplicit) {
1388   ImplicitConversionSequence ICS;
1389   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1390 }
1391 
1392 ExprResult
1393 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1394                                 AssignmentAction Action, bool AllowExplicit,
1395                                 ImplicitConversionSequence& ICS) {
1396   if (checkPlaceholderForOverload(*this, From))
1397     return ExprError();
1398 
1399   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1400   bool AllowObjCWritebackConversion
1401     = getLangOpts().ObjCAutoRefCount &&
1402       (Action == AA_Passing || Action == AA_Sending);
1403   if (getLangOpts().ObjC1)
1404     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1405                                       ToType, From->getType(), From);
1406   ICS = ::TryImplicitConversion(*this, From, ToType,
1407                                 /*SuppressUserConversions=*/false,
1408                                 AllowExplicit,
1409                                 /*InOverloadResolution=*/false,
1410                                 /*CStyle=*/false,
1411                                 AllowObjCWritebackConversion,
1412                                 /*AllowObjCConversionOnExplicit=*/false);
1413   return PerformImplicitConversion(From, ToType, ICS, Action);
1414 }
1415 
1416 /// \brief Determine whether the conversion from FromType to ToType is a valid
1417 /// conversion that strips "noexcept" or "noreturn" off the nested function
1418 /// type.
1419 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1420                                 QualType &ResultTy) {
1421   if (Context.hasSameUnqualifiedType(FromType, ToType))
1422     return false;
1423 
1424   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1425   //                    or F(t noexcept) -> F(t)
1426   // where F adds one of the following at most once:
1427   //   - a pointer
1428   //   - a member pointer
1429   //   - a block pointer
1430   // Changes here need matching changes in FindCompositePointerType.
1431   CanQualType CanTo = Context.getCanonicalType(ToType);
1432   CanQualType CanFrom = Context.getCanonicalType(FromType);
1433   Type::TypeClass TyClass = CanTo->getTypeClass();
1434   if (TyClass != CanFrom->getTypeClass()) return false;
1435   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1436     if (TyClass == Type::Pointer) {
1437       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1438       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1439     } else if (TyClass == Type::BlockPointer) {
1440       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1441       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1442     } else if (TyClass == Type::MemberPointer) {
1443       auto ToMPT = CanTo.getAs<MemberPointerType>();
1444       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1445       // A function pointer conversion cannot change the class of the function.
1446       if (ToMPT->getClass() != FromMPT->getClass())
1447         return false;
1448       CanTo = ToMPT->getPointeeType();
1449       CanFrom = FromMPT->getPointeeType();
1450     } else {
1451       return false;
1452     }
1453 
1454     TyClass = CanTo->getTypeClass();
1455     if (TyClass != CanFrom->getTypeClass()) return false;
1456     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1457       return false;
1458   }
1459 
1460   const auto *FromFn = cast<FunctionType>(CanFrom);
1461   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1462 
1463   const auto *ToFn = cast<FunctionType>(CanTo);
1464   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1465 
1466   bool Changed = false;
1467 
1468   // Drop 'noreturn' if not present in target type.
1469   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1470     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1471     Changed = true;
1472   }
1473 
1474   // Drop 'noexcept' if not present in target type.
1475   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1476     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1477     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1478       FromFn = cast<FunctionType>(
1479           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1480                                                    EST_None)
1481                  .getTypePtr());
1482       Changed = true;
1483     }
1484 
1485     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1486     // only if the ExtParameterInfo lists of the two function prototypes can be
1487     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1488     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1489     bool CanUseToFPT, CanUseFromFPT;
1490     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1491                                       CanUseFromFPT, NewParamInfos) &&
1492         CanUseToFPT && !CanUseFromFPT) {
1493       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1494       ExtInfo.ExtParameterInfos =
1495           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1496       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1497                                             FromFPT->getParamTypes(), ExtInfo);
1498       FromFn = QT->getAs<FunctionType>();
1499       Changed = true;
1500     }
1501   }
1502 
1503   if (!Changed)
1504     return false;
1505 
1506   assert(QualType(FromFn, 0).isCanonical());
1507   if (QualType(FromFn, 0) != CanTo) return false;
1508 
1509   ResultTy = ToType;
1510   return true;
1511 }
1512 
1513 /// \brief Determine whether the conversion from FromType to ToType is a valid
1514 /// vector conversion.
1515 ///
1516 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1517 /// conversion.
1518 static bool IsVectorConversion(Sema &S, QualType FromType,
1519                                QualType ToType, ImplicitConversionKind &ICK) {
1520   // We need at least one of these types to be a vector type to have a vector
1521   // conversion.
1522   if (!ToType->isVectorType() && !FromType->isVectorType())
1523     return false;
1524 
1525   // Identical types require no conversions.
1526   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1527     return false;
1528 
1529   // There are no conversions between extended vector types, only identity.
1530   if (ToType->isExtVectorType()) {
1531     // There are no conversions between extended vector types other than the
1532     // identity conversion.
1533     if (FromType->isExtVectorType())
1534       return false;
1535 
1536     // Vector splat from any arithmetic type to a vector.
1537     if (FromType->isArithmeticType()) {
1538       ICK = ICK_Vector_Splat;
1539       return true;
1540     }
1541   }
1542 
1543   // We can perform the conversion between vector types in the following cases:
1544   // 1)vector types are equivalent AltiVec and GCC vector types
1545   // 2)lax vector conversions are permitted and the vector types are of the
1546   //   same size
1547   if (ToType->isVectorType() && FromType->isVectorType()) {
1548     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1549         S.isLaxVectorConversion(FromType, ToType)) {
1550       ICK = ICK_Vector_Conversion;
1551       return true;
1552     }
1553   }
1554 
1555   return false;
1556 }
1557 
1558 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1559                                 bool InOverloadResolution,
1560                                 StandardConversionSequence &SCS,
1561                                 bool CStyle);
1562 
1563 /// IsStandardConversion - Determines whether there is a standard
1564 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1565 /// expression From to the type ToType. Standard conversion sequences
1566 /// only consider non-class types; for conversions that involve class
1567 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1568 /// contain the standard conversion sequence required to perform this
1569 /// conversion and this routine will return true. Otherwise, this
1570 /// routine will return false and the value of SCS is unspecified.
1571 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1572                                  bool InOverloadResolution,
1573                                  StandardConversionSequence &SCS,
1574                                  bool CStyle,
1575                                  bool AllowObjCWritebackConversion) {
1576   QualType FromType = From->getType();
1577 
1578   // Standard conversions (C++ [conv])
1579   SCS.setAsIdentityConversion();
1580   SCS.IncompatibleObjC = false;
1581   SCS.setFromType(FromType);
1582   SCS.CopyConstructor = nullptr;
1583 
1584   // There are no standard conversions for class types in C++, so
1585   // abort early. When overloading in C, however, we do permit them.
1586   if (S.getLangOpts().CPlusPlus &&
1587       (FromType->isRecordType() || ToType->isRecordType()))
1588     return false;
1589 
1590   // The first conversion can be an lvalue-to-rvalue conversion,
1591   // array-to-pointer conversion, or function-to-pointer conversion
1592   // (C++ 4p1).
1593 
1594   if (FromType == S.Context.OverloadTy) {
1595     DeclAccessPair AccessPair;
1596     if (FunctionDecl *Fn
1597           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1598                                                  AccessPair)) {
1599       // We were able to resolve the address of the overloaded function,
1600       // so we can convert to the type of that function.
1601       FromType = Fn->getType();
1602       SCS.setFromType(FromType);
1603 
1604       // we can sometimes resolve &foo<int> regardless of ToType, so check
1605       // if the type matches (identity) or we are converting to bool
1606       if (!S.Context.hasSameUnqualifiedType(
1607                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1608         QualType resultTy;
1609         // if the function type matches except for [[noreturn]], it's ok
1610         if (!S.IsFunctionConversion(FromType,
1611               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1612           // otherwise, only a boolean conversion is standard
1613           if (!ToType->isBooleanType())
1614             return false;
1615       }
1616 
1617       // Check if the "from" expression is taking the address of an overloaded
1618       // function and recompute the FromType accordingly. Take advantage of the
1619       // fact that non-static member functions *must* have such an address-of
1620       // expression.
1621       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1622       if (Method && !Method->isStatic()) {
1623         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1624                "Non-unary operator on non-static member address");
1625         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1626                == UO_AddrOf &&
1627                "Non-address-of operator on non-static member address");
1628         const Type *ClassType
1629           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1630         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1631       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1632         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1633                UO_AddrOf &&
1634                "Non-address-of operator for overloaded function expression");
1635         FromType = S.Context.getPointerType(FromType);
1636       }
1637 
1638       // Check that we've computed the proper type after overload resolution.
1639       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1640       // be calling it from within an NDEBUG block.
1641       assert(S.Context.hasSameType(
1642         FromType,
1643         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1644     } else {
1645       return false;
1646     }
1647   }
1648   // Lvalue-to-rvalue conversion (C++11 4.1):
1649   //   A glvalue (3.10) of a non-function, non-array type T can
1650   //   be converted to a prvalue.
1651   bool argIsLValue = From->isGLValue();
1652   if (argIsLValue &&
1653       !FromType->isFunctionType() && !FromType->isArrayType() &&
1654       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1655     SCS.First = ICK_Lvalue_To_Rvalue;
1656 
1657     // C11 6.3.2.1p2:
1658     //   ... if the lvalue has atomic type, the value has the non-atomic version
1659     //   of the type of the lvalue ...
1660     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1661       FromType = Atomic->getValueType();
1662 
1663     // If T is a non-class type, the type of the rvalue is the
1664     // cv-unqualified version of T. Otherwise, the type of the rvalue
1665     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1666     // just strip the qualifiers because they don't matter.
1667     FromType = FromType.getUnqualifiedType();
1668   } else if (FromType->isArrayType()) {
1669     // Array-to-pointer conversion (C++ 4.2)
1670     SCS.First = ICK_Array_To_Pointer;
1671 
1672     // An lvalue or rvalue of type "array of N T" or "array of unknown
1673     // bound of T" can be converted to an rvalue of type "pointer to
1674     // T" (C++ 4.2p1).
1675     FromType = S.Context.getArrayDecayedType(FromType);
1676 
1677     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1678       // This conversion is deprecated in C++03 (D.4)
1679       SCS.DeprecatedStringLiteralToCharPtr = true;
1680 
1681       // For the purpose of ranking in overload resolution
1682       // (13.3.3.1.1), this conversion is considered an
1683       // array-to-pointer conversion followed by a qualification
1684       // conversion (4.4). (C++ 4.2p2)
1685       SCS.Second = ICK_Identity;
1686       SCS.Third = ICK_Qualification;
1687       SCS.QualificationIncludesObjCLifetime = false;
1688       SCS.setAllToTypes(FromType);
1689       return true;
1690     }
1691   } else if (FromType->isFunctionType() && argIsLValue) {
1692     // Function-to-pointer conversion (C++ 4.3).
1693     SCS.First = ICK_Function_To_Pointer;
1694 
1695     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1696       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1697         if (!S.checkAddressOfFunctionIsAvailable(FD))
1698           return false;
1699 
1700     // An lvalue of function type T can be converted to an rvalue of
1701     // type "pointer to T." The result is a pointer to the
1702     // function. (C++ 4.3p1).
1703     FromType = S.Context.getPointerType(FromType);
1704   } else {
1705     // We don't require any conversions for the first step.
1706     SCS.First = ICK_Identity;
1707   }
1708   SCS.setToType(0, FromType);
1709 
1710   // The second conversion can be an integral promotion, floating
1711   // point promotion, integral conversion, floating point conversion,
1712   // floating-integral conversion, pointer conversion,
1713   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1714   // For overloading in C, this can also be a "compatible-type"
1715   // conversion.
1716   bool IncompatibleObjC = false;
1717   ImplicitConversionKind SecondICK = ICK_Identity;
1718   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1719     // The unqualified versions of the types are the same: there's no
1720     // conversion to do.
1721     SCS.Second = ICK_Identity;
1722   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1723     // Integral promotion (C++ 4.5).
1724     SCS.Second = ICK_Integral_Promotion;
1725     FromType = ToType.getUnqualifiedType();
1726   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1727     // Floating point promotion (C++ 4.6).
1728     SCS.Second = ICK_Floating_Promotion;
1729     FromType = ToType.getUnqualifiedType();
1730   } else if (S.IsComplexPromotion(FromType, ToType)) {
1731     // Complex promotion (Clang extension)
1732     SCS.Second = ICK_Complex_Promotion;
1733     FromType = ToType.getUnqualifiedType();
1734   } else if (ToType->isBooleanType() &&
1735              (FromType->isArithmeticType() ||
1736               FromType->isAnyPointerType() ||
1737               FromType->isBlockPointerType() ||
1738               FromType->isMemberPointerType() ||
1739               FromType->isNullPtrType())) {
1740     // Boolean conversions (C++ 4.12).
1741     SCS.Second = ICK_Boolean_Conversion;
1742     FromType = S.Context.BoolTy;
1743   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1744              ToType->isIntegralType(S.Context)) {
1745     // Integral conversions (C++ 4.7).
1746     SCS.Second = ICK_Integral_Conversion;
1747     FromType = ToType.getUnqualifiedType();
1748   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1749     // Complex conversions (C99 6.3.1.6)
1750     SCS.Second = ICK_Complex_Conversion;
1751     FromType = ToType.getUnqualifiedType();
1752   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1753              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1754     // Complex-real conversions (C99 6.3.1.7)
1755     SCS.Second = ICK_Complex_Real;
1756     FromType = ToType.getUnqualifiedType();
1757   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1758     // FIXME: disable conversions between long double and __float128 if
1759     // their representation is different until there is back end support
1760     // We of course allow this conversion if long double is really double.
1761     if (&S.Context.getFloatTypeSemantics(FromType) !=
1762         &S.Context.getFloatTypeSemantics(ToType)) {
1763       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1764                                     ToType == S.Context.LongDoubleTy) ||
1765                                    (FromType == S.Context.LongDoubleTy &&
1766                                     ToType == S.Context.Float128Ty));
1767       if (Float128AndLongDouble &&
1768           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1769            &llvm::APFloat::PPCDoubleDouble()))
1770         return false;
1771     }
1772     // Floating point conversions (C++ 4.8).
1773     SCS.Second = ICK_Floating_Conversion;
1774     FromType = ToType.getUnqualifiedType();
1775   } else if ((FromType->isRealFloatingType() &&
1776               ToType->isIntegralType(S.Context)) ||
1777              (FromType->isIntegralOrUnscopedEnumerationType() &&
1778               ToType->isRealFloatingType())) {
1779     // Floating-integral conversions (C++ 4.9).
1780     SCS.Second = ICK_Floating_Integral;
1781     FromType = ToType.getUnqualifiedType();
1782   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1783     SCS.Second = ICK_Block_Pointer_Conversion;
1784   } else if (AllowObjCWritebackConversion &&
1785              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1786     SCS.Second = ICK_Writeback_Conversion;
1787   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1788                                    FromType, IncompatibleObjC)) {
1789     // Pointer conversions (C++ 4.10).
1790     SCS.Second = ICK_Pointer_Conversion;
1791     SCS.IncompatibleObjC = IncompatibleObjC;
1792     FromType = FromType.getUnqualifiedType();
1793   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1794                                          InOverloadResolution, FromType)) {
1795     // Pointer to member conversions (4.11).
1796     SCS.Second = ICK_Pointer_Member;
1797   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1798     SCS.Second = SecondICK;
1799     FromType = ToType.getUnqualifiedType();
1800   } else if (!S.getLangOpts().CPlusPlus &&
1801              S.Context.typesAreCompatible(ToType, FromType)) {
1802     // Compatible conversions (Clang extension for C function overloading)
1803     SCS.Second = ICK_Compatible_Conversion;
1804     FromType = ToType.getUnqualifiedType();
1805   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1806                                              InOverloadResolution,
1807                                              SCS, CStyle)) {
1808     SCS.Second = ICK_TransparentUnionConversion;
1809     FromType = ToType;
1810   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1811                                  CStyle)) {
1812     // tryAtomicConversion has updated the standard conversion sequence
1813     // appropriately.
1814     return true;
1815   } else if (ToType->isEventT() &&
1816              From->isIntegerConstantExpr(S.getASTContext()) &&
1817              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1818     SCS.Second = ICK_Zero_Event_Conversion;
1819     FromType = ToType;
1820   } else if (ToType->isQueueT() &&
1821              From->isIntegerConstantExpr(S.getASTContext()) &&
1822              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1823     SCS.Second = ICK_Zero_Queue_Conversion;
1824     FromType = ToType;
1825   } else {
1826     // No second conversion required.
1827     SCS.Second = ICK_Identity;
1828   }
1829   SCS.setToType(1, FromType);
1830 
1831   // The third conversion can be a function pointer conversion or a
1832   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1833   bool ObjCLifetimeConversion;
1834   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1835     // Function pointer conversions (removing 'noexcept') including removal of
1836     // 'noreturn' (Clang extension).
1837     SCS.Third = ICK_Function_Conversion;
1838   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1839                                          ObjCLifetimeConversion)) {
1840     SCS.Third = ICK_Qualification;
1841     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1842     FromType = ToType;
1843   } else {
1844     // No conversion required
1845     SCS.Third = ICK_Identity;
1846   }
1847 
1848   // C++ [over.best.ics]p6:
1849   //   [...] Any difference in top-level cv-qualification is
1850   //   subsumed by the initialization itself and does not constitute
1851   //   a conversion. [...]
1852   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1853   QualType CanonTo = S.Context.getCanonicalType(ToType);
1854   if (CanonFrom.getLocalUnqualifiedType()
1855                                      == CanonTo.getLocalUnqualifiedType() &&
1856       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1857     FromType = ToType;
1858     CanonFrom = CanonTo;
1859   }
1860 
1861   SCS.setToType(2, FromType);
1862 
1863   if (CanonFrom == CanonTo)
1864     return true;
1865 
1866   // If we have not converted the argument type to the parameter type,
1867   // this is a bad conversion sequence, unless we're resolving an overload in C.
1868   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1869     return false;
1870 
1871   ExprResult ER = ExprResult{From};
1872   Sema::AssignConvertType Conv =
1873       S.CheckSingleAssignmentConstraints(ToType, ER,
1874                                          /*Diagnose=*/false,
1875                                          /*DiagnoseCFAudited=*/false,
1876                                          /*ConvertRHS=*/false);
1877   ImplicitConversionKind SecondConv;
1878   switch (Conv) {
1879   case Sema::Compatible:
1880     SecondConv = ICK_C_Only_Conversion;
1881     break;
1882   // For our purposes, discarding qualifiers is just as bad as using an
1883   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1884   // qualifiers, as well.
1885   case Sema::CompatiblePointerDiscardsQualifiers:
1886   case Sema::IncompatiblePointer:
1887   case Sema::IncompatiblePointerSign:
1888     SecondConv = ICK_Incompatible_Pointer_Conversion;
1889     break;
1890   default:
1891     return false;
1892   }
1893 
1894   // First can only be an lvalue conversion, so we pretend that this was the
1895   // second conversion. First should already be valid from earlier in the
1896   // function.
1897   SCS.Second = SecondConv;
1898   SCS.setToType(1, ToType);
1899 
1900   // Third is Identity, because Second should rank us worse than any other
1901   // conversion. This could also be ICK_Qualification, but it's simpler to just
1902   // lump everything in with the second conversion, and we don't gain anything
1903   // from making this ICK_Qualification.
1904   SCS.Third = ICK_Identity;
1905   SCS.setToType(2, ToType);
1906   return true;
1907 }
1908 
1909 static bool
1910 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1911                                      QualType &ToType,
1912                                      bool InOverloadResolution,
1913                                      StandardConversionSequence &SCS,
1914                                      bool CStyle) {
1915 
1916   const RecordType *UT = ToType->getAsUnionType();
1917   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1918     return false;
1919   // The field to initialize within the transparent union.
1920   RecordDecl *UD = UT->getDecl();
1921   // It's compatible if the expression matches any of the fields.
1922   for (const auto *it : UD->fields()) {
1923     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1924                              CStyle, /*ObjCWritebackConversion=*/false)) {
1925       ToType = it->getType();
1926       return true;
1927     }
1928   }
1929   return false;
1930 }
1931 
1932 /// IsIntegralPromotion - Determines whether the conversion from the
1933 /// expression From (whose potentially-adjusted type is FromType) to
1934 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1935 /// sets PromotedType to the promoted type.
1936 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1937   const BuiltinType *To = ToType->getAs<BuiltinType>();
1938   // All integers are built-in.
1939   if (!To) {
1940     return false;
1941   }
1942 
1943   // An rvalue of type char, signed char, unsigned char, short int, or
1944   // unsigned short int can be converted to an rvalue of type int if
1945   // int can represent all the values of the source type; otherwise,
1946   // the source rvalue can be converted to an rvalue of type unsigned
1947   // int (C++ 4.5p1).
1948   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1949       !FromType->isEnumeralType()) {
1950     if (// We can promote any signed, promotable integer type to an int
1951         (FromType->isSignedIntegerType() ||
1952          // We can promote any unsigned integer type whose size is
1953          // less than int to an int.
1954          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1955       return To->getKind() == BuiltinType::Int;
1956     }
1957 
1958     return To->getKind() == BuiltinType::UInt;
1959   }
1960 
1961   // C++11 [conv.prom]p3:
1962   //   A prvalue of an unscoped enumeration type whose underlying type is not
1963   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1964   //   following types that can represent all the values of the enumeration
1965   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1966   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1967   //   long long int. If none of the types in that list can represent all the
1968   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1969   //   type can be converted to an rvalue a prvalue of the extended integer type
1970   //   with lowest integer conversion rank (4.13) greater than the rank of long
1971   //   long in which all the values of the enumeration can be represented. If
1972   //   there are two such extended types, the signed one is chosen.
1973   // C++11 [conv.prom]p4:
1974   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1975   //   can be converted to a prvalue of its underlying type. Moreover, if
1976   //   integral promotion can be applied to its underlying type, a prvalue of an
1977   //   unscoped enumeration type whose underlying type is fixed can also be
1978   //   converted to a prvalue of the promoted underlying type.
1979   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1980     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1981     // provided for a scoped enumeration.
1982     if (FromEnumType->getDecl()->isScoped())
1983       return false;
1984 
1985     // We can perform an integral promotion to the underlying type of the enum,
1986     // even if that's not the promoted type. Note that the check for promoting
1987     // the underlying type is based on the type alone, and does not consider
1988     // the bitfield-ness of the actual source expression.
1989     if (FromEnumType->getDecl()->isFixed()) {
1990       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1991       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1992              IsIntegralPromotion(nullptr, Underlying, ToType);
1993     }
1994 
1995     // We have already pre-calculated the promotion type, so this is trivial.
1996     if (ToType->isIntegerType() &&
1997         isCompleteType(From->getLocStart(), FromType))
1998       return Context.hasSameUnqualifiedType(
1999           ToType, FromEnumType->getDecl()->getPromotionType());
2000   }
2001 
2002   // C++0x [conv.prom]p2:
2003   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2004   //   to an rvalue a prvalue of the first of the following types that can
2005   //   represent all the values of its underlying type: int, unsigned int,
2006   //   long int, unsigned long int, long long int, or unsigned long long int.
2007   //   If none of the types in that list can represent all the values of its
2008   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2009   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2010   //   type.
2011   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2012       ToType->isIntegerType()) {
2013     // Determine whether the type we're converting from is signed or
2014     // unsigned.
2015     bool FromIsSigned = FromType->isSignedIntegerType();
2016     uint64_t FromSize = Context.getTypeSize(FromType);
2017 
2018     // The types we'll try to promote to, in the appropriate
2019     // order. Try each of these types.
2020     QualType PromoteTypes[6] = {
2021       Context.IntTy, Context.UnsignedIntTy,
2022       Context.LongTy, Context.UnsignedLongTy ,
2023       Context.LongLongTy, Context.UnsignedLongLongTy
2024     };
2025     for (int Idx = 0; Idx < 6; ++Idx) {
2026       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2027       if (FromSize < ToSize ||
2028           (FromSize == ToSize &&
2029            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2030         // We found the type that we can promote to. If this is the
2031         // type we wanted, we have a promotion. Otherwise, no
2032         // promotion.
2033         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2034       }
2035     }
2036   }
2037 
2038   // An rvalue for an integral bit-field (9.6) can be converted to an
2039   // rvalue of type int if int can represent all the values of the
2040   // bit-field; otherwise, it can be converted to unsigned int if
2041   // unsigned int can represent all the values of the bit-field. If
2042   // the bit-field is larger yet, no integral promotion applies to
2043   // it. If the bit-field has an enumerated type, it is treated as any
2044   // other value of that type for promotion purposes (C++ 4.5p3).
2045   // FIXME: We should delay checking of bit-fields until we actually perform the
2046   // conversion.
2047   if (From) {
2048     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2049       llvm::APSInt BitWidth;
2050       if (FromType->isIntegralType(Context) &&
2051           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2052         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2053         ToSize = Context.getTypeSize(ToType);
2054 
2055         // Are we promoting to an int from a bitfield that fits in an int?
2056         if (BitWidth < ToSize ||
2057             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2058           return To->getKind() == BuiltinType::Int;
2059         }
2060 
2061         // Are we promoting to an unsigned int from an unsigned bitfield
2062         // that fits into an unsigned int?
2063         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2064           return To->getKind() == BuiltinType::UInt;
2065         }
2066 
2067         return false;
2068       }
2069     }
2070   }
2071 
2072   // An rvalue of type bool can be converted to an rvalue of type int,
2073   // with false becoming zero and true becoming one (C++ 4.5p4).
2074   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2075     return true;
2076   }
2077 
2078   return false;
2079 }
2080 
2081 /// IsFloatingPointPromotion - Determines whether the conversion from
2082 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2083 /// returns true and sets PromotedType to the promoted type.
2084 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2085   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2086     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2087       /// An rvalue of type float can be converted to an rvalue of type
2088       /// double. (C++ 4.6p1).
2089       if (FromBuiltin->getKind() == BuiltinType::Float &&
2090           ToBuiltin->getKind() == BuiltinType::Double)
2091         return true;
2092 
2093       // C99 6.3.1.5p1:
2094       //   When a float is promoted to double or long double, or a
2095       //   double is promoted to long double [...].
2096       if (!getLangOpts().CPlusPlus &&
2097           (FromBuiltin->getKind() == BuiltinType::Float ||
2098            FromBuiltin->getKind() == BuiltinType::Double) &&
2099           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2100            ToBuiltin->getKind() == BuiltinType::Float128))
2101         return true;
2102 
2103       // Half can be promoted to float.
2104       if (!getLangOpts().NativeHalfType &&
2105            FromBuiltin->getKind() == BuiltinType::Half &&
2106           ToBuiltin->getKind() == BuiltinType::Float)
2107         return true;
2108     }
2109 
2110   return false;
2111 }
2112 
2113 /// \brief Determine if a conversion is a complex promotion.
2114 ///
2115 /// A complex promotion is defined as a complex -> complex conversion
2116 /// where the conversion between the underlying real types is a
2117 /// floating-point or integral promotion.
2118 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2119   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2120   if (!FromComplex)
2121     return false;
2122 
2123   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2124   if (!ToComplex)
2125     return false;
2126 
2127   return IsFloatingPointPromotion(FromComplex->getElementType(),
2128                                   ToComplex->getElementType()) ||
2129     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2130                         ToComplex->getElementType());
2131 }
2132 
2133 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2134 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2135 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2136 /// if non-empty, will be a pointer to ToType that may or may not have
2137 /// the right set of qualifiers on its pointee.
2138 ///
2139 static QualType
2140 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2141                                    QualType ToPointee, QualType ToType,
2142                                    ASTContext &Context,
2143                                    bool StripObjCLifetime = false) {
2144   assert((FromPtr->getTypeClass() == Type::Pointer ||
2145           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2146          "Invalid similarly-qualified pointer type");
2147 
2148   /// Conversions to 'id' subsume cv-qualifier conversions.
2149   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2150     return ToType.getUnqualifiedType();
2151 
2152   QualType CanonFromPointee
2153     = Context.getCanonicalType(FromPtr->getPointeeType());
2154   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2155   Qualifiers Quals = CanonFromPointee.getQualifiers();
2156 
2157   if (StripObjCLifetime)
2158     Quals.removeObjCLifetime();
2159 
2160   // Exact qualifier match -> return the pointer type we're converting to.
2161   if (CanonToPointee.getLocalQualifiers() == Quals) {
2162     // ToType is exactly what we need. Return it.
2163     if (!ToType.isNull())
2164       return ToType.getUnqualifiedType();
2165 
2166     // Build a pointer to ToPointee. It has the right qualifiers
2167     // already.
2168     if (isa<ObjCObjectPointerType>(ToType))
2169       return Context.getObjCObjectPointerType(ToPointee);
2170     return Context.getPointerType(ToPointee);
2171   }
2172 
2173   // Just build a canonical type that has the right qualifiers.
2174   QualType QualifiedCanonToPointee
2175     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2176 
2177   if (isa<ObjCObjectPointerType>(ToType))
2178     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2179   return Context.getPointerType(QualifiedCanonToPointee);
2180 }
2181 
2182 static bool isNullPointerConstantForConversion(Expr *Expr,
2183                                                bool InOverloadResolution,
2184                                                ASTContext &Context) {
2185   // Handle value-dependent integral null pointer constants correctly.
2186   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2187   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2188       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2189     return !InOverloadResolution;
2190 
2191   return Expr->isNullPointerConstant(Context,
2192                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2193                                         : Expr::NPC_ValueDependentIsNull);
2194 }
2195 
2196 /// IsPointerConversion - Determines whether the conversion of the
2197 /// expression From, which has the (possibly adjusted) type FromType,
2198 /// can be converted to the type ToType via a pointer conversion (C++
2199 /// 4.10). If so, returns true and places the converted type (that
2200 /// might differ from ToType in its cv-qualifiers at some level) into
2201 /// ConvertedType.
2202 ///
2203 /// This routine also supports conversions to and from block pointers
2204 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2205 /// pointers to interfaces. FIXME: Once we've determined the
2206 /// appropriate overloading rules for Objective-C, we may want to
2207 /// split the Objective-C checks into a different routine; however,
2208 /// GCC seems to consider all of these conversions to be pointer
2209 /// conversions, so for now they live here. IncompatibleObjC will be
2210 /// set if the conversion is an allowed Objective-C conversion that
2211 /// should result in a warning.
2212 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2213                                bool InOverloadResolution,
2214                                QualType& ConvertedType,
2215                                bool &IncompatibleObjC) {
2216   IncompatibleObjC = false;
2217   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2218                               IncompatibleObjC))
2219     return true;
2220 
2221   // Conversion from a null pointer constant to any Objective-C pointer type.
2222   if (ToType->isObjCObjectPointerType() &&
2223       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2224     ConvertedType = ToType;
2225     return true;
2226   }
2227 
2228   // Blocks: Block pointers can be converted to void*.
2229   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2230       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2231     ConvertedType = ToType;
2232     return true;
2233   }
2234   // Blocks: A null pointer constant can be converted to a block
2235   // pointer type.
2236   if (ToType->isBlockPointerType() &&
2237       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2238     ConvertedType = ToType;
2239     return true;
2240   }
2241 
2242   // If the left-hand-side is nullptr_t, the right side can be a null
2243   // pointer constant.
2244   if (ToType->isNullPtrType() &&
2245       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2246     ConvertedType = ToType;
2247     return true;
2248   }
2249 
2250   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2251   if (!ToTypePtr)
2252     return false;
2253 
2254   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2255   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2256     ConvertedType = ToType;
2257     return true;
2258   }
2259 
2260   // Beyond this point, both types need to be pointers
2261   // , including objective-c pointers.
2262   QualType ToPointeeType = ToTypePtr->getPointeeType();
2263   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2264       !getLangOpts().ObjCAutoRefCount) {
2265     ConvertedType = BuildSimilarlyQualifiedPointerType(
2266                                       FromType->getAs<ObjCObjectPointerType>(),
2267                                                        ToPointeeType,
2268                                                        ToType, Context);
2269     return true;
2270   }
2271   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2272   if (!FromTypePtr)
2273     return false;
2274 
2275   QualType FromPointeeType = FromTypePtr->getPointeeType();
2276 
2277   // If the unqualified pointee types are the same, this can't be a
2278   // pointer conversion, so don't do all of the work below.
2279   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2280     return false;
2281 
2282   // An rvalue of type "pointer to cv T," where T is an object type,
2283   // can be converted to an rvalue of type "pointer to cv void" (C++
2284   // 4.10p2).
2285   if (FromPointeeType->isIncompleteOrObjectType() &&
2286       ToPointeeType->isVoidType()) {
2287     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2288                                                        ToPointeeType,
2289                                                        ToType, Context,
2290                                                    /*StripObjCLifetime=*/true);
2291     return true;
2292   }
2293 
2294   // MSVC allows implicit function to void* type conversion.
2295   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2296       ToPointeeType->isVoidType()) {
2297     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2298                                                        ToPointeeType,
2299                                                        ToType, Context);
2300     return true;
2301   }
2302 
2303   // When we're overloading in C, we allow a special kind of pointer
2304   // conversion for compatible-but-not-identical pointee types.
2305   if (!getLangOpts().CPlusPlus &&
2306       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2307     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2308                                                        ToPointeeType,
2309                                                        ToType, Context);
2310     return true;
2311   }
2312 
2313   // C++ [conv.ptr]p3:
2314   //
2315   //   An rvalue of type "pointer to cv D," where D is a class type,
2316   //   can be converted to an rvalue of type "pointer to cv B," where
2317   //   B is a base class (clause 10) of D. If B is an inaccessible
2318   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2319   //   necessitates this conversion is ill-formed. The result of the
2320   //   conversion is a pointer to the base class sub-object of the
2321   //   derived class object. The null pointer value is converted to
2322   //   the null pointer value of the destination type.
2323   //
2324   // Note that we do not check for ambiguity or inaccessibility
2325   // here. That is handled by CheckPointerConversion.
2326   if (getLangOpts().CPlusPlus &&
2327       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2328       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2329       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2330     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2331                                                        ToPointeeType,
2332                                                        ToType, Context);
2333     return true;
2334   }
2335 
2336   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2337       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2338     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339                                                        ToPointeeType,
2340                                                        ToType, Context);
2341     return true;
2342   }
2343 
2344   return false;
2345 }
2346 
2347 /// \brief Adopt the given qualifiers for the given type.
2348 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2349   Qualifiers TQs = T.getQualifiers();
2350 
2351   // Check whether qualifiers already match.
2352   if (TQs == Qs)
2353     return T;
2354 
2355   if (Qs.compatiblyIncludes(TQs))
2356     return Context.getQualifiedType(T, Qs);
2357 
2358   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2359 }
2360 
2361 /// isObjCPointerConversion - Determines whether this is an
2362 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2363 /// with the same arguments and return values.
2364 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2365                                    QualType& ConvertedType,
2366                                    bool &IncompatibleObjC) {
2367   if (!getLangOpts().ObjC1)
2368     return false;
2369 
2370   // The set of qualifiers on the type we're converting from.
2371   Qualifiers FromQualifiers = FromType.getQualifiers();
2372 
2373   // First, we handle all conversions on ObjC object pointer types.
2374   const ObjCObjectPointerType* ToObjCPtr =
2375     ToType->getAs<ObjCObjectPointerType>();
2376   const ObjCObjectPointerType *FromObjCPtr =
2377     FromType->getAs<ObjCObjectPointerType>();
2378 
2379   if (ToObjCPtr && FromObjCPtr) {
2380     // If the pointee types are the same (ignoring qualifications),
2381     // then this is not a pointer conversion.
2382     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2383                                        FromObjCPtr->getPointeeType()))
2384       return false;
2385 
2386     // Conversion between Objective-C pointers.
2387     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2388       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2389       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2390       if (getLangOpts().CPlusPlus && LHS && RHS &&
2391           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2392                                                 FromObjCPtr->getPointeeType()))
2393         return false;
2394       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2395                                                    ToObjCPtr->getPointeeType(),
2396                                                          ToType, Context);
2397       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2398       return true;
2399     }
2400 
2401     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2402       // Okay: this is some kind of implicit downcast of Objective-C
2403       // interfaces, which is permitted. However, we're going to
2404       // complain about it.
2405       IncompatibleObjC = true;
2406       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2407                                                    ToObjCPtr->getPointeeType(),
2408                                                          ToType, Context);
2409       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2410       return true;
2411     }
2412   }
2413   // Beyond this point, both types need to be C pointers or block pointers.
2414   QualType ToPointeeType;
2415   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2416     ToPointeeType = ToCPtr->getPointeeType();
2417   else if (const BlockPointerType *ToBlockPtr =
2418             ToType->getAs<BlockPointerType>()) {
2419     // Objective C++: We're able to convert from a pointer to any object
2420     // to a block pointer type.
2421     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2422       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2423       return true;
2424     }
2425     ToPointeeType = ToBlockPtr->getPointeeType();
2426   }
2427   else if (FromType->getAs<BlockPointerType>() &&
2428            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2429     // Objective C++: We're able to convert from a block pointer type to a
2430     // pointer to any object.
2431     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2432     return true;
2433   }
2434   else
2435     return false;
2436 
2437   QualType FromPointeeType;
2438   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2439     FromPointeeType = FromCPtr->getPointeeType();
2440   else if (const BlockPointerType *FromBlockPtr =
2441            FromType->getAs<BlockPointerType>())
2442     FromPointeeType = FromBlockPtr->getPointeeType();
2443   else
2444     return false;
2445 
2446   // If we have pointers to pointers, recursively check whether this
2447   // is an Objective-C conversion.
2448   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2449       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2450                               IncompatibleObjC)) {
2451     // We always complain about this conversion.
2452     IncompatibleObjC = true;
2453     ConvertedType = Context.getPointerType(ConvertedType);
2454     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2455     return true;
2456   }
2457   // Allow conversion of pointee being objective-c pointer to another one;
2458   // as in I* to id.
2459   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2460       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2461       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2462                               IncompatibleObjC)) {
2463 
2464     ConvertedType = Context.getPointerType(ConvertedType);
2465     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2466     return true;
2467   }
2468 
2469   // If we have pointers to functions or blocks, check whether the only
2470   // differences in the argument and result types are in Objective-C
2471   // pointer conversions. If so, we permit the conversion (but
2472   // complain about it).
2473   const FunctionProtoType *FromFunctionType
2474     = FromPointeeType->getAs<FunctionProtoType>();
2475   const FunctionProtoType *ToFunctionType
2476     = ToPointeeType->getAs<FunctionProtoType>();
2477   if (FromFunctionType && ToFunctionType) {
2478     // If the function types are exactly the same, this isn't an
2479     // Objective-C pointer conversion.
2480     if (Context.getCanonicalType(FromPointeeType)
2481           == Context.getCanonicalType(ToPointeeType))
2482       return false;
2483 
2484     // Perform the quick checks that will tell us whether these
2485     // function types are obviously different.
2486     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2487         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2488         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2489       return false;
2490 
2491     bool HasObjCConversion = false;
2492     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2493         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2494       // Okay, the types match exactly. Nothing to do.
2495     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2496                                        ToFunctionType->getReturnType(),
2497                                        ConvertedType, IncompatibleObjC)) {
2498       // Okay, we have an Objective-C pointer conversion.
2499       HasObjCConversion = true;
2500     } else {
2501       // Function types are too different. Abort.
2502       return false;
2503     }
2504 
2505     // Check argument types.
2506     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2507          ArgIdx != NumArgs; ++ArgIdx) {
2508       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2509       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2510       if (Context.getCanonicalType(FromArgType)
2511             == Context.getCanonicalType(ToArgType)) {
2512         // Okay, the types match exactly. Nothing to do.
2513       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2514                                          ConvertedType, IncompatibleObjC)) {
2515         // Okay, we have an Objective-C pointer conversion.
2516         HasObjCConversion = true;
2517       } else {
2518         // Argument types are too different. Abort.
2519         return false;
2520       }
2521     }
2522 
2523     if (HasObjCConversion) {
2524       // We had an Objective-C conversion. Allow this pointer
2525       // conversion, but complain about it.
2526       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2527       IncompatibleObjC = true;
2528       return true;
2529     }
2530   }
2531 
2532   return false;
2533 }
2534 
2535 /// \brief Determine whether this is an Objective-C writeback conversion,
2536 /// used for parameter passing when performing automatic reference counting.
2537 ///
2538 /// \param FromType The type we're converting form.
2539 ///
2540 /// \param ToType The type we're converting to.
2541 ///
2542 /// \param ConvertedType The type that will be produced after applying
2543 /// this conversion.
2544 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2545                                      QualType &ConvertedType) {
2546   if (!getLangOpts().ObjCAutoRefCount ||
2547       Context.hasSameUnqualifiedType(FromType, ToType))
2548     return false;
2549 
2550   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2551   QualType ToPointee;
2552   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2553     ToPointee = ToPointer->getPointeeType();
2554   else
2555     return false;
2556 
2557   Qualifiers ToQuals = ToPointee.getQualifiers();
2558   if (!ToPointee->isObjCLifetimeType() ||
2559       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2560       !ToQuals.withoutObjCLifetime().empty())
2561     return false;
2562 
2563   // Argument must be a pointer to __strong to __weak.
2564   QualType FromPointee;
2565   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2566     FromPointee = FromPointer->getPointeeType();
2567   else
2568     return false;
2569 
2570   Qualifiers FromQuals = FromPointee.getQualifiers();
2571   if (!FromPointee->isObjCLifetimeType() ||
2572       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2573        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2574     return false;
2575 
2576   // Make sure that we have compatible qualifiers.
2577   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2578   if (!ToQuals.compatiblyIncludes(FromQuals))
2579     return false;
2580 
2581   // Remove qualifiers from the pointee type we're converting from; they
2582   // aren't used in the compatibility check belong, and we'll be adding back
2583   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2584   FromPointee = FromPointee.getUnqualifiedType();
2585 
2586   // The unqualified form of the pointee types must be compatible.
2587   ToPointee = ToPointee.getUnqualifiedType();
2588   bool IncompatibleObjC;
2589   if (Context.typesAreCompatible(FromPointee, ToPointee))
2590     FromPointee = ToPointee;
2591   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2592                                     IncompatibleObjC))
2593     return false;
2594 
2595   /// \brief Construct the type we're converting to, which is a pointer to
2596   /// __autoreleasing pointee.
2597   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2598   ConvertedType = Context.getPointerType(FromPointee);
2599   return true;
2600 }
2601 
2602 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2603                                     QualType& ConvertedType) {
2604   QualType ToPointeeType;
2605   if (const BlockPointerType *ToBlockPtr =
2606         ToType->getAs<BlockPointerType>())
2607     ToPointeeType = ToBlockPtr->getPointeeType();
2608   else
2609     return false;
2610 
2611   QualType FromPointeeType;
2612   if (const BlockPointerType *FromBlockPtr =
2613       FromType->getAs<BlockPointerType>())
2614     FromPointeeType = FromBlockPtr->getPointeeType();
2615   else
2616     return false;
2617   // We have pointer to blocks, check whether the only
2618   // differences in the argument and result types are in Objective-C
2619   // pointer conversions. If so, we permit the conversion.
2620 
2621   const FunctionProtoType *FromFunctionType
2622     = FromPointeeType->getAs<FunctionProtoType>();
2623   const FunctionProtoType *ToFunctionType
2624     = ToPointeeType->getAs<FunctionProtoType>();
2625 
2626   if (!FromFunctionType || !ToFunctionType)
2627     return false;
2628 
2629   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2630     return true;
2631 
2632   // Perform the quick checks that will tell us whether these
2633   // function types are obviously different.
2634   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2635       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2636     return false;
2637 
2638   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2639   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2640   if (FromEInfo != ToEInfo)
2641     return false;
2642 
2643   bool IncompatibleObjC = false;
2644   if (Context.hasSameType(FromFunctionType->getReturnType(),
2645                           ToFunctionType->getReturnType())) {
2646     // Okay, the types match exactly. Nothing to do.
2647   } else {
2648     QualType RHS = FromFunctionType->getReturnType();
2649     QualType LHS = ToFunctionType->getReturnType();
2650     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2651         !RHS.hasQualifiers() && LHS.hasQualifiers())
2652        LHS = LHS.getUnqualifiedType();
2653 
2654      if (Context.hasSameType(RHS,LHS)) {
2655        // OK exact match.
2656      } else if (isObjCPointerConversion(RHS, LHS,
2657                                         ConvertedType, IncompatibleObjC)) {
2658      if (IncompatibleObjC)
2659        return false;
2660      // Okay, we have an Objective-C pointer conversion.
2661      }
2662      else
2663        return false;
2664    }
2665 
2666    // Check argument types.
2667    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2668         ArgIdx != NumArgs; ++ArgIdx) {
2669      IncompatibleObjC = false;
2670      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2671      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2672      if (Context.hasSameType(FromArgType, ToArgType)) {
2673        // Okay, the types match exactly. Nothing to do.
2674      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2675                                         ConvertedType, IncompatibleObjC)) {
2676        if (IncompatibleObjC)
2677          return false;
2678        // Okay, we have an Objective-C pointer conversion.
2679      } else
2680        // Argument types are too different. Abort.
2681        return false;
2682    }
2683 
2684    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2685    bool CanUseToFPT, CanUseFromFPT;
2686    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2687                                       CanUseToFPT, CanUseFromFPT,
2688                                       NewParamInfos))
2689      return false;
2690 
2691    ConvertedType = ToType;
2692    return true;
2693 }
2694 
2695 enum {
2696   ft_default,
2697   ft_different_class,
2698   ft_parameter_arity,
2699   ft_parameter_mismatch,
2700   ft_return_type,
2701   ft_qualifer_mismatch,
2702   ft_noexcept
2703 };
2704 
2705 /// Attempts to get the FunctionProtoType from a Type. Handles
2706 /// MemberFunctionPointers properly.
2707 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2708   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2709     return FPT;
2710 
2711   if (auto *MPT = FromType->getAs<MemberPointerType>())
2712     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2713 
2714   return nullptr;
2715 }
2716 
2717 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2718 /// function types.  Catches different number of parameter, mismatch in
2719 /// parameter types, and different return types.
2720 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2721                                       QualType FromType, QualType ToType) {
2722   // If either type is not valid, include no extra info.
2723   if (FromType.isNull() || ToType.isNull()) {
2724     PDiag << ft_default;
2725     return;
2726   }
2727 
2728   // Get the function type from the pointers.
2729   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2730     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2731                             *ToMember = ToType->getAs<MemberPointerType>();
2732     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2733       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2734             << QualType(FromMember->getClass(), 0);
2735       return;
2736     }
2737     FromType = FromMember->getPointeeType();
2738     ToType = ToMember->getPointeeType();
2739   }
2740 
2741   if (FromType->isPointerType())
2742     FromType = FromType->getPointeeType();
2743   if (ToType->isPointerType())
2744     ToType = ToType->getPointeeType();
2745 
2746   // Remove references.
2747   FromType = FromType.getNonReferenceType();
2748   ToType = ToType.getNonReferenceType();
2749 
2750   // Don't print extra info for non-specialized template functions.
2751   if (FromType->isInstantiationDependentType() &&
2752       !FromType->getAs<TemplateSpecializationType>()) {
2753     PDiag << ft_default;
2754     return;
2755   }
2756 
2757   // No extra info for same types.
2758   if (Context.hasSameType(FromType, ToType)) {
2759     PDiag << ft_default;
2760     return;
2761   }
2762 
2763   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2764                           *ToFunction = tryGetFunctionProtoType(ToType);
2765 
2766   // Both types need to be function types.
2767   if (!FromFunction || !ToFunction) {
2768     PDiag << ft_default;
2769     return;
2770   }
2771 
2772   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2773     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2774           << FromFunction->getNumParams();
2775     return;
2776   }
2777 
2778   // Handle different parameter types.
2779   unsigned ArgPos;
2780   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2781     PDiag << ft_parameter_mismatch << ArgPos + 1
2782           << ToFunction->getParamType(ArgPos)
2783           << FromFunction->getParamType(ArgPos);
2784     return;
2785   }
2786 
2787   // Handle different return type.
2788   if (!Context.hasSameType(FromFunction->getReturnType(),
2789                            ToFunction->getReturnType())) {
2790     PDiag << ft_return_type << ToFunction->getReturnType()
2791           << FromFunction->getReturnType();
2792     return;
2793   }
2794 
2795   unsigned FromQuals = FromFunction->getTypeQuals(),
2796            ToQuals = ToFunction->getTypeQuals();
2797   if (FromQuals != ToQuals) {
2798     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2799     return;
2800   }
2801 
2802   // Handle exception specification differences on canonical type (in C++17
2803   // onwards).
2804   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2805           ->isNothrow(Context) !=
2806       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2807           ->isNothrow(Context)) {
2808     PDiag << ft_noexcept;
2809     return;
2810   }
2811 
2812   // Unable to find a difference, so add no extra info.
2813   PDiag << ft_default;
2814 }
2815 
2816 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2817 /// for equality of their argument types. Caller has already checked that
2818 /// they have same number of arguments.  If the parameters are different,
2819 /// ArgPos will have the parameter index of the first different parameter.
2820 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2821                                       const FunctionProtoType *NewType,
2822                                       unsigned *ArgPos) {
2823   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2824                                               N = NewType->param_type_begin(),
2825                                               E = OldType->param_type_end();
2826        O && (O != E); ++O, ++N) {
2827     if (!Context.hasSameType(O->getUnqualifiedType(),
2828                              N->getUnqualifiedType())) {
2829       if (ArgPos)
2830         *ArgPos = O - OldType->param_type_begin();
2831       return false;
2832     }
2833   }
2834   return true;
2835 }
2836 
2837 /// CheckPointerConversion - Check the pointer conversion from the
2838 /// expression From to the type ToType. This routine checks for
2839 /// ambiguous or inaccessible derived-to-base pointer
2840 /// conversions for which IsPointerConversion has already returned
2841 /// true. It returns true and produces a diagnostic if there was an
2842 /// error, or returns false otherwise.
2843 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2844                                   CastKind &Kind,
2845                                   CXXCastPath& BasePath,
2846                                   bool IgnoreBaseAccess,
2847                                   bool Diagnose) {
2848   QualType FromType = From->getType();
2849   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2850 
2851   Kind = CK_BitCast;
2852 
2853   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2854       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2855           Expr::NPCK_ZeroExpression) {
2856     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2857       DiagRuntimeBehavior(From->getExprLoc(), From,
2858                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2859                             << ToType << From->getSourceRange());
2860     else if (!isUnevaluatedContext())
2861       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2862         << ToType << From->getSourceRange();
2863   }
2864   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2865     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2866       QualType FromPointeeType = FromPtrType->getPointeeType(),
2867                ToPointeeType   = ToPtrType->getPointeeType();
2868 
2869       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2870           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2871         // We must have a derived-to-base conversion. Check an
2872         // ambiguous or inaccessible conversion.
2873         unsigned InaccessibleID = 0;
2874         unsigned AmbigiousID = 0;
2875         if (Diagnose) {
2876           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2877           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2878         }
2879         if (CheckDerivedToBaseConversion(
2880                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2881                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2882                 &BasePath, IgnoreBaseAccess))
2883           return true;
2884 
2885         // The conversion was successful.
2886         Kind = CK_DerivedToBase;
2887       }
2888 
2889       if (Diagnose && !IsCStyleOrFunctionalCast &&
2890           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2891         assert(getLangOpts().MSVCCompat &&
2892                "this should only be possible with MSVCCompat!");
2893         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2894             << From->getSourceRange();
2895       }
2896     }
2897   } else if (const ObjCObjectPointerType *ToPtrType =
2898                ToType->getAs<ObjCObjectPointerType>()) {
2899     if (const ObjCObjectPointerType *FromPtrType =
2900           FromType->getAs<ObjCObjectPointerType>()) {
2901       // Objective-C++ conversions are always okay.
2902       // FIXME: We should have a different class of conversions for the
2903       // Objective-C++ implicit conversions.
2904       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2905         return false;
2906     } else if (FromType->isBlockPointerType()) {
2907       Kind = CK_BlockPointerToObjCPointerCast;
2908     } else {
2909       Kind = CK_CPointerToObjCPointerCast;
2910     }
2911   } else if (ToType->isBlockPointerType()) {
2912     if (!FromType->isBlockPointerType())
2913       Kind = CK_AnyPointerToBlockPointerCast;
2914   }
2915 
2916   // We shouldn't fall into this case unless it's valid for other
2917   // reasons.
2918   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2919     Kind = CK_NullToPointer;
2920 
2921   return false;
2922 }
2923 
2924 /// IsMemberPointerConversion - Determines whether the conversion of the
2925 /// expression From, which has the (possibly adjusted) type FromType, can be
2926 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2927 /// If so, returns true and places the converted type (that might differ from
2928 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2929 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2930                                      QualType ToType,
2931                                      bool InOverloadResolution,
2932                                      QualType &ConvertedType) {
2933   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2934   if (!ToTypePtr)
2935     return false;
2936 
2937   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2938   if (From->isNullPointerConstant(Context,
2939                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2940                                         : Expr::NPC_ValueDependentIsNull)) {
2941     ConvertedType = ToType;
2942     return true;
2943   }
2944 
2945   // Otherwise, both types have to be member pointers.
2946   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2947   if (!FromTypePtr)
2948     return false;
2949 
2950   // A pointer to member of B can be converted to a pointer to member of D,
2951   // where D is derived from B (C++ 4.11p2).
2952   QualType FromClass(FromTypePtr->getClass(), 0);
2953   QualType ToClass(ToTypePtr->getClass(), 0);
2954 
2955   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2956       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2957     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2958                                                  ToClass.getTypePtr());
2959     return true;
2960   }
2961 
2962   return false;
2963 }
2964 
2965 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2966 /// expression From to the type ToType. This routine checks for ambiguous or
2967 /// virtual or inaccessible base-to-derived member pointer conversions
2968 /// for which IsMemberPointerConversion has already returned true. It returns
2969 /// true and produces a diagnostic if there was an error, or returns false
2970 /// otherwise.
2971 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2972                                         CastKind &Kind,
2973                                         CXXCastPath &BasePath,
2974                                         bool IgnoreBaseAccess) {
2975   QualType FromType = From->getType();
2976   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2977   if (!FromPtrType) {
2978     // This must be a null pointer to member pointer conversion
2979     assert(From->isNullPointerConstant(Context,
2980                                        Expr::NPC_ValueDependentIsNull) &&
2981            "Expr must be null pointer constant!");
2982     Kind = CK_NullToMemberPointer;
2983     return false;
2984   }
2985 
2986   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2987   assert(ToPtrType && "No member pointer cast has a target type "
2988                       "that is not a member pointer.");
2989 
2990   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2991   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2992 
2993   // FIXME: What about dependent types?
2994   assert(FromClass->isRecordType() && "Pointer into non-class.");
2995   assert(ToClass->isRecordType() && "Pointer into non-class.");
2996 
2997   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2998                      /*DetectVirtual=*/true);
2999   bool DerivationOkay =
3000       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3001   assert(DerivationOkay &&
3002          "Should not have been called if derivation isn't OK.");
3003   (void)DerivationOkay;
3004 
3005   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3006                                   getUnqualifiedType())) {
3007     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3008     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3009       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3010     return true;
3011   }
3012 
3013   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3014     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3015       << FromClass << ToClass << QualType(VBase, 0)
3016       << From->getSourceRange();
3017     return true;
3018   }
3019 
3020   if (!IgnoreBaseAccess)
3021     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3022                          Paths.front(),
3023                          diag::err_downcast_from_inaccessible_base);
3024 
3025   // Must be a base to derived member conversion.
3026   BuildBasePathArray(Paths, BasePath);
3027   Kind = CK_BaseToDerivedMemberPointer;
3028   return false;
3029 }
3030 
3031 /// Determine whether the lifetime conversion between the two given
3032 /// qualifiers sets is nontrivial.
3033 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3034                                                Qualifiers ToQuals) {
3035   // Converting anything to const __unsafe_unretained is trivial.
3036   if (ToQuals.hasConst() &&
3037       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3038     return false;
3039 
3040   return true;
3041 }
3042 
3043 /// IsQualificationConversion - Determines whether the conversion from
3044 /// an rvalue of type FromType to ToType is a qualification conversion
3045 /// (C++ 4.4).
3046 ///
3047 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3048 /// when the qualification conversion involves a change in the Objective-C
3049 /// object lifetime.
3050 bool
3051 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3052                                 bool CStyle, bool &ObjCLifetimeConversion) {
3053   FromType = Context.getCanonicalType(FromType);
3054   ToType = Context.getCanonicalType(ToType);
3055   ObjCLifetimeConversion = false;
3056 
3057   // If FromType and ToType are the same type, this is not a
3058   // qualification conversion.
3059   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3060     return false;
3061 
3062   // (C++ 4.4p4):
3063   //   A conversion can add cv-qualifiers at levels other than the first
3064   //   in multi-level pointers, subject to the following rules: [...]
3065   bool PreviousToQualsIncludeConst = true;
3066   bool UnwrappedAnyPointer = false;
3067   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3068     // Within each iteration of the loop, we check the qualifiers to
3069     // determine if this still looks like a qualification
3070     // conversion. Then, if all is well, we unwrap one more level of
3071     // pointers or pointers-to-members and do it all again
3072     // until there are no more pointers or pointers-to-members left to
3073     // unwrap.
3074     UnwrappedAnyPointer = true;
3075 
3076     Qualifiers FromQuals = FromType.getQualifiers();
3077     Qualifiers ToQuals = ToType.getQualifiers();
3078 
3079     // Ignore __unaligned qualifier if this type is void.
3080     if (ToType.getUnqualifiedType()->isVoidType())
3081       FromQuals.removeUnaligned();
3082 
3083     // Objective-C ARC:
3084     //   Check Objective-C lifetime conversions.
3085     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3086         UnwrappedAnyPointer) {
3087       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3088         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3089           ObjCLifetimeConversion = true;
3090         FromQuals.removeObjCLifetime();
3091         ToQuals.removeObjCLifetime();
3092       } else {
3093         // Qualification conversions cannot cast between different
3094         // Objective-C lifetime qualifiers.
3095         return false;
3096       }
3097     }
3098 
3099     // Allow addition/removal of GC attributes but not changing GC attributes.
3100     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3101         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3102       FromQuals.removeObjCGCAttr();
3103       ToQuals.removeObjCGCAttr();
3104     }
3105 
3106     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3107     //      2,j, and similarly for volatile.
3108     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3109       return false;
3110 
3111     //   -- if the cv 1,j and cv 2,j are different, then const is in
3112     //      every cv for 0 < k < j.
3113     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3114         && !PreviousToQualsIncludeConst)
3115       return false;
3116 
3117     // Keep track of whether all prior cv-qualifiers in the "to" type
3118     // include const.
3119     PreviousToQualsIncludeConst
3120       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3121   }
3122 
3123   // We are left with FromType and ToType being the pointee types
3124   // after unwrapping the original FromType and ToType the same number
3125   // of types. If we unwrapped any pointers, and if FromType and
3126   // ToType have the same unqualified type (since we checked
3127   // qualifiers above), then this is a qualification conversion.
3128   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3129 }
3130 
3131 /// \brief - Determine whether this is a conversion from a scalar type to an
3132 /// atomic type.
3133 ///
3134 /// If successful, updates \c SCS's second and third steps in the conversion
3135 /// sequence to finish the conversion.
3136 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3137                                 bool InOverloadResolution,
3138                                 StandardConversionSequence &SCS,
3139                                 bool CStyle) {
3140   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3141   if (!ToAtomic)
3142     return false;
3143 
3144   StandardConversionSequence InnerSCS;
3145   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3146                             InOverloadResolution, InnerSCS,
3147                             CStyle, /*AllowObjCWritebackConversion=*/false))
3148     return false;
3149 
3150   SCS.Second = InnerSCS.Second;
3151   SCS.setToType(1, InnerSCS.getToType(1));
3152   SCS.Third = InnerSCS.Third;
3153   SCS.QualificationIncludesObjCLifetime
3154     = InnerSCS.QualificationIncludesObjCLifetime;
3155   SCS.setToType(2, InnerSCS.getToType(2));
3156   return true;
3157 }
3158 
3159 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3160                                               CXXConstructorDecl *Constructor,
3161                                               QualType Type) {
3162   const FunctionProtoType *CtorType =
3163       Constructor->getType()->getAs<FunctionProtoType>();
3164   if (CtorType->getNumParams() > 0) {
3165     QualType FirstArg = CtorType->getParamType(0);
3166     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3167       return true;
3168   }
3169   return false;
3170 }
3171 
3172 static OverloadingResult
3173 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3174                                        CXXRecordDecl *To,
3175                                        UserDefinedConversionSequence &User,
3176                                        OverloadCandidateSet &CandidateSet,
3177                                        bool AllowExplicit) {
3178   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3179   for (auto *D : S.LookupConstructors(To)) {
3180     auto Info = getConstructorInfo(D);
3181     if (!Info)
3182       continue;
3183 
3184     bool Usable = !Info.Constructor->isInvalidDecl() &&
3185                   S.isInitListConstructor(Info.Constructor) &&
3186                   (AllowExplicit || !Info.Constructor->isExplicit());
3187     if (Usable) {
3188       // If the first argument is (a reference to) the target type,
3189       // suppress conversions.
3190       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3191           S.Context, Info.Constructor, ToType);
3192       if (Info.ConstructorTmpl)
3193         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3194                                        /*ExplicitArgs*/ nullptr, From,
3195                                        CandidateSet, SuppressUserConversions);
3196       else
3197         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3198                                CandidateSet, SuppressUserConversions);
3199     }
3200   }
3201 
3202   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3203 
3204   OverloadCandidateSet::iterator Best;
3205   switch (auto Result =
3206             CandidateSet.BestViableFunction(S, From->getLocStart(),
3207                                             Best)) {
3208   case OR_Deleted:
3209   case OR_Success: {
3210     // Record the standard conversion we used and the conversion function.
3211     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3212     QualType ThisType = Constructor->getThisType(S.Context);
3213     // Initializer lists don't have conversions as such.
3214     User.Before.setAsIdentityConversion();
3215     User.HadMultipleCandidates = HadMultipleCandidates;
3216     User.ConversionFunction = Constructor;
3217     User.FoundConversionFunction = Best->FoundDecl;
3218     User.After.setAsIdentityConversion();
3219     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3220     User.After.setAllToTypes(ToType);
3221     return Result;
3222   }
3223 
3224   case OR_No_Viable_Function:
3225     return OR_No_Viable_Function;
3226   case OR_Ambiguous:
3227     return OR_Ambiguous;
3228   }
3229 
3230   llvm_unreachable("Invalid OverloadResult!");
3231 }
3232 
3233 /// Determines whether there is a user-defined conversion sequence
3234 /// (C++ [over.ics.user]) that converts expression From to the type
3235 /// ToType. If such a conversion exists, User will contain the
3236 /// user-defined conversion sequence that performs such a conversion
3237 /// and this routine will return true. Otherwise, this routine returns
3238 /// false and User is unspecified.
3239 ///
3240 /// \param AllowExplicit  true if the conversion should consider C++0x
3241 /// "explicit" conversion functions as well as non-explicit conversion
3242 /// functions (C++0x [class.conv.fct]p2).
3243 ///
3244 /// \param AllowObjCConversionOnExplicit true if the conversion should
3245 /// allow an extra Objective-C pointer conversion on uses of explicit
3246 /// constructors. Requires \c AllowExplicit to also be set.
3247 static OverloadingResult
3248 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3249                         UserDefinedConversionSequence &User,
3250                         OverloadCandidateSet &CandidateSet,
3251                         bool AllowExplicit,
3252                         bool AllowObjCConversionOnExplicit) {
3253   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3254   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3255 
3256   // Whether we will only visit constructors.
3257   bool ConstructorsOnly = false;
3258 
3259   // If the type we are conversion to is a class type, enumerate its
3260   // constructors.
3261   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3262     // C++ [over.match.ctor]p1:
3263     //   When objects of class type are direct-initialized (8.5), or
3264     //   copy-initialized from an expression of the same or a
3265     //   derived class type (8.5), overload resolution selects the
3266     //   constructor. [...] For copy-initialization, the candidate
3267     //   functions are all the converting constructors (12.3.1) of
3268     //   that class. The argument list is the expression-list within
3269     //   the parentheses of the initializer.
3270     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3271         (From->getType()->getAs<RecordType>() &&
3272          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3273       ConstructorsOnly = true;
3274 
3275     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3276       // We're not going to find any constructors.
3277     } else if (CXXRecordDecl *ToRecordDecl
3278                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3279 
3280       Expr **Args = &From;
3281       unsigned NumArgs = 1;
3282       bool ListInitializing = false;
3283       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3284         // But first, see if there is an init-list-constructor that will work.
3285         OverloadingResult Result = IsInitializerListConstructorConversion(
3286             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3287         if (Result != OR_No_Viable_Function)
3288           return Result;
3289         // Never mind.
3290         CandidateSet.clear(
3291             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3292 
3293         // If we're list-initializing, we pass the individual elements as
3294         // arguments, not the entire list.
3295         Args = InitList->getInits();
3296         NumArgs = InitList->getNumInits();
3297         ListInitializing = true;
3298       }
3299 
3300       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3301         auto Info = getConstructorInfo(D);
3302         if (!Info)
3303           continue;
3304 
3305         bool Usable = !Info.Constructor->isInvalidDecl();
3306         if (ListInitializing)
3307           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3308         else
3309           Usable = Usable &&
3310                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3311         if (Usable) {
3312           bool SuppressUserConversions = !ConstructorsOnly;
3313           if (SuppressUserConversions && ListInitializing) {
3314             SuppressUserConversions = false;
3315             if (NumArgs == 1) {
3316               // If the first argument is (a reference to) the target type,
3317               // suppress conversions.
3318               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3319                   S.Context, Info.Constructor, ToType);
3320             }
3321           }
3322           if (Info.ConstructorTmpl)
3323             S.AddTemplateOverloadCandidate(
3324                 Info.ConstructorTmpl, Info.FoundDecl,
3325                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3326                 CandidateSet, SuppressUserConversions);
3327           else
3328             // Allow one user-defined conversion when user specifies a
3329             // From->ToType conversion via an static cast (c-style, etc).
3330             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3331                                    llvm::makeArrayRef(Args, NumArgs),
3332                                    CandidateSet, SuppressUserConversions);
3333         }
3334       }
3335     }
3336   }
3337 
3338   // Enumerate conversion functions, if we're allowed to.
3339   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3340   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3341     // No conversion functions from incomplete types.
3342   } else if (const RecordType *FromRecordType
3343                                    = From->getType()->getAs<RecordType>()) {
3344     if (CXXRecordDecl *FromRecordDecl
3345          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3346       // Add all of the conversion functions as candidates.
3347       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3348       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3349         DeclAccessPair FoundDecl = I.getPair();
3350         NamedDecl *D = FoundDecl.getDecl();
3351         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3352         if (isa<UsingShadowDecl>(D))
3353           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3354 
3355         CXXConversionDecl *Conv;
3356         FunctionTemplateDecl *ConvTemplate;
3357         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3358           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3359         else
3360           Conv = cast<CXXConversionDecl>(D);
3361 
3362         if (AllowExplicit || !Conv->isExplicit()) {
3363           if (ConvTemplate)
3364             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3365                                              ActingContext, From, ToType,
3366                                              CandidateSet,
3367                                              AllowObjCConversionOnExplicit);
3368           else
3369             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3370                                      From, ToType, CandidateSet,
3371                                      AllowObjCConversionOnExplicit);
3372         }
3373       }
3374     }
3375   }
3376 
3377   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3378 
3379   OverloadCandidateSet::iterator Best;
3380   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3381                                                         Best)) {
3382   case OR_Success:
3383   case OR_Deleted:
3384     // Record the standard conversion we used and the conversion function.
3385     if (CXXConstructorDecl *Constructor
3386           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3387       // C++ [over.ics.user]p1:
3388       //   If the user-defined conversion is specified by a
3389       //   constructor (12.3.1), the initial standard conversion
3390       //   sequence converts the source type to the type required by
3391       //   the argument of the constructor.
3392       //
3393       QualType ThisType = Constructor->getThisType(S.Context);
3394       if (isa<InitListExpr>(From)) {
3395         // Initializer lists don't have conversions as such.
3396         User.Before.setAsIdentityConversion();
3397       } else {
3398         if (Best->Conversions[0].isEllipsis())
3399           User.EllipsisConversion = true;
3400         else {
3401           User.Before = Best->Conversions[0].Standard;
3402           User.EllipsisConversion = false;
3403         }
3404       }
3405       User.HadMultipleCandidates = HadMultipleCandidates;
3406       User.ConversionFunction = Constructor;
3407       User.FoundConversionFunction = Best->FoundDecl;
3408       User.After.setAsIdentityConversion();
3409       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3410       User.After.setAllToTypes(ToType);
3411       return Result;
3412     }
3413     if (CXXConversionDecl *Conversion
3414                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3415       // C++ [over.ics.user]p1:
3416       //
3417       //   [...] If the user-defined conversion is specified by a
3418       //   conversion function (12.3.2), the initial standard
3419       //   conversion sequence converts the source type to the
3420       //   implicit object parameter of the conversion function.
3421       User.Before = Best->Conversions[0].Standard;
3422       User.HadMultipleCandidates = HadMultipleCandidates;
3423       User.ConversionFunction = Conversion;
3424       User.FoundConversionFunction = Best->FoundDecl;
3425       User.EllipsisConversion = false;
3426 
3427       // C++ [over.ics.user]p2:
3428       //   The second standard conversion sequence converts the
3429       //   result of the user-defined conversion to the target type
3430       //   for the sequence. Since an implicit conversion sequence
3431       //   is an initialization, the special rules for
3432       //   initialization by user-defined conversion apply when
3433       //   selecting the best user-defined conversion for a
3434       //   user-defined conversion sequence (see 13.3.3 and
3435       //   13.3.3.1).
3436       User.After = Best->FinalConversion;
3437       return Result;
3438     }
3439     llvm_unreachable("Not a constructor or conversion function?");
3440 
3441   case OR_No_Viable_Function:
3442     return OR_No_Viable_Function;
3443 
3444   case OR_Ambiguous:
3445     return OR_Ambiguous;
3446   }
3447 
3448   llvm_unreachable("Invalid OverloadResult!");
3449 }
3450 
3451 bool
3452 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3453   ImplicitConversionSequence ICS;
3454   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3455                                     OverloadCandidateSet::CSK_Normal);
3456   OverloadingResult OvResult =
3457     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3458                             CandidateSet, false, false);
3459   if (OvResult == OR_Ambiguous)
3460     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3461         << From->getType() << ToType << From->getSourceRange();
3462   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3463     if (!RequireCompleteType(From->getLocStart(), ToType,
3464                              diag::err_typecheck_nonviable_condition_incomplete,
3465                              From->getType(), From->getSourceRange()))
3466       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3467           << false << From->getType() << From->getSourceRange() << ToType;
3468   } else
3469     return false;
3470   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3471   return true;
3472 }
3473 
3474 /// \brief Compare the user-defined conversion functions or constructors
3475 /// of two user-defined conversion sequences to determine whether any ordering
3476 /// is possible.
3477 static ImplicitConversionSequence::CompareKind
3478 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3479                            FunctionDecl *Function2) {
3480   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3481     return ImplicitConversionSequence::Indistinguishable;
3482 
3483   // Objective-C++:
3484   //   If both conversion functions are implicitly-declared conversions from
3485   //   a lambda closure type to a function pointer and a block pointer,
3486   //   respectively, always prefer the conversion to a function pointer,
3487   //   because the function pointer is more lightweight and is more likely
3488   //   to keep code working.
3489   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3490   if (!Conv1)
3491     return ImplicitConversionSequence::Indistinguishable;
3492 
3493   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3494   if (!Conv2)
3495     return ImplicitConversionSequence::Indistinguishable;
3496 
3497   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3498     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3499     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3500     if (Block1 != Block2)
3501       return Block1 ? ImplicitConversionSequence::Worse
3502                     : ImplicitConversionSequence::Better;
3503   }
3504 
3505   return ImplicitConversionSequence::Indistinguishable;
3506 }
3507 
3508 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3509     const ImplicitConversionSequence &ICS) {
3510   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3511          (ICS.isUserDefined() &&
3512           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3513 }
3514 
3515 /// CompareImplicitConversionSequences - Compare two implicit
3516 /// conversion sequences to determine whether one is better than the
3517 /// other or if they are indistinguishable (C++ 13.3.3.2).
3518 static ImplicitConversionSequence::CompareKind
3519 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3520                                    const ImplicitConversionSequence& ICS1,
3521                                    const ImplicitConversionSequence& ICS2)
3522 {
3523   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3524   // conversion sequences (as defined in 13.3.3.1)
3525   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3526   //      conversion sequence than a user-defined conversion sequence or
3527   //      an ellipsis conversion sequence, and
3528   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3529   //      conversion sequence than an ellipsis conversion sequence
3530   //      (13.3.3.1.3).
3531   //
3532   // C++0x [over.best.ics]p10:
3533   //   For the purpose of ranking implicit conversion sequences as
3534   //   described in 13.3.3.2, the ambiguous conversion sequence is
3535   //   treated as a user-defined sequence that is indistinguishable
3536   //   from any other user-defined conversion sequence.
3537 
3538   // String literal to 'char *' conversion has been deprecated in C++03. It has
3539   // been removed from C++11. We still accept this conversion, if it happens at
3540   // the best viable function. Otherwise, this conversion is considered worse
3541   // than ellipsis conversion. Consider this as an extension; this is not in the
3542   // standard. For example:
3543   //
3544   // int &f(...);    // #1
3545   // void f(char*);  // #2
3546   // void g() { int &r = f("foo"); }
3547   //
3548   // In C++03, we pick #2 as the best viable function.
3549   // In C++11, we pick #1 as the best viable function, because ellipsis
3550   // conversion is better than string-literal to char* conversion (since there
3551   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3552   // convert arguments, #2 would be the best viable function in C++11.
3553   // If the best viable function has this conversion, a warning will be issued
3554   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3555 
3556   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3557       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3558       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3559     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3560                ? ImplicitConversionSequence::Worse
3561                : ImplicitConversionSequence::Better;
3562 
3563   if (ICS1.getKindRank() < ICS2.getKindRank())
3564     return ImplicitConversionSequence::Better;
3565   if (ICS2.getKindRank() < ICS1.getKindRank())
3566     return ImplicitConversionSequence::Worse;
3567 
3568   // The following checks require both conversion sequences to be of
3569   // the same kind.
3570   if (ICS1.getKind() != ICS2.getKind())
3571     return ImplicitConversionSequence::Indistinguishable;
3572 
3573   ImplicitConversionSequence::CompareKind Result =
3574       ImplicitConversionSequence::Indistinguishable;
3575 
3576   // Two implicit conversion sequences of the same form are
3577   // indistinguishable conversion sequences unless one of the
3578   // following rules apply: (C++ 13.3.3.2p3):
3579 
3580   // List-initialization sequence L1 is a better conversion sequence than
3581   // list-initialization sequence L2 if:
3582   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3583   //   if not that,
3584   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3585   //   and N1 is smaller than N2.,
3586   // even if one of the other rules in this paragraph would otherwise apply.
3587   if (!ICS1.isBad()) {
3588     if (ICS1.isStdInitializerListElement() &&
3589         !ICS2.isStdInitializerListElement())
3590       return ImplicitConversionSequence::Better;
3591     if (!ICS1.isStdInitializerListElement() &&
3592         ICS2.isStdInitializerListElement())
3593       return ImplicitConversionSequence::Worse;
3594   }
3595 
3596   if (ICS1.isStandard())
3597     // Standard conversion sequence S1 is a better conversion sequence than
3598     // standard conversion sequence S2 if [...]
3599     Result = CompareStandardConversionSequences(S, Loc,
3600                                                 ICS1.Standard, ICS2.Standard);
3601   else if (ICS1.isUserDefined()) {
3602     // User-defined conversion sequence U1 is a better conversion
3603     // sequence than another user-defined conversion sequence U2 if
3604     // they contain the same user-defined conversion function or
3605     // constructor and if the second standard conversion sequence of
3606     // U1 is better than the second standard conversion sequence of
3607     // U2 (C++ 13.3.3.2p3).
3608     if (ICS1.UserDefined.ConversionFunction ==
3609           ICS2.UserDefined.ConversionFunction)
3610       Result = CompareStandardConversionSequences(S, Loc,
3611                                                   ICS1.UserDefined.After,
3612                                                   ICS2.UserDefined.After);
3613     else
3614       Result = compareConversionFunctions(S,
3615                                           ICS1.UserDefined.ConversionFunction,
3616                                           ICS2.UserDefined.ConversionFunction);
3617   }
3618 
3619   return Result;
3620 }
3621 
3622 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3623   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3624     Qualifiers Quals;
3625     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3626     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3627   }
3628 
3629   return Context.hasSameUnqualifiedType(T1, T2);
3630 }
3631 
3632 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3633 // determine if one is a proper subset of the other.
3634 static ImplicitConversionSequence::CompareKind
3635 compareStandardConversionSubsets(ASTContext &Context,
3636                                  const StandardConversionSequence& SCS1,
3637                                  const StandardConversionSequence& SCS2) {
3638   ImplicitConversionSequence::CompareKind Result
3639     = ImplicitConversionSequence::Indistinguishable;
3640 
3641   // the identity conversion sequence is considered to be a subsequence of
3642   // any non-identity conversion sequence
3643   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3644     return ImplicitConversionSequence::Better;
3645   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3646     return ImplicitConversionSequence::Worse;
3647 
3648   if (SCS1.Second != SCS2.Second) {
3649     if (SCS1.Second == ICK_Identity)
3650       Result = ImplicitConversionSequence::Better;
3651     else if (SCS2.Second == ICK_Identity)
3652       Result = ImplicitConversionSequence::Worse;
3653     else
3654       return ImplicitConversionSequence::Indistinguishable;
3655   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3656     return ImplicitConversionSequence::Indistinguishable;
3657 
3658   if (SCS1.Third == SCS2.Third) {
3659     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3660                              : ImplicitConversionSequence::Indistinguishable;
3661   }
3662 
3663   if (SCS1.Third == ICK_Identity)
3664     return Result == ImplicitConversionSequence::Worse
3665              ? ImplicitConversionSequence::Indistinguishable
3666              : ImplicitConversionSequence::Better;
3667 
3668   if (SCS2.Third == ICK_Identity)
3669     return Result == ImplicitConversionSequence::Better
3670              ? ImplicitConversionSequence::Indistinguishable
3671              : ImplicitConversionSequence::Worse;
3672 
3673   return ImplicitConversionSequence::Indistinguishable;
3674 }
3675 
3676 /// \brief Determine whether one of the given reference bindings is better
3677 /// than the other based on what kind of bindings they are.
3678 static bool
3679 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3680                              const StandardConversionSequence &SCS2) {
3681   // C++0x [over.ics.rank]p3b4:
3682   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3683   //      implicit object parameter of a non-static member function declared
3684   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3685   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3686   //      lvalue reference to a function lvalue and S2 binds an rvalue
3687   //      reference*.
3688   //
3689   // FIXME: Rvalue references. We're going rogue with the above edits,
3690   // because the semantics in the current C++0x working paper (N3225 at the
3691   // time of this writing) break the standard definition of std::forward
3692   // and std::reference_wrapper when dealing with references to functions.
3693   // Proposed wording changes submitted to CWG for consideration.
3694   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3695       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3696     return false;
3697 
3698   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3699           SCS2.IsLvalueReference) ||
3700          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3701           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3702 }
3703 
3704 /// CompareStandardConversionSequences - Compare two standard
3705 /// conversion sequences to determine whether one is better than the
3706 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3707 static ImplicitConversionSequence::CompareKind
3708 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3709                                    const StandardConversionSequence& SCS1,
3710                                    const StandardConversionSequence& SCS2)
3711 {
3712   // Standard conversion sequence S1 is a better conversion sequence
3713   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3714 
3715   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3716   //     sequences in the canonical form defined by 13.3.3.1.1,
3717   //     excluding any Lvalue Transformation; the identity conversion
3718   //     sequence is considered to be a subsequence of any
3719   //     non-identity conversion sequence) or, if not that,
3720   if (ImplicitConversionSequence::CompareKind CK
3721         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3722     return CK;
3723 
3724   //  -- the rank of S1 is better than the rank of S2 (by the rules
3725   //     defined below), or, if not that,
3726   ImplicitConversionRank Rank1 = SCS1.getRank();
3727   ImplicitConversionRank Rank2 = SCS2.getRank();
3728   if (Rank1 < Rank2)
3729     return ImplicitConversionSequence::Better;
3730   else if (Rank2 < Rank1)
3731     return ImplicitConversionSequence::Worse;
3732 
3733   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3734   // are indistinguishable unless one of the following rules
3735   // applies:
3736 
3737   //   A conversion that is not a conversion of a pointer, or
3738   //   pointer to member, to bool is better than another conversion
3739   //   that is such a conversion.
3740   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3741     return SCS2.isPointerConversionToBool()
3742              ? ImplicitConversionSequence::Better
3743              : ImplicitConversionSequence::Worse;
3744 
3745   // C++ [over.ics.rank]p4b2:
3746   //
3747   //   If class B is derived directly or indirectly from class A,
3748   //   conversion of B* to A* is better than conversion of B* to
3749   //   void*, and conversion of A* to void* is better than conversion
3750   //   of B* to void*.
3751   bool SCS1ConvertsToVoid
3752     = SCS1.isPointerConversionToVoidPointer(S.Context);
3753   bool SCS2ConvertsToVoid
3754     = SCS2.isPointerConversionToVoidPointer(S.Context);
3755   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3756     // Exactly one of the conversion sequences is a conversion to
3757     // a void pointer; it's the worse conversion.
3758     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3759                               : ImplicitConversionSequence::Worse;
3760   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3761     // Neither conversion sequence converts to a void pointer; compare
3762     // their derived-to-base conversions.
3763     if (ImplicitConversionSequence::CompareKind DerivedCK
3764           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3765       return DerivedCK;
3766   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3767              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3768     // Both conversion sequences are conversions to void
3769     // pointers. Compare the source types to determine if there's an
3770     // inheritance relationship in their sources.
3771     QualType FromType1 = SCS1.getFromType();
3772     QualType FromType2 = SCS2.getFromType();
3773 
3774     // Adjust the types we're converting from via the array-to-pointer
3775     // conversion, if we need to.
3776     if (SCS1.First == ICK_Array_To_Pointer)
3777       FromType1 = S.Context.getArrayDecayedType(FromType1);
3778     if (SCS2.First == ICK_Array_To_Pointer)
3779       FromType2 = S.Context.getArrayDecayedType(FromType2);
3780 
3781     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3782     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3783 
3784     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3785       return ImplicitConversionSequence::Better;
3786     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3787       return ImplicitConversionSequence::Worse;
3788 
3789     // Objective-C++: If one interface is more specific than the
3790     // other, it is the better one.
3791     const ObjCObjectPointerType* FromObjCPtr1
3792       = FromType1->getAs<ObjCObjectPointerType>();
3793     const ObjCObjectPointerType* FromObjCPtr2
3794       = FromType2->getAs<ObjCObjectPointerType>();
3795     if (FromObjCPtr1 && FromObjCPtr2) {
3796       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3797                                                           FromObjCPtr2);
3798       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3799                                                            FromObjCPtr1);
3800       if (AssignLeft != AssignRight) {
3801         return AssignLeft? ImplicitConversionSequence::Better
3802                          : ImplicitConversionSequence::Worse;
3803       }
3804     }
3805   }
3806 
3807   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3808   // bullet 3).
3809   if (ImplicitConversionSequence::CompareKind QualCK
3810         = CompareQualificationConversions(S, SCS1, SCS2))
3811     return QualCK;
3812 
3813   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3814     // Check for a better reference binding based on the kind of bindings.
3815     if (isBetterReferenceBindingKind(SCS1, SCS2))
3816       return ImplicitConversionSequence::Better;
3817     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3818       return ImplicitConversionSequence::Worse;
3819 
3820     // C++ [over.ics.rank]p3b4:
3821     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3822     //      which the references refer are the same type except for
3823     //      top-level cv-qualifiers, and the type to which the reference
3824     //      initialized by S2 refers is more cv-qualified than the type
3825     //      to which the reference initialized by S1 refers.
3826     QualType T1 = SCS1.getToType(2);
3827     QualType T2 = SCS2.getToType(2);
3828     T1 = S.Context.getCanonicalType(T1);
3829     T2 = S.Context.getCanonicalType(T2);
3830     Qualifiers T1Quals, T2Quals;
3831     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3832     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3833     if (UnqualT1 == UnqualT2) {
3834       // Objective-C++ ARC: If the references refer to objects with different
3835       // lifetimes, prefer bindings that don't change lifetime.
3836       if (SCS1.ObjCLifetimeConversionBinding !=
3837                                           SCS2.ObjCLifetimeConversionBinding) {
3838         return SCS1.ObjCLifetimeConversionBinding
3839                                            ? ImplicitConversionSequence::Worse
3840                                            : ImplicitConversionSequence::Better;
3841       }
3842 
3843       // If the type is an array type, promote the element qualifiers to the
3844       // type for comparison.
3845       if (isa<ArrayType>(T1) && T1Quals)
3846         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3847       if (isa<ArrayType>(T2) && T2Quals)
3848         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3849       if (T2.isMoreQualifiedThan(T1))
3850         return ImplicitConversionSequence::Better;
3851       else if (T1.isMoreQualifiedThan(T2))
3852         return ImplicitConversionSequence::Worse;
3853     }
3854   }
3855 
3856   // In Microsoft mode, prefer an integral conversion to a
3857   // floating-to-integral conversion if the integral conversion
3858   // is between types of the same size.
3859   // For example:
3860   // void f(float);
3861   // void f(int);
3862   // int main {
3863   //    long a;
3864   //    f(a);
3865   // }
3866   // Here, MSVC will call f(int) instead of generating a compile error
3867   // as clang will do in standard mode.
3868   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3869       SCS2.Second == ICK_Floating_Integral &&
3870       S.Context.getTypeSize(SCS1.getFromType()) ==
3871           S.Context.getTypeSize(SCS1.getToType(2)))
3872     return ImplicitConversionSequence::Better;
3873 
3874   return ImplicitConversionSequence::Indistinguishable;
3875 }
3876 
3877 /// CompareQualificationConversions - Compares two standard conversion
3878 /// sequences to determine whether they can be ranked based on their
3879 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3880 static ImplicitConversionSequence::CompareKind
3881 CompareQualificationConversions(Sema &S,
3882                                 const StandardConversionSequence& SCS1,
3883                                 const StandardConversionSequence& SCS2) {
3884   // C++ 13.3.3.2p3:
3885   //  -- S1 and S2 differ only in their qualification conversion and
3886   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3887   //     cv-qualification signature of type T1 is a proper subset of
3888   //     the cv-qualification signature of type T2, and S1 is not the
3889   //     deprecated string literal array-to-pointer conversion (4.2).
3890   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3891       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3892     return ImplicitConversionSequence::Indistinguishable;
3893 
3894   // FIXME: the example in the standard doesn't use a qualification
3895   // conversion (!)
3896   QualType T1 = SCS1.getToType(2);
3897   QualType T2 = SCS2.getToType(2);
3898   T1 = S.Context.getCanonicalType(T1);
3899   T2 = S.Context.getCanonicalType(T2);
3900   Qualifiers T1Quals, T2Quals;
3901   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3902   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3903 
3904   // If the types are the same, we won't learn anything by unwrapped
3905   // them.
3906   if (UnqualT1 == UnqualT2)
3907     return ImplicitConversionSequence::Indistinguishable;
3908 
3909   // If the type is an array type, promote the element qualifiers to the type
3910   // for comparison.
3911   if (isa<ArrayType>(T1) && T1Quals)
3912     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3913   if (isa<ArrayType>(T2) && T2Quals)
3914     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3915 
3916   ImplicitConversionSequence::CompareKind Result
3917     = ImplicitConversionSequence::Indistinguishable;
3918 
3919   // Objective-C++ ARC:
3920   //   Prefer qualification conversions not involving a change in lifetime
3921   //   to qualification conversions that do not change lifetime.
3922   if (SCS1.QualificationIncludesObjCLifetime !=
3923                                       SCS2.QualificationIncludesObjCLifetime) {
3924     Result = SCS1.QualificationIncludesObjCLifetime
3925                ? ImplicitConversionSequence::Worse
3926                : ImplicitConversionSequence::Better;
3927   }
3928 
3929   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3930     // Within each iteration of the loop, we check the qualifiers to
3931     // determine if this still looks like a qualification
3932     // conversion. Then, if all is well, we unwrap one more level of
3933     // pointers or pointers-to-members and do it all again
3934     // until there are no more pointers or pointers-to-members left
3935     // to unwrap. This essentially mimics what
3936     // IsQualificationConversion does, but here we're checking for a
3937     // strict subset of qualifiers.
3938     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3939       // The qualifiers are the same, so this doesn't tell us anything
3940       // about how the sequences rank.
3941       ;
3942     else if (T2.isMoreQualifiedThan(T1)) {
3943       // T1 has fewer qualifiers, so it could be the better sequence.
3944       if (Result == ImplicitConversionSequence::Worse)
3945         // Neither has qualifiers that are a subset of the other's
3946         // qualifiers.
3947         return ImplicitConversionSequence::Indistinguishable;
3948 
3949       Result = ImplicitConversionSequence::Better;
3950     } else if (T1.isMoreQualifiedThan(T2)) {
3951       // T2 has fewer qualifiers, so it could be the better sequence.
3952       if (Result == ImplicitConversionSequence::Better)
3953         // Neither has qualifiers that are a subset of the other's
3954         // qualifiers.
3955         return ImplicitConversionSequence::Indistinguishable;
3956 
3957       Result = ImplicitConversionSequence::Worse;
3958     } else {
3959       // Qualifiers are disjoint.
3960       return ImplicitConversionSequence::Indistinguishable;
3961     }
3962 
3963     // If the types after this point are equivalent, we're done.
3964     if (S.Context.hasSameUnqualifiedType(T1, T2))
3965       break;
3966   }
3967 
3968   // Check that the winning standard conversion sequence isn't using
3969   // the deprecated string literal array to pointer conversion.
3970   switch (Result) {
3971   case ImplicitConversionSequence::Better:
3972     if (SCS1.DeprecatedStringLiteralToCharPtr)
3973       Result = ImplicitConversionSequence::Indistinguishable;
3974     break;
3975 
3976   case ImplicitConversionSequence::Indistinguishable:
3977     break;
3978 
3979   case ImplicitConversionSequence::Worse:
3980     if (SCS2.DeprecatedStringLiteralToCharPtr)
3981       Result = ImplicitConversionSequence::Indistinguishable;
3982     break;
3983   }
3984 
3985   return Result;
3986 }
3987 
3988 /// CompareDerivedToBaseConversions - Compares two standard conversion
3989 /// sequences to determine whether they can be ranked based on their
3990 /// various kinds of derived-to-base conversions (C++
3991 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3992 /// conversions between Objective-C interface types.
3993 static ImplicitConversionSequence::CompareKind
3994 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3995                                 const StandardConversionSequence& SCS1,
3996                                 const StandardConversionSequence& SCS2) {
3997   QualType FromType1 = SCS1.getFromType();
3998   QualType ToType1 = SCS1.getToType(1);
3999   QualType FromType2 = SCS2.getFromType();
4000   QualType ToType2 = SCS2.getToType(1);
4001 
4002   // Adjust the types we're converting from via the array-to-pointer
4003   // conversion, if we need to.
4004   if (SCS1.First == ICK_Array_To_Pointer)
4005     FromType1 = S.Context.getArrayDecayedType(FromType1);
4006   if (SCS2.First == ICK_Array_To_Pointer)
4007     FromType2 = S.Context.getArrayDecayedType(FromType2);
4008 
4009   // Canonicalize all of the types.
4010   FromType1 = S.Context.getCanonicalType(FromType1);
4011   ToType1 = S.Context.getCanonicalType(ToType1);
4012   FromType2 = S.Context.getCanonicalType(FromType2);
4013   ToType2 = S.Context.getCanonicalType(ToType2);
4014 
4015   // C++ [over.ics.rank]p4b3:
4016   //
4017   //   If class B is derived directly or indirectly from class A and
4018   //   class C is derived directly or indirectly from B,
4019   //
4020   // Compare based on pointer conversions.
4021   if (SCS1.Second == ICK_Pointer_Conversion &&
4022       SCS2.Second == ICK_Pointer_Conversion &&
4023       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4024       FromType1->isPointerType() && FromType2->isPointerType() &&
4025       ToType1->isPointerType() && ToType2->isPointerType()) {
4026     QualType FromPointee1
4027       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4028     QualType ToPointee1
4029       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4030     QualType FromPointee2
4031       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4032     QualType ToPointee2
4033       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4034 
4035     //   -- conversion of C* to B* is better than conversion of C* to A*,
4036     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4037       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4038         return ImplicitConversionSequence::Better;
4039       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4040         return ImplicitConversionSequence::Worse;
4041     }
4042 
4043     //   -- conversion of B* to A* is better than conversion of C* to A*,
4044     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4045       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4046         return ImplicitConversionSequence::Better;
4047       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4048         return ImplicitConversionSequence::Worse;
4049     }
4050   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4051              SCS2.Second == ICK_Pointer_Conversion) {
4052     const ObjCObjectPointerType *FromPtr1
4053       = FromType1->getAs<ObjCObjectPointerType>();
4054     const ObjCObjectPointerType *FromPtr2
4055       = FromType2->getAs<ObjCObjectPointerType>();
4056     const ObjCObjectPointerType *ToPtr1
4057       = ToType1->getAs<ObjCObjectPointerType>();
4058     const ObjCObjectPointerType *ToPtr2
4059       = ToType2->getAs<ObjCObjectPointerType>();
4060 
4061     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4062       // Apply the same conversion ranking rules for Objective-C pointer types
4063       // that we do for C++ pointers to class types. However, we employ the
4064       // Objective-C pseudo-subtyping relationship used for assignment of
4065       // Objective-C pointer types.
4066       bool FromAssignLeft
4067         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4068       bool FromAssignRight
4069         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4070       bool ToAssignLeft
4071         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4072       bool ToAssignRight
4073         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4074 
4075       // A conversion to an a non-id object pointer type or qualified 'id'
4076       // type is better than a conversion to 'id'.
4077       if (ToPtr1->isObjCIdType() &&
4078           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4079         return ImplicitConversionSequence::Worse;
4080       if (ToPtr2->isObjCIdType() &&
4081           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4082         return ImplicitConversionSequence::Better;
4083 
4084       // A conversion to a non-id object pointer type is better than a
4085       // conversion to a qualified 'id' type
4086       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4087         return ImplicitConversionSequence::Worse;
4088       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4089         return ImplicitConversionSequence::Better;
4090 
4091       // A conversion to an a non-Class object pointer type or qualified 'Class'
4092       // type is better than a conversion to 'Class'.
4093       if (ToPtr1->isObjCClassType() &&
4094           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4095         return ImplicitConversionSequence::Worse;
4096       if (ToPtr2->isObjCClassType() &&
4097           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4098         return ImplicitConversionSequence::Better;
4099 
4100       // A conversion to a non-Class object pointer type is better than a
4101       // conversion to a qualified 'Class' type.
4102       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4103         return ImplicitConversionSequence::Worse;
4104       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4105         return ImplicitConversionSequence::Better;
4106 
4107       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4108       if (S.Context.hasSameType(FromType1, FromType2) &&
4109           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4110           (ToAssignLeft != ToAssignRight)) {
4111         if (FromPtr1->isSpecialized()) {
4112           // "conversion of B<A> * to B * is better than conversion of B * to
4113           // C *.
4114           bool IsFirstSame =
4115               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4116           bool IsSecondSame =
4117               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4118           if (IsFirstSame) {
4119             if (!IsSecondSame)
4120               return ImplicitConversionSequence::Better;
4121           } else if (IsSecondSame)
4122             return ImplicitConversionSequence::Worse;
4123         }
4124         return ToAssignLeft? ImplicitConversionSequence::Worse
4125                            : ImplicitConversionSequence::Better;
4126       }
4127 
4128       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4129       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4130           (FromAssignLeft != FromAssignRight))
4131         return FromAssignLeft? ImplicitConversionSequence::Better
4132         : ImplicitConversionSequence::Worse;
4133     }
4134   }
4135 
4136   // Ranking of member-pointer types.
4137   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4138       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4139       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4140     const MemberPointerType * FromMemPointer1 =
4141                                         FromType1->getAs<MemberPointerType>();
4142     const MemberPointerType * ToMemPointer1 =
4143                                           ToType1->getAs<MemberPointerType>();
4144     const MemberPointerType * FromMemPointer2 =
4145                                           FromType2->getAs<MemberPointerType>();
4146     const MemberPointerType * ToMemPointer2 =
4147                                           ToType2->getAs<MemberPointerType>();
4148     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4149     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4150     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4151     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4152     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4153     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4154     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4155     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4156     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4157     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4158       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4159         return ImplicitConversionSequence::Worse;
4160       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4161         return ImplicitConversionSequence::Better;
4162     }
4163     // conversion of B::* to C::* is better than conversion of A::* to C::*
4164     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4165       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4166         return ImplicitConversionSequence::Better;
4167       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4168         return ImplicitConversionSequence::Worse;
4169     }
4170   }
4171 
4172   if (SCS1.Second == ICK_Derived_To_Base) {
4173     //   -- conversion of C to B is better than conversion of C to A,
4174     //   -- binding of an expression of type C to a reference of type
4175     //      B& is better than binding an expression of type C to a
4176     //      reference of type A&,
4177     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4178         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4179       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4180         return ImplicitConversionSequence::Better;
4181       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4182         return ImplicitConversionSequence::Worse;
4183     }
4184 
4185     //   -- conversion of B to A is better than conversion of C to A.
4186     //   -- binding of an expression of type B to a reference of type
4187     //      A& is better than binding an expression of type C to a
4188     //      reference of type A&,
4189     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4190         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4191       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4192         return ImplicitConversionSequence::Better;
4193       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4194         return ImplicitConversionSequence::Worse;
4195     }
4196   }
4197 
4198   return ImplicitConversionSequence::Indistinguishable;
4199 }
4200 
4201 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4202 /// C++ class.
4203 static bool isTypeValid(QualType T) {
4204   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4205     return !Record->isInvalidDecl();
4206 
4207   return true;
4208 }
4209 
4210 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4211 /// determine whether they are reference-related,
4212 /// reference-compatible, reference-compatible with added
4213 /// qualification, or incompatible, for use in C++ initialization by
4214 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4215 /// type, and the first type (T1) is the pointee type of the reference
4216 /// type being initialized.
4217 Sema::ReferenceCompareResult
4218 Sema::CompareReferenceRelationship(SourceLocation Loc,
4219                                    QualType OrigT1, QualType OrigT2,
4220                                    bool &DerivedToBase,
4221                                    bool &ObjCConversion,
4222                                    bool &ObjCLifetimeConversion) {
4223   assert(!OrigT1->isReferenceType() &&
4224     "T1 must be the pointee type of the reference type");
4225   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4226 
4227   QualType T1 = Context.getCanonicalType(OrigT1);
4228   QualType T2 = Context.getCanonicalType(OrigT2);
4229   Qualifiers T1Quals, T2Quals;
4230   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4231   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4232 
4233   // C++ [dcl.init.ref]p4:
4234   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4235   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4236   //   T1 is a base class of T2.
4237   DerivedToBase = false;
4238   ObjCConversion = false;
4239   ObjCLifetimeConversion = false;
4240   QualType ConvertedT2;
4241   if (UnqualT1 == UnqualT2) {
4242     // Nothing to do.
4243   } else if (isCompleteType(Loc, OrigT2) &&
4244              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4245              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4246     DerivedToBase = true;
4247   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4248            UnqualT2->isObjCObjectOrInterfaceType() &&
4249            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4250     ObjCConversion = true;
4251   else if (UnqualT2->isFunctionType() &&
4252            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4253     // C++1z [dcl.init.ref]p4:
4254     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4255     //   function" and T1 is "function"
4256     //
4257     // We extend this to also apply to 'noreturn', so allow any function
4258     // conversion between function types.
4259     return Ref_Compatible;
4260   else
4261     return Ref_Incompatible;
4262 
4263   // At this point, we know that T1 and T2 are reference-related (at
4264   // least).
4265 
4266   // If the type is an array type, promote the element qualifiers to the type
4267   // for comparison.
4268   if (isa<ArrayType>(T1) && T1Quals)
4269     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4270   if (isa<ArrayType>(T2) && T2Quals)
4271     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4272 
4273   // C++ [dcl.init.ref]p4:
4274   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4275   //   reference-related to T2 and cv1 is the same cv-qualification
4276   //   as, or greater cv-qualification than, cv2. For purposes of
4277   //   overload resolution, cases for which cv1 is greater
4278   //   cv-qualification than cv2 are identified as
4279   //   reference-compatible with added qualification (see 13.3.3.2).
4280   //
4281   // Note that we also require equivalence of Objective-C GC and address-space
4282   // qualifiers when performing these computations, so that e.g., an int in
4283   // address space 1 is not reference-compatible with an int in address
4284   // space 2.
4285   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4286       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4287     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4288       ObjCLifetimeConversion = true;
4289 
4290     T1Quals.removeObjCLifetime();
4291     T2Quals.removeObjCLifetime();
4292   }
4293 
4294   // MS compiler ignores __unaligned qualifier for references; do the same.
4295   T1Quals.removeUnaligned();
4296   T2Quals.removeUnaligned();
4297 
4298   if (T1Quals.compatiblyIncludes(T2Quals))
4299     return Ref_Compatible;
4300   else
4301     return Ref_Related;
4302 }
4303 
4304 /// \brief Look for a user-defined conversion to a value reference-compatible
4305 ///        with DeclType. Return true if something definite is found.
4306 static bool
4307 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4308                          QualType DeclType, SourceLocation DeclLoc,
4309                          Expr *Init, QualType T2, bool AllowRvalues,
4310                          bool AllowExplicit) {
4311   assert(T2->isRecordType() && "Can only find conversions of record types.");
4312   CXXRecordDecl *T2RecordDecl
4313     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4314 
4315   OverloadCandidateSet CandidateSet(
4316       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4317   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4318   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4319     NamedDecl *D = *I;
4320     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4321     if (isa<UsingShadowDecl>(D))
4322       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4323 
4324     FunctionTemplateDecl *ConvTemplate
4325       = dyn_cast<FunctionTemplateDecl>(D);
4326     CXXConversionDecl *Conv;
4327     if (ConvTemplate)
4328       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4329     else
4330       Conv = cast<CXXConversionDecl>(D);
4331 
4332     // If this is an explicit conversion, and we're not allowed to consider
4333     // explicit conversions, skip it.
4334     if (!AllowExplicit && Conv->isExplicit())
4335       continue;
4336 
4337     if (AllowRvalues) {
4338       bool DerivedToBase = false;
4339       bool ObjCConversion = false;
4340       bool ObjCLifetimeConversion = false;
4341 
4342       // If we are initializing an rvalue reference, don't permit conversion
4343       // functions that return lvalues.
4344       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4345         const ReferenceType *RefType
4346           = Conv->getConversionType()->getAs<LValueReferenceType>();
4347         if (RefType && !RefType->getPointeeType()->isFunctionType())
4348           continue;
4349       }
4350 
4351       if (!ConvTemplate &&
4352           S.CompareReferenceRelationship(
4353             DeclLoc,
4354             Conv->getConversionType().getNonReferenceType()
4355               .getUnqualifiedType(),
4356             DeclType.getNonReferenceType().getUnqualifiedType(),
4357             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4358           Sema::Ref_Incompatible)
4359         continue;
4360     } else {
4361       // If the conversion function doesn't return a reference type,
4362       // it can't be considered for this conversion. An rvalue reference
4363       // is only acceptable if its referencee is a function type.
4364 
4365       const ReferenceType *RefType =
4366         Conv->getConversionType()->getAs<ReferenceType>();
4367       if (!RefType ||
4368           (!RefType->isLValueReferenceType() &&
4369            !RefType->getPointeeType()->isFunctionType()))
4370         continue;
4371     }
4372 
4373     if (ConvTemplate)
4374       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4375                                        Init, DeclType, CandidateSet,
4376                                        /*AllowObjCConversionOnExplicit=*/false);
4377     else
4378       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4379                                DeclType, CandidateSet,
4380                                /*AllowObjCConversionOnExplicit=*/false);
4381   }
4382 
4383   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4384 
4385   OverloadCandidateSet::iterator Best;
4386   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4387   case OR_Success:
4388     // C++ [over.ics.ref]p1:
4389     //
4390     //   [...] If the parameter binds directly to the result of
4391     //   applying a conversion function to the argument
4392     //   expression, the implicit conversion sequence is a
4393     //   user-defined conversion sequence (13.3.3.1.2), with the
4394     //   second standard conversion sequence either an identity
4395     //   conversion or, if the conversion function returns an
4396     //   entity of a type that is a derived class of the parameter
4397     //   type, a derived-to-base Conversion.
4398     if (!Best->FinalConversion.DirectBinding)
4399       return false;
4400 
4401     ICS.setUserDefined();
4402     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4403     ICS.UserDefined.After = Best->FinalConversion;
4404     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4405     ICS.UserDefined.ConversionFunction = Best->Function;
4406     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4407     ICS.UserDefined.EllipsisConversion = false;
4408     assert(ICS.UserDefined.After.ReferenceBinding &&
4409            ICS.UserDefined.After.DirectBinding &&
4410            "Expected a direct reference binding!");
4411     return true;
4412 
4413   case OR_Ambiguous:
4414     ICS.setAmbiguous();
4415     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4416          Cand != CandidateSet.end(); ++Cand)
4417       if (Cand->Viable)
4418         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4419     return true;
4420 
4421   case OR_No_Viable_Function:
4422   case OR_Deleted:
4423     // There was no suitable conversion, or we found a deleted
4424     // conversion; continue with other checks.
4425     return false;
4426   }
4427 
4428   llvm_unreachable("Invalid OverloadResult!");
4429 }
4430 
4431 /// \brief Compute an implicit conversion sequence for reference
4432 /// initialization.
4433 static ImplicitConversionSequence
4434 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4435                  SourceLocation DeclLoc,
4436                  bool SuppressUserConversions,
4437                  bool AllowExplicit) {
4438   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4439 
4440   // Most paths end in a failed conversion.
4441   ImplicitConversionSequence ICS;
4442   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4443 
4444   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4445   QualType T2 = Init->getType();
4446 
4447   // If the initializer is the address of an overloaded function, try
4448   // to resolve the overloaded function. If all goes well, T2 is the
4449   // type of the resulting function.
4450   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4451     DeclAccessPair Found;
4452     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4453                                                                 false, Found))
4454       T2 = Fn->getType();
4455   }
4456 
4457   // Compute some basic properties of the types and the initializer.
4458   bool isRValRef = DeclType->isRValueReferenceType();
4459   bool DerivedToBase = false;
4460   bool ObjCConversion = false;
4461   bool ObjCLifetimeConversion = false;
4462   Expr::Classification InitCategory = Init->Classify(S.Context);
4463   Sema::ReferenceCompareResult RefRelationship
4464     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4465                                      ObjCConversion, ObjCLifetimeConversion);
4466 
4467 
4468   // C++0x [dcl.init.ref]p5:
4469   //   A reference to type "cv1 T1" is initialized by an expression
4470   //   of type "cv2 T2" as follows:
4471 
4472   //     -- If reference is an lvalue reference and the initializer expression
4473   if (!isRValRef) {
4474     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4475     //        reference-compatible with "cv2 T2," or
4476     //
4477     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4478     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4479       // C++ [over.ics.ref]p1:
4480       //   When a parameter of reference type binds directly (8.5.3)
4481       //   to an argument expression, the implicit conversion sequence
4482       //   is the identity conversion, unless the argument expression
4483       //   has a type that is a derived class of the parameter type,
4484       //   in which case the implicit conversion sequence is a
4485       //   derived-to-base Conversion (13.3.3.1).
4486       ICS.setStandard();
4487       ICS.Standard.First = ICK_Identity;
4488       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4489                          : ObjCConversion? ICK_Compatible_Conversion
4490                          : ICK_Identity;
4491       ICS.Standard.Third = ICK_Identity;
4492       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4493       ICS.Standard.setToType(0, T2);
4494       ICS.Standard.setToType(1, T1);
4495       ICS.Standard.setToType(2, T1);
4496       ICS.Standard.ReferenceBinding = true;
4497       ICS.Standard.DirectBinding = true;
4498       ICS.Standard.IsLvalueReference = !isRValRef;
4499       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4500       ICS.Standard.BindsToRvalue = false;
4501       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4502       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4503       ICS.Standard.CopyConstructor = nullptr;
4504       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4505 
4506       // Nothing more to do: the inaccessibility/ambiguity check for
4507       // derived-to-base conversions is suppressed when we're
4508       // computing the implicit conversion sequence (C++
4509       // [over.best.ics]p2).
4510       return ICS;
4511     }
4512 
4513     //       -- has a class type (i.e., T2 is a class type), where T1 is
4514     //          not reference-related to T2, and can be implicitly
4515     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4516     //          is reference-compatible with "cv3 T3" 92) (this
4517     //          conversion is selected by enumerating the applicable
4518     //          conversion functions (13.3.1.6) and choosing the best
4519     //          one through overload resolution (13.3)),
4520     if (!SuppressUserConversions && T2->isRecordType() &&
4521         S.isCompleteType(DeclLoc, T2) &&
4522         RefRelationship == Sema::Ref_Incompatible) {
4523       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4524                                    Init, T2, /*AllowRvalues=*/false,
4525                                    AllowExplicit))
4526         return ICS;
4527     }
4528   }
4529 
4530   //     -- Otherwise, the reference shall be an lvalue reference to a
4531   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4532   //        shall be an rvalue reference.
4533   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4534     return ICS;
4535 
4536   //       -- If the initializer expression
4537   //
4538   //            -- is an xvalue, class prvalue, array prvalue or function
4539   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4540   if (RefRelationship == Sema::Ref_Compatible &&
4541       (InitCategory.isXValue() ||
4542        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4543        (InitCategory.isLValue() && T2->isFunctionType()))) {
4544     ICS.setStandard();
4545     ICS.Standard.First = ICK_Identity;
4546     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4547                       : ObjCConversion? ICK_Compatible_Conversion
4548                       : ICK_Identity;
4549     ICS.Standard.Third = ICK_Identity;
4550     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4551     ICS.Standard.setToType(0, T2);
4552     ICS.Standard.setToType(1, T1);
4553     ICS.Standard.setToType(2, T1);
4554     ICS.Standard.ReferenceBinding = true;
4555     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4556     // binding unless we're binding to a class prvalue.
4557     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4558     // allow the use of rvalue references in C++98/03 for the benefit of
4559     // standard library implementors; therefore, we need the xvalue check here.
4560     ICS.Standard.DirectBinding =
4561       S.getLangOpts().CPlusPlus11 ||
4562       !(InitCategory.isPRValue() || T2->isRecordType());
4563     ICS.Standard.IsLvalueReference = !isRValRef;
4564     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4565     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4566     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4567     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4568     ICS.Standard.CopyConstructor = nullptr;
4569     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4570     return ICS;
4571   }
4572 
4573   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4574   //               reference-related to T2, and can be implicitly converted to
4575   //               an xvalue, class prvalue, or function lvalue of type
4576   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4577   //               "cv3 T3",
4578   //
4579   //          then the reference is bound to the value of the initializer
4580   //          expression in the first case and to the result of the conversion
4581   //          in the second case (or, in either case, to an appropriate base
4582   //          class subobject).
4583   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4584       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4585       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4586                                Init, T2, /*AllowRvalues=*/true,
4587                                AllowExplicit)) {
4588     // In the second case, if the reference is an rvalue reference
4589     // and the second standard conversion sequence of the
4590     // user-defined conversion sequence includes an lvalue-to-rvalue
4591     // conversion, the program is ill-formed.
4592     if (ICS.isUserDefined() && isRValRef &&
4593         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4594       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4595 
4596     return ICS;
4597   }
4598 
4599   // A temporary of function type cannot be created; don't even try.
4600   if (T1->isFunctionType())
4601     return ICS;
4602 
4603   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4604   //          initialized from the initializer expression using the
4605   //          rules for a non-reference copy initialization (8.5). The
4606   //          reference is then bound to the temporary. If T1 is
4607   //          reference-related to T2, cv1 must be the same
4608   //          cv-qualification as, or greater cv-qualification than,
4609   //          cv2; otherwise, the program is ill-formed.
4610   if (RefRelationship == Sema::Ref_Related) {
4611     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4612     // we would be reference-compatible or reference-compatible with
4613     // added qualification. But that wasn't the case, so the reference
4614     // initialization fails.
4615     //
4616     // Note that we only want to check address spaces and cvr-qualifiers here.
4617     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4618     Qualifiers T1Quals = T1.getQualifiers();
4619     Qualifiers T2Quals = T2.getQualifiers();
4620     T1Quals.removeObjCGCAttr();
4621     T1Quals.removeObjCLifetime();
4622     T2Quals.removeObjCGCAttr();
4623     T2Quals.removeObjCLifetime();
4624     // MS compiler ignores __unaligned qualifier for references; do the same.
4625     T1Quals.removeUnaligned();
4626     T2Quals.removeUnaligned();
4627     if (!T1Quals.compatiblyIncludes(T2Quals))
4628       return ICS;
4629   }
4630 
4631   // If at least one of the types is a class type, the types are not
4632   // related, and we aren't allowed any user conversions, the
4633   // reference binding fails. This case is important for breaking
4634   // recursion, since TryImplicitConversion below will attempt to
4635   // create a temporary through the use of a copy constructor.
4636   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4637       (T1->isRecordType() || T2->isRecordType()))
4638     return ICS;
4639 
4640   // If T1 is reference-related to T2 and the reference is an rvalue
4641   // reference, the initializer expression shall not be an lvalue.
4642   if (RefRelationship >= Sema::Ref_Related &&
4643       isRValRef && Init->Classify(S.Context).isLValue())
4644     return ICS;
4645 
4646   // C++ [over.ics.ref]p2:
4647   //   When a parameter of reference type is not bound directly to
4648   //   an argument expression, the conversion sequence is the one
4649   //   required to convert the argument expression to the
4650   //   underlying type of the reference according to
4651   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4652   //   to copy-initializing a temporary of the underlying type with
4653   //   the argument expression. Any difference in top-level
4654   //   cv-qualification is subsumed by the initialization itself
4655   //   and does not constitute a conversion.
4656   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4657                               /*AllowExplicit=*/false,
4658                               /*InOverloadResolution=*/false,
4659                               /*CStyle=*/false,
4660                               /*AllowObjCWritebackConversion=*/false,
4661                               /*AllowObjCConversionOnExplicit=*/false);
4662 
4663   // Of course, that's still a reference binding.
4664   if (ICS.isStandard()) {
4665     ICS.Standard.ReferenceBinding = true;
4666     ICS.Standard.IsLvalueReference = !isRValRef;
4667     ICS.Standard.BindsToFunctionLvalue = false;
4668     ICS.Standard.BindsToRvalue = true;
4669     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4670     ICS.Standard.ObjCLifetimeConversionBinding = false;
4671   } else if (ICS.isUserDefined()) {
4672     const ReferenceType *LValRefType =
4673         ICS.UserDefined.ConversionFunction->getReturnType()
4674             ->getAs<LValueReferenceType>();
4675 
4676     // C++ [over.ics.ref]p3:
4677     //   Except for an implicit object parameter, for which see 13.3.1, a
4678     //   standard conversion sequence cannot be formed if it requires [...]
4679     //   binding an rvalue reference to an lvalue other than a function
4680     //   lvalue.
4681     // Note that the function case is not possible here.
4682     if (DeclType->isRValueReferenceType() && LValRefType) {
4683       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4684       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4685       // reference to an rvalue!
4686       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4687       return ICS;
4688     }
4689 
4690     ICS.UserDefined.After.ReferenceBinding = true;
4691     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4692     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4693     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4694     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4695     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4696   }
4697 
4698   return ICS;
4699 }
4700 
4701 static ImplicitConversionSequence
4702 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4703                       bool SuppressUserConversions,
4704                       bool InOverloadResolution,
4705                       bool AllowObjCWritebackConversion,
4706                       bool AllowExplicit = false);
4707 
4708 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4709 /// initializer list From.
4710 static ImplicitConversionSequence
4711 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4712                   bool SuppressUserConversions,
4713                   bool InOverloadResolution,
4714                   bool AllowObjCWritebackConversion) {
4715   // C++11 [over.ics.list]p1:
4716   //   When an argument is an initializer list, it is not an expression and
4717   //   special rules apply for converting it to a parameter type.
4718 
4719   ImplicitConversionSequence Result;
4720   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4721 
4722   // We need a complete type for what follows. Incomplete types can never be
4723   // initialized from init lists.
4724   if (!S.isCompleteType(From->getLocStart(), ToType))
4725     return Result;
4726 
4727   // Per DR1467:
4728   //   If the parameter type is a class X and the initializer list has a single
4729   //   element of type cv U, where U is X or a class derived from X, the
4730   //   implicit conversion sequence is the one required to convert the element
4731   //   to the parameter type.
4732   //
4733   //   Otherwise, if the parameter type is a character array [... ]
4734   //   and the initializer list has a single element that is an
4735   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4736   //   implicit conversion sequence is the identity conversion.
4737   if (From->getNumInits() == 1) {
4738     if (ToType->isRecordType()) {
4739       QualType InitType = From->getInit(0)->getType();
4740       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4741           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4742         return TryCopyInitialization(S, From->getInit(0), ToType,
4743                                      SuppressUserConversions,
4744                                      InOverloadResolution,
4745                                      AllowObjCWritebackConversion);
4746     }
4747     // FIXME: Check the other conditions here: array of character type,
4748     // initializer is a string literal.
4749     if (ToType->isArrayType()) {
4750       InitializedEntity Entity =
4751         InitializedEntity::InitializeParameter(S.Context, ToType,
4752                                                /*Consumed=*/false);
4753       if (S.CanPerformCopyInitialization(Entity, From)) {
4754         Result.setStandard();
4755         Result.Standard.setAsIdentityConversion();
4756         Result.Standard.setFromType(ToType);
4757         Result.Standard.setAllToTypes(ToType);
4758         return Result;
4759       }
4760     }
4761   }
4762 
4763   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4764   // C++11 [over.ics.list]p2:
4765   //   If the parameter type is std::initializer_list<X> or "array of X" and
4766   //   all the elements can be implicitly converted to X, the implicit
4767   //   conversion sequence is the worst conversion necessary to convert an
4768   //   element of the list to X.
4769   //
4770   // C++14 [over.ics.list]p3:
4771   //   Otherwise, if the parameter type is "array of N X", if the initializer
4772   //   list has exactly N elements or if it has fewer than N elements and X is
4773   //   default-constructible, and if all the elements of the initializer list
4774   //   can be implicitly converted to X, the implicit conversion sequence is
4775   //   the worst conversion necessary to convert an element of the list to X.
4776   //
4777   // FIXME: We're missing a lot of these checks.
4778   bool toStdInitializerList = false;
4779   QualType X;
4780   if (ToType->isArrayType())
4781     X = S.Context.getAsArrayType(ToType)->getElementType();
4782   else
4783     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4784   if (!X.isNull()) {
4785     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4786       Expr *Init = From->getInit(i);
4787       ImplicitConversionSequence ICS =
4788           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4789                                 InOverloadResolution,
4790                                 AllowObjCWritebackConversion);
4791       // If a single element isn't convertible, fail.
4792       if (ICS.isBad()) {
4793         Result = ICS;
4794         break;
4795       }
4796       // Otherwise, look for the worst conversion.
4797       if (Result.isBad() ||
4798           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4799                                              Result) ==
4800               ImplicitConversionSequence::Worse)
4801         Result = ICS;
4802     }
4803 
4804     // For an empty list, we won't have computed any conversion sequence.
4805     // Introduce the identity conversion sequence.
4806     if (From->getNumInits() == 0) {
4807       Result.setStandard();
4808       Result.Standard.setAsIdentityConversion();
4809       Result.Standard.setFromType(ToType);
4810       Result.Standard.setAllToTypes(ToType);
4811     }
4812 
4813     Result.setStdInitializerListElement(toStdInitializerList);
4814     return Result;
4815   }
4816 
4817   // C++14 [over.ics.list]p4:
4818   // C++11 [over.ics.list]p3:
4819   //   Otherwise, if the parameter is a non-aggregate class X and overload
4820   //   resolution chooses a single best constructor [...] the implicit
4821   //   conversion sequence is a user-defined conversion sequence. If multiple
4822   //   constructors are viable but none is better than the others, the
4823   //   implicit conversion sequence is a user-defined conversion sequence.
4824   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4825     // This function can deal with initializer lists.
4826     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4827                                     /*AllowExplicit=*/false,
4828                                     InOverloadResolution, /*CStyle=*/false,
4829                                     AllowObjCWritebackConversion,
4830                                     /*AllowObjCConversionOnExplicit=*/false);
4831   }
4832 
4833   // C++14 [over.ics.list]p5:
4834   // C++11 [over.ics.list]p4:
4835   //   Otherwise, if the parameter has an aggregate type which can be
4836   //   initialized from the initializer list [...] the implicit conversion
4837   //   sequence is a user-defined conversion sequence.
4838   if (ToType->isAggregateType()) {
4839     // Type is an aggregate, argument is an init list. At this point it comes
4840     // down to checking whether the initialization works.
4841     // FIXME: Find out whether this parameter is consumed or not.
4842     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4843     // need to call into the initialization code here; overload resolution
4844     // should not be doing that.
4845     InitializedEntity Entity =
4846         InitializedEntity::InitializeParameter(S.Context, ToType,
4847                                                /*Consumed=*/false);
4848     if (S.CanPerformCopyInitialization(Entity, From)) {
4849       Result.setUserDefined();
4850       Result.UserDefined.Before.setAsIdentityConversion();
4851       // Initializer lists don't have a type.
4852       Result.UserDefined.Before.setFromType(QualType());
4853       Result.UserDefined.Before.setAllToTypes(QualType());
4854 
4855       Result.UserDefined.After.setAsIdentityConversion();
4856       Result.UserDefined.After.setFromType(ToType);
4857       Result.UserDefined.After.setAllToTypes(ToType);
4858       Result.UserDefined.ConversionFunction = nullptr;
4859     }
4860     return Result;
4861   }
4862 
4863   // C++14 [over.ics.list]p6:
4864   // C++11 [over.ics.list]p5:
4865   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4866   if (ToType->isReferenceType()) {
4867     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4868     // mention initializer lists in any way. So we go by what list-
4869     // initialization would do and try to extrapolate from that.
4870 
4871     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4872 
4873     // If the initializer list has a single element that is reference-related
4874     // to the parameter type, we initialize the reference from that.
4875     if (From->getNumInits() == 1) {
4876       Expr *Init = From->getInit(0);
4877 
4878       QualType T2 = Init->getType();
4879 
4880       // If the initializer is the address of an overloaded function, try
4881       // to resolve the overloaded function. If all goes well, T2 is the
4882       // type of the resulting function.
4883       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4884         DeclAccessPair Found;
4885         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4886                                    Init, ToType, false, Found))
4887           T2 = Fn->getType();
4888       }
4889 
4890       // Compute some basic properties of the types and the initializer.
4891       bool dummy1 = false;
4892       bool dummy2 = false;
4893       bool dummy3 = false;
4894       Sema::ReferenceCompareResult RefRelationship
4895         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4896                                          dummy2, dummy3);
4897 
4898       if (RefRelationship >= Sema::Ref_Related) {
4899         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4900                                 SuppressUserConversions,
4901                                 /*AllowExplicit=*/false);
4902       }
4903     }
4904 
4905     // Otherwise, we bind the reference to a temporary created from the
4906     // initializer list.
4907     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4908                                InOverloadResolution,
4909                                AllowObjCWritebackConversion);
4910     if (Result.isFailure())
4911       return Result;
4912     assert(!Result.isEllipsis() &&
4913            "Sub-initialization cannot result in ellipsis conversion.");
4914 
4915     // Can we even bind to a temporary?
4916     if (ToType->isRValueReferenceType() ||
4917         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4918       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4919                                             Result.UserDefined.After;
4920       SCS.ReferenceBinding = true;
4921       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4922       SCS.BindsToRvalue = true;
4923       SCS.BindsToFunctionLvalue = false;
4924       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4925       SCS.ObjCLifetimeConversionBinding = false;
4926     } else
4927       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4928                     From, ToType);
4929     return Result;
4930   }
4931 
4932   // C++14 [over.ics.list]p7:
4933   // C++11 [over.ics.list]p6:
4934   //   Otherwise, if the parameter type is not a class:
4935   if (!ToType->isRecordType()) {
4936     //    - if the initializer list has one element that is not itself an
4937     //      initializer list, the implicit conversion sequence is the one
4938     //      required to convert the element to the parameter type.
4939     unsigned NumInits = From->getNumInits();
4940     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4941       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4942                                      SuppressUserConversions,
4943                                      InOverloadResolution,
4944                                      AllowObjCWritebackConversion);
4945     //    - if the initializer list has no elements, the implicit conversion
4946     //      sequence is the identity conversion.
4947     else if (NumInits == 0) {
4948       Result.setStandard();
4949       Result.Standard.setAsIdentityConversion();
4950       Result.Standard.setFromType(ToType);
4951       Result.Standard.setAllToTypes(ToType);
4952     }
4953     return Result;
4954   }
4955 
4956   // C++14 [over.ics.list]p8:
4957   // C++11 [over.ics.list]p7:
4958   //   In all cases other than those enumerated above, no conversion is possible
4959   return Result;
4960 }
4961 
4962 /// TryCopyInitialization - Try to copy-initialize a value of type
4963 /// ToType from the expression From. Return the implicit conversion
4964 /// sequence required to pass this argument, which may be a bad
4965 /// conversion sequence (meaning that the argument cannot be passed to
4966 /// a parameter of this type). If @p SuppressUserConversions, then we
4967 /// do not permit any user-defined conversion sequences.
4968 static ImplicitConversionSequence
4969 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4970                       bool SuppressUserConversions,
4971                       bool InOverloadResolution,
4972                       bool AllowObjCWritebackConversion,
4973                       bool AllowExplicit) {
4974   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4975     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4976                              InOverloadResolution,AllowObjCWritebackConversion);
4977 
4978   if (ToType->isReferenceType())
4979     return TryReferenceInit(S, From, ToType,
4980                             /*FIXME:*/From->getLocStart(),
4981                             SuppressUserConversions,
4982                             AllowExplicit);
4983 
4984   return TryImplicitConversion(S, From, ToType,
4985                                SuppressUserConversions,
4986                                /*AllowExplicit=*/false,
4987                                InOverloadResolution,
4988                                /*CStyle=*/false,
4989                                AllowObjCWritebackConversion,
4990                                /*AllowObjCConversionOnExplicit=*/false);
4991 }
4992 
4993 static bool TryCopyInitialization(const CanQualType FromQTy,
4994                                   const CanQualType ToQTy,
4995                                   Sema &S,
4996                                   SourceLocation Loc,
4997                                   ExprValueKind FromVK) {
4998   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4999   ImplicitConversionSequence ICS =
5000     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5001 
5002   return !ICS.isBad();
5003 }
5004 
5005 /// TryObjectArgumentInitialization - Try to initialize the object
5006 /// parameter of the given member function (@c Method) from the
5007 /// expression @p From.
5008 static ImplicitConversionSequence
5009 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5010                                 Expr::Classification FromClassification,
5011                                 CXXMethodDecl *Method,
5012                                 CXXRecordDecl *ActingContext) {
5013   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5014   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5015   //                 const volatile object.
5016   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5017     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5018   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5019 
5020   // Set up the conversion sequence as a "bad" conversion, to allow us
5021   // to exit early.
5022   ImplicitConversionSequence ICS;
5023 
5024   // We need to have an object of class type.
5025   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5026     FromType = PT->getPointeeType();
5027 
5028     // When we had a pointer, it's implicitly dereferenced, so we
5029     // better have an lvalue.
5030     assert(FromClassification.isLValue());
5031   }
5032 
5033   assert(FromType->isRecordType());
5034 
5035   // C++0x [over.match.funcs]p4:
5036   //   For non-static member functions, the type of the implicit object
5037   //   parameter is
5038   //
5039   //     - "lvalue reference to cv X" for functions declared without a
5040   //        ref-qualifier or with the & ref-qualifier
5041   //     - "rvalue reference to cv X" for functions declared with the &&
5042   //        ref-qualifier
5043   //
5044   // where X is the class of which the function is a member and cv is the
5045   // cv-qualification on the member function declaration.
5046   //
5047   // However, when finding an implicit conversion sequence for the argument, we
5048   // are not allowed to perform user-defined conversions
5049   // (C++ [over.match.funcs]p5). We perform a simplified version of
5050   // reference binding here, that allows class rvalues to bind to
5051   // non-constant references.
5052 
5053   // First check the qualifiers.
5054   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5055   if (ImplicitParamType.getCVRQualifiers()
5056                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5057       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5058     ICS.setBad(BadConversionSequence::bad_qualifiers,
5059                FromType, ImplicitParamType);
5060     return ICS;
5061   }
5062 
5063   // Check that we have either the same type or a derived type. It
5064   // affects the conversion rank.
5065   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5066   ImplicitConversionKind SecondKind;
5067   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5068     SecondKind = ICK_Identity;
5069   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5070     SecondKind = ICK_Derived_To_Base;
5071   else {
5072     ICS.setBad(BadConversionSequence::unrelated_class,
5073                FromType, ImplicitParamType);
5074     return ICS;
5075   }
5076 
5077   // Check the ref-qualifier.
5078   switch (Method->getRefQualifier()) {
5079   case RQ_None:
5080     // Do nothing; we don't care about lvalueness or rvalueness.
5081     break;
5082 
5083   case RQ_LValue:
5084     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5085       // non-const lvalue reference cannot bind to an rvalue
5086       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5087                  ImplicitParamType);
5088       return ICS;
5089     }
5090     break;
5091 
5092   case RQ_RValue:
5093     if (!FromClassification.isRValue()) {
5094       // rvalue reference cannot bind to an lvalue
5095       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5096                  ImplicitParamType);
5097       return ICS;
5098     }
5099     break;
5100   }
5101 
5102   // Success. Mark this as a reference binding.
5103   ICS.setStandard();
5104   ICS.Standard.setAsIdentityConversion();
5105   ICS.Standard.Second = SecondKind;
5106   ICS.Standard.setFromType(FromType);
5107   ICS.Standard.setAllToTypes(ImplicitParamType);
5108   ICS.Standard.ReferenceBinding = true;
5109   ICS.Standard.DirectBinding = true;
5110   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5111   ICS.Standard.BindsToFunctionLvalue = false;
5112   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5113   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5114     = (Method->getRefQualifier() == RQ_None);
5115   return ICS;
5116 }
5117 
5118 /// PerformObjectArgumentInitialization - Perform initialization of
5119 /// the implicit object parameter for the given Method with the given
5120 /// expression.
5121 ExprResult
5122 Sema::PerformObjectArgumentInitialization(Expr *From,
5123                                           NestedNameSpecifier *Qualifier,
5124                                           NamedDecl *FoundDecl,
5125                                           CXXMethodDecl *Method) {
5126   QualType FromRecordType, DestType;
5127   QualType ImplicitParamRecordType  =
5128     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5129 
5130   Expr::Classification FromClassification;
5131   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5132     FromRecordType = PT->getPointeeType();
5133     DestType = Method->getThisType(Context);
5134     FromClassification = Expr::Classification::makeSimpleLValue();
5135   } else {
5136     FromRecordType = From->getType();
5137     DestType = ImplicitParamRecordType;
5138     FromClassification = From->Classify(Context);
5139   }
5140 
5141   // Note that we always use the true parent context when performing
5142   // the actual argument initialization.
5143   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5144       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5145       Method->getParent());
5146   if (ICS.isBad()) {
5147     switch (ICS.Bad.Kind) {
5148     case BadConversionSequence::bad_qualifiers: {
5149       Qualifiers FromQs = FromRecordType.getQualifiers();
5150       Qualifiers ToQs = DestType.getQualifiers();
5151       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5152       if (CVR) {
5153         Diag(From->getLocStart(),
5154              diag::err_member_function_call_bad_cvr)
5155           << Method->getDeclName() << FromRecordType << (CVR - 1)
5156           << From->getSourceRange();
5157         Diag(Method->getLocation(), diag::note_previous_decl)
5158           << Method->getDeclName();
5159         return ExprError();
5160       }
5161       break;
5162     }
5163 
5164     case BadConversionSequence::lvalue_ref_to_rvalue:
5165     case BadConversionSequence::rvalue_ref_to_lvalue: {
5166       bool IsRValueQualified =
5167         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5168       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5169         << Method->getDeclName() << FromClassification.isRValue()
5170         << IsRValueQualified;
5171       Diag(Method->getLocation(), diag::note_previous_decl)
5172         << Method->getDeclName();
5173       return ExprError();
5174     }
5175 
5176     case BadConversionSequence::no_conversion:
5177     case BadConversionSequence::unrelated_class:
5178       break;
5179     }
5180 
5181     return Diag(From->getLocStart(),
5182                 diag::err_member_function_call_bad_type)
5183        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5184   }
5185 
5186   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5187     ExprResult FromRes =
5188       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5189     if (FromRes.isInvalid())
5190       return ExprError();
5191     From = FromRes.get();
5192   }
5193 
5194   if (!Context.hasSameType(From->getType(), DestType))
5195     From = ImpCastExprToType(From, DestType, CK_NoOp,
5196                              From->getValueKind()).get();
5197   return From;
5198 }
5199 
5200 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5201 /// expression From to bool (C++0x [conv]p3).
5202 static ImplicitConversionSequence
5203 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5204   return TryImplicitConversion(S, From, S.Context.BoolTy,
5205                                /*SuppressUserConversions=*/false,
5206                                /*AllowExplicit=*/true,
5207                                /*InOverloadResolution=*/false,
5208                                /*CStyle=*/false,
5209                                /*AllowObjCWritebackConversion=*/false,
5210                                /*AllowObjCConversionOnExplicit=*/false);
5211 }
5212 
5213 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5214 /// of the expression From to bool (C++0x [conv]p3).
5215 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5216   if (checkPlaceholderForOverload(*this, From))
5217     return ExprError();
5218 
5219   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5220   if (!ICS.isBad())
5221     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5222 
5223   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5224     return Diag(From->getLocStart(),
5225                 diag::err_typecheck_bool_condition)
5226                   << From->getType() << From->getSourceRange();
5227   return ExprError();
5228 }
5229 
5230 /// Check that the specified conversion is permitted in a converted constant
5231 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5232 /// is acceptable.
5233 static bool CheckConvertedConstantConversions(Sema &S,
5234                                               StandardConversionSequence &SCS) {
5235   // Since we know that the target type is an integral or unscoped enumeration
5236   // type, most conversion kinds are impossible. All possible First and Third
5237   // conversions are fine.
5238   switch (SCS.Second) {
5239   case ICK_Identity:
5240   case ICK_Function_Conversion:
5241   case ICK_Integral_Promotion:
5242   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5243   case ICK_Zero_Queue_Conversion:
5244     return true;
5245 
5246   case ICK_Boolean_Conversion:
5247     // Conversion from an integral or unscoped enumeration type to bool is
5248     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5249     // conversion, so we allow it in a converted constant expression.
5250     //
5251     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5252     // a lot of popular code. We should at least add a warning for this
5253     // (non-conforming) extension.
5254     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5255            SCS.getToType(2)->isBooleanType();
5256 
5257   case ICK_Pointer_Conversion:
5258   case ICK_Pointer_Member:
5259     // C++1z: null pointer conversions and null member pointer conversions are
5260     // only permitted if the source type is std::nullptr_t.
5261     return SCS.getFromType()->isNullPtrType();
5262 
5263   case ICK_Floating_Promotion:
5264   case ICK_Complex_Promotion:
5265   case ICK_Floating_Conversion:
5266   case ICK_Complex_Conversion:
5267   case ICK_Floating_Integral:
5268   case ICK_Compatible_Conversion:
5269   case ICK_Derived_To_Base:
5270   case ICK_Vector_Conversion:
5271   case ICK_Vector_Splat:
5272   case ICK_Complex_Real:
5273   case ICK_Block_Pointer_Conversion:
5274   case ICK_TransparentUnionConversion:
5275   case ICK_Writeback_Conversion:
5276   case ICK_Zero_Event_Conversion:
5277   case ICK_C_Only_Conversion:
5278   case ICK_Incompatible_Pointer_Conversion:
5279     return false;
5280 
5281   case ICK_Lvalue_To_Rvalue:
5282   case ICK_Array_To_Pointer:
5283   case ICK_Function_To_Pointer:
5284     llvm_unreachable("found a first conversion kind in Second");
5285 
5286   case ICK_Qualification:
5287     llvm_unreachable("found a third conversion kind in Second");
5288 
5289   case ICK_Num_Conversion_Kinds:
5290     break;
5291   }
5292 
5293   llvm_unreachable("unknown conversion kind");
5294 }
5295 
5296 /// CheckConvertedConstantExpression - Check that the expression From is a
5297 /// converted constant expression of type T, perform the conversion and produce
5298 /// the converted expression, per C++11 [expr.const]p3.
5299 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5300                                                    QualType T, APValue &Value,
5301                                                    Sema::CCEKind CCE,
5302                                                    bool RequireInt) {
5303   assert(S.getLangOpts().CPlusPlus11 &&
5304          "converted constant expression outside C++11");
5305 
5306   if (checkPlaceholderForOverload(S, From))
5307     return ExprError();
5308 
5309   // C++1z [expr.const]p3:
5310   //  A converted constant expression of type T is an expression,
5311   //  implicitly converted to type T, where the converted
5312   //  expression is a constant expression and the implicit conversion
5313   //  sequence contains only [... list of conversions ...].
5314   // C++1z [stmt.if]p2:
5315   //  If the if statement is of the form if constexpr, the value of the
5316   //  condition shall be a contextually converted constant expression of type
5317   //  bool.
5318   ImplicitConversionSequence ICS =
5319       CCE == Sema::CCEK_ConstexprIf
5320           ? TryContextuallyConvertToBool(S, From)
5321           : TryCopyInitialization(S, From, T,
5322                                   /*SuppressUserConversions=*/false,
5323                                   /*InOverloadResolution=*/false,
5324                                   /*AllowObjcWritebackConversion=*/false,
5325                                   /*AllowExplicit=*/false);
5326   StandardConversionSequence *SCS = nullptr;
5327   switch (ICS.getKind()) {
5328   case ImplicitConversionSequence::StandardConversion:
5329     SCS = &ICS.Standard;
5330     break;
5331   case ImplicitConversionSequence::UserDefinedConversion:
5332     // We are converting to a non-class type, so the Before sequence
5333     // must be trivial.
5334     SCS = &ICS.UserDefined.After;
5335     break;
5336   case ImplicitConversionSequence::AmbiguousConversion:
5337   case ImplicitConversionSequence::BadConversion:
5338     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5339       return S.Diag(From->getLocStart(),
5340                     diag::err_typecheck_converted_constant_expression)
5341                 << From->getType() << From->getSourceRange() << T;
5342     return ExprError();
5343 
5344   case ImplicitConversionSequence::EllipsisConversion:
5345     llvm_unreachable("ellipsis conversion in converted constant expression");
5346   }
5347 
5348   // Check that we would only use permitted conversions.
5349   if (!CheckConvertedConstantConversions(S, *SCS)) {
5350     return S.Diag(From->getLocStart(),
5351                   diag::err_typecheck_converted_constant_expression_disallowed)
5352              << From->getType() << From->getSourceRange() << T;
5353   }
5354   // [...] and where the reference binding (if any) binds directly.
5355   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5356     return S.Diag(From->getLocStart(),
5357                   diag::err_typecheck_converted_constant_expression_indirect)
5358              << From->getType() << From->getSourceRange() << T;
5359   }
5360 
5361   ExprResult Result =
5362       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5363   if (Result.isInvalid())
5364     return Result;
5365 
5366   // Check for a narrowing implicit conversion.
5367   APValue PreNarrowingValue;
5368   QualType PreNarrowingType;
5369   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5370                                 PreNarrowingType)) {
5371   case NK_Dependent_Narrowing:
5372     // Implicit conversion to a narrower type, but the expression is
5373     // value-dependent so we can't tell whether it's actually narrowing.
5374   case NK_Variable_Narrowing:
5375     // Implicit conversion to a narrower type, and the value is not a constant
5376     // expression. We'll diagnose this in a moment.
5377   case NK_Not_Narrowing:
5378     break;
5379 
5380   case NK_Constant_Narrowing:
5381     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5382       << CCE << /*Constant*/1
5383       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5384     break;
5385 
5386   case NK_Type_Narrowing:
5387     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5388       << CCE << /*Constant*/0 << From->getType() << T;
5389     break;
5390   }
5391 
5392   if (Result.get()->isValueDependent()) {
5393     Value = APValue();
5394     return Result;
5395   }
5396 
5397   // Check the expression is a constant expression.
5398   SmallVector<PartialDiagnosticAt, 8> Notes;
5399   Expr::EvalResult Eval;
5400   Eval.Diag = &Notes;
5401 
5402   if ((T->isReferenceType()
5403            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5404            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5405       (RequireInt && !Eval.Val.isInt())) {
5406     // The expression can't be folded, so we can't keep it at this position in
5407     // the AST.
5408     Result = ExprError();
5409   } else {
5410     Value = Eval.Val;
5411 
5412     if (Notes.empty()) {
5413       // It's a constant expression.
5414       return Result;
5415     }
5416   }
5417 
5418   // It's not a constant expression. Produce an appropriate diagnostic.
5419   if (Notes.size() == 1 &&
5420       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5421     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5422   else {
5423     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5424       << CCE << From->getSourceRange();
5425     for (unsigned I = 0; I < Notes.size(); ++I)
5426       S.Diag(Notes[I].first, Notes[I].second);
5427   }
5428   return ExprError();
5429 }
5430 
5431 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5432                                                   APValue &Value, CCEKind CCE) {
5433   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5434 }
5435 
5436 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5437                                                   llvm::APSInt &Value,
5438                                                   CCEKind CCE) {
5439   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5440 
5441   APValue V;
5442   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5443   if (!R.isInvalid() && !R.get()->isValueDependent())
5444     Value = V.getInt();
5445   return R;
5446 }
5447 
5448 
5449 /// dropPointerConversions - If the given standard conversion sequence
5450 /// involves any pointer conversions, remove them.  This may change
5451 /// the result type of the conversion sequence.
5452 static void dropPointerConversion(StandardConversionSequence &SCS) {
5453   if (SCS.Second == ICK_Pointer_Conversion) {
5454     SCS.Second = ICK_Identity;
5455     SCS.Third = ICK_Identity;
5456     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5457   }
5458 }
5459 
5460 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5461 /// convert the expression From to an Objective-C pointer type.
5462 static ImplicitConversionSequence
5463 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5464   // Do an implicit conversion to 'id'.
5465   QualType Ty = S.Context.getObjCIdType();
5466   ImplicitConversionSequence ICS
5467     = TryImplicitConversion(S, From, Ty,
5468                             // FIXME: Are these flags correct?
5469                             /*SuppressUserConversions=*/false,
5470                             /*AllowExplicit=*/true,
5471                             /*InOverloadResolution=*/false,
5472                             /*CStyle=*/false,
5473                             /*AllowObjCWritebackConversion=*/false,
5474                             /*AllowObjCConversionOnExplicit=*/true);
5475 
5476   // Strip off any final conversions to 'id'.
5477   switch (ICS.getKind()) {
5478   case ImplicitConversionSequence::BadConversion:
5479   case ImplicitConversionSequence::AmbiguousConversion:
5480   case ImplicitConversionSequence::EllipsisConversion:
5481     break;
5482 
5483   case ImplicitConversionSequence::UserDefinedConversion:
5484     dropPointerConversion(ICS.UserDefined.After);
5485     break;
5486 
5487   case ImplicitConversionSequence::StandardConversion:
5488     dropPointerConversion(ICS.Standard);
5489     break;
5490   }
5491 
5492   return ICS;
5493 }
5494 
5495 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5496 /// conversion of the expression From to an Objective-C pointer type.
5497 /// Returns a valid but null ExprResult if no conversion sequence exists.
5498 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5499   if (checkPlaceholderForOverload(*this, From))
5500     return ExprError();
5501 
5502   QualType Ty = Context.getObjCIdType();
5503   ImplicitConversionSequence ICS =
5504     TryContextuallyConvertToObjCPointer(*this, From);
5505   if (!ICS.isBad())
5506     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5507   return ExprResult();
5508 }
5509 
5510 /// Determine whether the provided type is an integral type, or an enumeration
5511 /// type of a permitted flavor.
5512 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5513   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5514                                  : T->isIntegralOrUnscopedEnumerationType();
5515 }
5516 
5517 static ExprResult
5518 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5519                             Sema::ContextualImplicitConverter &Converter,
5520                             QualType T, UnresolvedSetImpl &ViableConversions) {
5521 
5522   if (Converter.Suppress)
5523     return ExprError();
5524 
5525   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5526   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5527     CXXConversionDecl *Conv =
5528         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5529     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5530     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5531   }
5532   return From;
5533 }
5534 
5535 static bool
5536 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5537                            Sema::ContextualImplicitConverter &Converter,
5538                            QualType T, bool HadMultipleCandidates,
5539                            UnresolvedSetImpl &ExplicitConversions) {
5540   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5541     DeclAccessPair Found = ExplicitConversions[0];
5542     CXXConversionDecl *Conversion =
5543         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5544 
5545     // The user probably meant to invoke the given explicit
5546     // conversion; use it.
5547     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5548     std::string TypeStr;
5549     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5550 
5551     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5552         << FixItHint::CreateInsertion(From->getLocStart(),
5553                                       "static_cast<" + TypeStr + ">(")
5554         << FixItHint::CreateInsertion(
5555                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5556     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5557 
5558     // If we aren't in a SFINAE context, build a call to the
5559     // explicit conversion function.
5560     if (SemaRef.isSFINAEContext())
5561       return true;
5562 
5563     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5564     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5565                                                        HadMultipleCandidates);
5566     if (Result.isInvalid())
5567       return true;
5568     // Record usage of conversion in an implicit cast.
5569     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5570                                     CK_UserDefinedConversion, Result.get(),
5571                                     nullptr, Result.get()->getValueKind());
5572   }
5573   return false;
5574 }
5575 
5576 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5577                              Sema::ContextualImplicitConverter &Converter,
5578                              QualType T, bool HadMultipleCandidates,
5579                              DeclAccessPair &Found) {
5580   CXXConversionDecl *Conversion =
5581       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5582   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5583 
5584   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5585   if (!Converter.SuppressConversion) {
5586     if (SemaRef.isSFINAEContext())
5587       return true;
5588 
5589     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5590         << From->getSourceRange();
5591   }
5592 
5593   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5594                                                      HadMultipleCandidates);
5595   if (Result.isInvalid())
5596     return true;
5597   // Record usage of conversion in an implicit cast.
5598   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5599                                   CK_UserDefinedConversion, Result.get(),
5600                                   nullptr, Result.get()->getValueKind());
5601   return false;
5602 }
5603 
5604 static ExprResult finishContextualImplicitConversion(
5605     Sema &SemaRef, SourceLocation Loc, Expr *From,
5606     Sema::ContextualImplicitConverter &Converter) {
5607   if (!Converter.match(From->getType()) && !Converter.Suppress)
5608     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5609         << From->getSourceRange();
5610 
5611   return SemaRef.DefaultLvalueConversion(From);
5612 }
5613 
5614 static void
5615 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5616                                   UnresolvedSetImpl &ViableConversions,
5617                                   OverloadCandidateSet &CandidateSet) {
5618   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5619     DeclAccessPair FoundDecl = ViableConversions[I];
5620     NamedDecl *D = FoundDecl.getDecl();
5621     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5622     if (isa<UsingShadowDecl>(D))
5623       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5624 
5625     CXXConversionDecl *Conv;
5626     FunctionTemplateDecl *ConvTemplate;
5627     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5628       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5629     else
5630       Conv = cast<CXXConversionDecl>(D);
5631 
5632     if (ConvTemplate)
5633       SemaRef.AddTemplateConversionCandidate(
5634         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5635         /*AllowObjCConversionOnExplicit=*/false);
5636     else
5637       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5638                                      ToType, CandidateSet,
5639                                      /*AllowObjCConversionOnExplicit=*/false);
5640   }
5641 }
5642 
5643 /// \brief Attempt to convert the given expression to a type which is accepted
5644 /// by the given converter.
5645 ///
5646 /// This routine will attempt to convert an expression of class type to a
5647 /// type accepted by the specified converter. In C++11 and before, the class
5648 /// must have a single non-explicit conversion function converting to a matching
5649 /// type. In C++1y, there can be multiple such conversion functions, but only
5650 /// one target type.
5651 ///
5652 /// \param Loc The source location of the construct that requires the
5653 /// conversion.
5654 ///
5655 /// \param From The expression we're converting from.
5656 ///
5657 /// \param Converter Used to control and diagnose the conversion process.
5658 ///
5659 /// \returns The expression, converted to an integral or enumeration type if
5660 /// successful.
5661 ExprResult Sema::PerformContextualImplicitConversion(
5662     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5663   // We can't perform any more checking for type-dependent expressions.
5664   if (From->isTypeDependent())
5665     return From;
5666 
5667   // Process placeholders immediately.
5668   if (From->hasPlaceholderType()) {
5669     ExprResult result = CheckPlaceholderExpr(From);
5670     if (result.isInvalid())
5671       return result;
5672     From = result.get();
5673   }
5674 
5675   // If the expression already has a matching type, we're golden.
5676   QualType T = From->getType();
5677   if (Converter.match(T))
5678     return DefaultLvalueConversion(From);
5679 
5680   // FIXME: Check for missing '()' if T is a function type?
5681 
5682   // We can only perform contextual implicit conversions on objects of class
5683   // type.
5684   const RecordType *RecordTy = T->getAs<RecordType>();
5685   if (!RecordTy || !getLangOpts().CPlusPlus) {
5686     if (!Converter.Suppress)
5687       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5688     return From;
5689   }
5690 
5691   // We must have a complete class type.
5692   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5693     ContextualImplicitConverter &Converter;
5694     Expr *From;
5695 
5696     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5697         : Converter(Converter), From(From) {}
5698 
5699     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5700       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5701     }
5702   } IncompleteDiagnoser(Converter, From);
5703 
5704   if (Converter.Suppress ? !isCompleteType(Loc, T)
5705                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5706     return From;
5707 
5708   // Look for a conversion to an integral or enumeration type.
5709   UnresolvedSet<4>
5710       ViableConversions; // These are *potentially* viable in C++1y.
5711   UnresolvedSet<4> ExplicitConversions;
5712   const auto &Conversions =
5713       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5714 
5715   bool HadMultipleCandidates =
5716       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5717 
5718   // To check that there is only one target type, in C++1y:
5719   QualType ToType;
5720   bool HasUniqueTargetType = true;
5721 
5722   // Collect explicit or viable (potentially in C++1y) conversions.
5723   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5724     NamedDecl *D = (*I)->getUnderlyingDecl();
5725     CXXConversionDecl *Conversion;
5726     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5727     if (ConvTemplate) {
5728       if (getLangOpts().CPlusPlus14)
5729         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5730       else
5731         continue; // C++11 does not consider conversion operator templates(?).
5732     } else
5733       Conversion = cast<CXXConversionDecl>(D);
5734 
5735     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5736            "Conversion operator templates are considered potentially "
5737            "viable in C++1y");
5738 
5739     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5740     if (Converter.match(CurToType) || ConvTemplate) {
5741 
5742       if (Conversion->isExplicit()) {
5743         // FIXME: For C++1y, do we need this restriction?
5744         // cf. diagnoseNoViableConversion()
5745         if (!ConvTemplate)
5746           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5747       } else {
5748         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5749           if (ToType.isNull())
5750             ToType = CurToType.getUnqualifiedType();
5751           else if (HasUniqueTargetType &&
5752                    (CurToType.getUnqualifiedType() != ToType))
5753             HasUniqueTargetType = false;
5754         }
5755         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5756       }
5757     }
5758   }
5759 
5760   if (getLangOpts().CPlusPlus14) {
5761     // C++1y [conv]p6:
5762     // ... An expression e of class type E appearing in such a context
5763     // is said to be contextually implicitly converted to a specified
5764     // type T and is well-formed if and only if e can be implicitly
5765     // converted to a type T that is determined as follows: E is searched
5766     // for conversion functions whose return type is cv T or reference to
5767     // cv T such that T is allowed by the context. There shall be
5768     // exactly one such T.
5769 
5770     // If no unique T is found:
5771     if (ToType.isNull()) {
5772       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5773                                      HadMultipleCandidates,
5774                                      ExplicitConversions))
5775         return ExprError();
5776       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5777     }
5778 
5779     // If more than one unique Ts are found:
5780     if (!HasUniqueTargetType)
5781       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5782                                          ViableConversions);
5783 
5784     // If one unique T is found:
5785     // First, build a candidate set from the previously recorded
5786     // potentially viable conversions.
5787     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5788     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5789                                       CandidateSet);
5790 
5791     // Then, perform overload resolution over the candidate set.
5792     OverloadCandidateSet::iterator Best;
5793     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5794     case OR_Success: {
5795       // Apply this conversion.
5796       DeclAccessPair Found =
5797           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5798       if (recordConversion(*this, Loc, From, Converter, T,
5799                            HadMultipleCandidates, Found))
5800         return ExprError();
5801       break;
5802     }
5803     case OR_Ambiguous:
5804       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5805                                          ViableConversions);
5806     case OR_No_Viable_Function:
5807       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5808                                      HadMultipleCandidates,
5809                                      ExplicitConversions))
5810         return ExprError();
5811       LLVM_FALLTHROUGH;
5812     case OR_Deleted:
5813       // We'll complain below about a non-integral condition type.
5814       break;
5815     }
5816   } else {
5817     switch (ViableConversions.size()) {
5818     case 0: {
5819       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5820                                      HadMultipleCandidates,
5821                                      ExplicitConversions))
5822         return ExprError();
5823 
5824       // We'll complain below about a non-integral condition type.
5825       break;
5826     }
5827     case 1: {
5828       // Apply this conversion.
5829       DeclAccessPair Found = ViableConversions[0];
5830       if (recordConversion(*this, Loc, From, Converter, T,
5831                            HadMultipleCandidates, Found))
5832         return ExprError();
5833       break;
5834     }
5835     default:
5836       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5837                                          ViableConversions);
5838     }
5839   }
5840 
5841   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5842 }
5843 
5844 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5845 /// an acceptable non-member overloaded operator for a call whose
5846 /// arguments have types T1 (and, if non-empty, T2). This routine
5847 /// implements the check in C++ [over.match.oper]p3b2 concerning
5848 /// enumeration types.
5849 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5850                                                    FunctionDecl *Fn,
5851                                                    ArrayRef<Expr *> Args) {
5852   QualType T1 = Args[0]->getType();
5853   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5854 
5855   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5856     return true;
5857 
5858   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5859     return true;
5860 
5861   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5862   if (Proto->getNumParams() < 1)
5863     return false;
5864 
5865   if (T1->isEnumeralType()) {
5866     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5867     if (Context.hasSameUnqualifiedType(T1, ArgType))
5868       return true;
5869   }
5870 
5871   if (Proto->getNumParams() < 2)
5872     return false;
5873 
5874   if (!T2.isNull() && T2->isEnumeralType()) {
5875     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5876     if (Context.hasSameUnqualifiedType(T2, ArgType))
5877       return true;
5878   }
5879 
5880   return false;
5881 }
5882 
5883 /// AddOverloadCandidate - Adds the given function to the set of
5884 /// candidate functions, using the given function call arguments.  If
5885 /// @p SuppressUserConversions, then don't allow user-defined
5886 /// conversions via constructors or conversion operators.
5887 ///
5888 /// \param PartialOverloading true if we are performing "partial" overloading
5889 /// based on an incomplete set of function arguments. This feature is used by
5890 /// code completion.
5891 void
5892 Sema::AddOverloadCandidate(FunctionDecl *Function,
5893                            DeclAccessPair FoundDecl,
5894                            ArrayRef<Expr *> Args,
5895                            OverloadCandidateSet &CandidateSet,
5896                            bool SuppressUserConversions,
5897                            bool PartialOverloading,
5898                            bool AllowExplicit,
5899                            ConversionSequenceList EarlyConversions) {
5900   const FunctionProtoType *Proto
5901     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5902   assert(Proto && "Functions without a prototype cannot be overloaded");
5903   assert(!Function->getDescribedFunctionTemplate() &&
5904          "Use AddTemplateOverloadCandidate for function templates");
5905 
5906   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5907     if (!isa<CXXConstructorDecl>(Method)) {
5908       // If we get here, it's because we're calling a member function
5909       // that is named without a member access expression (e.g.,
5910       // "this->f") that was either written explicitly or created
5911       // implicitly. This can happen with a qualified call to a member
5912       // function, e.g., X::f(). We use an empty type for the implied
5913       // object argument (C++ [over.call.func]p3), and the acting context
5914       // is irrelevant.
5915       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5916                          Expr::Classification::makeSimpleLValue(), Args,
5917                          CandidateSet, SuppressUserConversions,
5918                          PartialOverloading, EarlyConversions);
5919       return;
5920     }
5921     // We treat a constructor like a non-member function, since its object
5922     // argument doesn't participate in overload resolution.
5923   }
5924 
5925   if (!CandidateSet.isNewCandidate(Function))
5926     return;
5927 
5928   // C++ [over.match.oper]p3:
5929   //   if no operand has a class type, only those non-member functions in the
5930   //   lookup set that have a first parameter of type T1 or "reference to
5931   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5932   //   is a right operand) a second parameter of type T2 or "reference to
5933   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5934   //   candidate functions.
5935   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5936       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5937     return;
5938 
5939   // C++11 [class.copy]p11: [DR1402]
5940   //   A defaulted move constructor that is defined as deleted is ignored by
5941   //   overload resolution.
5942   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5943   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5944       Constructor->isMoveConstructor())
5945     return;
5946 
5947   // Overload resolution is always an unevaluated context.
5948   EnterExpressionEvaluationContext Unevaluated(
5949       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5950 
5951   // Add this candidate
5952   OverloadCandidate &Candidate =
5953       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5954   Candidate.FoundDecl = FoundDecl;
5955   Candidate.Function = Function;
5956   Candidate.Viable = true;
5957   Candidate.IsSurrogate = false;
5958   Candidate.IgnoreObjectArgument = false;
5959   Candidate.ExplicitCallArguments = Args.size();
5960 
5961   if (Function->isMultiVersion() &&
5962       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5963     Candidate.Viable = false;
5964     Candidate.FailureKind = ovl_non_default_multiversion_function;
5965     return;
5966   }
5967 
5968   if (Constructor) {
5969     // C++ [class.copy]p3:
5970     //   A member function template is never instantiated to perform the copy
5971     //   of a class object to an object of its class type.
5972     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5973     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5974         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5975          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5976                        ClassType))) {
5977       Candidate.Viable = false;
5978       Candidate.FailureKind = ovl_fail_illegal_constructor;
5979       return;
5980     }
5981 
5982     // C++ [over.match.funcs]p8: (proposed DR resolution)
5983     //   A constructor inherited from class type C that has a first parameter
5984     //   of type "reference to P" (including such a constructor instantiated
5985     //   from a template) is excluded from the set of candidate functions when
5986     //   constructing an object of type cv D if the argument list has exactly
5987     //   one argument and D is reference-related to P and P is reference-related
5988     //   to C.
5989     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5990     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5991         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5992       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5993       QualType C = Context.getRecordType(Constructor->getParent());
5994       QualType D = Context.getRecordType(Shadow->getParent());
5995       SourceLocation Loc = Args.front()->getExprLoc();
5996       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5997           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5998         Candidate.Viable = false;
5999         Candidate.FailureKind = ovl_fail_inhctor_slice;
6000         return;
6001       }
6002     }
6003   }
6004 
6005   unsigned NumParams = Proto->getNumParams();
6006 
6007   // (C++ 13.3.2p2): A candidate function having fewer than m
6008   // parameters is viable only if it has an ellipsis in its parameter
6009   // list (8.3.5).
6010   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6011       !Proto->isVariadic()) {
6012     Candidate.Viable = false;
6013     Candidate.FailureKind = ovl_fail_too_many_arguments;
6014     return;
6015   }
6016 
6017   // (C++ 13.3.2p2): A candidate function having more than m parameters
6018   // is viable only if the (m+1)st parameter has a default argument
6019   // (8.3.6). For the purposes of overload resolution, the
6020   // parameter list is truncated on the right, so that there are
6021   // exactly m parameters.
6022   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6023   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6024     // Not enough arguments.
6025     Candidate.Viable = false;
6026     Candidate.FailureKind = ovl_fail_too_few_arguments;
6027     return;
6028   }
6029 
6030   // (CUDA B.1): Check for invalid calls between targets.
6031   if (getLangOpts().CUDA)
6032     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6033       // Skip the check for callers that are implicit members, because in this
6034       // case we may not yet know what the member's target is; the target is
6035       // inferred for the member automatically, based on the bases and fields of
6036       // the class.
6037       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6038         Candidate.Viable = false;
6039         Candidate.FailureKind = ovl_fail_bad_target;
6040         return;
6041       }
6042 
6043   // Determine the implicit conversion sequences for each of the
6044   // arguments.
6045   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6046     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6047       // We already formed a conversion sequence for this parameter during
6048       // template argument deduction.
6049     } else if (ArgIdx < NumParams) {
6050       // (C++ 13.3.2p3): for F to be a viable function, there shall
6051       // exist for each argument an implicit conversion sequence
6052       // (13.3.3.1) that converts that argument to the corresponding
6053       // parameter of F.
6054       QualType ParamType = Proto->getParamType(ArgIdx);
6055       Candidate.Conversions[ArgIdx]
6056         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6057                                 SuppressUserConversions,
6058                                 /*InOverloadResolution=*/true,
6059                                 /*AllowObjCWritebackConversion=*/
6060                                   getLangOpts().ObjCAutoRefCount,
6061                                 AllowExplicit);
6062       if (Candidate.Conversions[ArgIdx].isBad()) {
6063         Candidate.Viable = false;
6064         Candidate.FailureKind = ovl_fail_bad_conversion;
6065         return;
6066       }
6067     } else {
6068       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6069       // argument for which there is no corresponding parameter is
6070       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6071       Candidate.Conversions[ArgIdx].setEllipsis();
6072     }
6073   }
6074 
6075   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6076     Candidate.Viable = false;
6077     Candidate.FailureKind = ovl_fail_enable_if;
6078     Candidate.DeductionFailure.Data = FailedAttr;
6079     return;
6080   }
6081 
6082   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6083     Candidate.Viable = false;
6084     Candidate.FailureKind = ovl_fail_ext_disabled;
6085     return;
6086   }
6087 }
6088 
6089 ObjCMethodDecl *
6090 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6091                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6092   if (Methods.size() <= 1)
6093     return nullptr;
6094 
6095   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6096     bool Match = true;
6097     ObjCMethodDecl *Method = Methods[b];
6098     unsigned NumNamedArgs = Sel.getNumArgs();
6099     // Method might have more arguments than selector indicates. This is due
6100     // to addition of c-style arguments in method.
6101     if (Method->param_size() > NumNamedArgs)
6102       NumNamedArgs = Method->param_size();
6103     if (Args.size() < NumNamedArgs)
6104       continue;
6105 
6106     for (unsigned i = 0; i < NumNamedArgs; i++) {
6107       // We can't do any type-checking on a type-dependent argument.
6108       if (Args[i]->isTypeDependent()) {
6109         Match = false;
6110         break;
6111       }
6112 
6113       ParmVarDecl *param = Method->parameters()[i];
6114       Expr *argExpr = Args[i];
6115       assert(argExpr && "SelectBestMethod(): missing expression");
6116 
6117       // Strip the unbridged-cast placeholder expression off unless it's
6118       // a consumed argument.
6119       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6120           !param->hasAttr<CFConsumedAttr>())
6121         argExpr = stripARCUnbridgedCast(argExpr);
6122 
6123       // If the parameter is __unknown_anytype, move on to the next method.
6124       if (param->getType() == Context.UnknownAnyTy) {
6125         Match = false;
6126         break;
6127       }
6128 
6129       ImplicitConversionSequence ConversionState
6130         = TryCopyInitialization(*this, argExpr, param->getType(),
6131                                 /*SuppressUserConversions*/false,
6132                                 /*InOverloadResolution=*/true,
6133                                 /*AllowObjCWritebackConversion=*/
6134                                 getLangOpts().ObjCAutoRefCount,
6135                                 /*AllowExplicit*/false);
6136       // This function looks for a reasonably-exact match, so we consider
6137       // incompatible pointer conversions to be a failure here.
6138       if (ConversionState.isBad() ||
6139           (ConversionState.isStandard() &&
6140            ConversionState.Standard.Second ==
6141                ICK_Incompatible_Pointer_Conversion)) {
6142         Match = false;
6143         break;
6144       }
6145     }
6146     // Promote additional arguments to variadic methods.
6147     if (Match && Method->isVariadic()) {
6148       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6149         if (Args[i]->isTypeDependent()) {
6150           Match = false;
6151           break;
6152         }
6153         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6154                                                           nullptr);
6155         if (Arg.isInvalid()) {
6156           Match = false;
6157           break;
6158         }
6159       }
6160     } else {
6161       // Check for extra arguments to non-variadic methods.
6162       if (Args.size() != NumNamedArgs)
6163         Match = false;
6164       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6165         // Special case when selectors have no argument. In this case, select
6166         // one with the most general result type of 'id'.
6167         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6168           QualType ReturnT = Methods[b]->getReturnType();
6169           if (ReturnT->isObjCIdType())
6170             return Methods[b];
6171         }
6172       }
6173     }
6174 
6175     if (Match)
6176       return Method;
6177   }
6178   return nullptr;
6179 }
6180 
6181 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6182 // enable_if is order-sensitive. As a result, we need to reverse things
6183 // sometimes. Size of 4 elements is arbitrary.
6184 static SmallVector<EnableIfAttr *, 4>
6185 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6186   SmallVector<EnableIfAttr *, 4> Result;
6187   if (!Function->hasAttrs())
6188     return Result;
6189 
6190   const auto &FuncAttrs = Function->getAttrs();
6191   for (Attr *Attr : FuncAttrs)
6192     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6193       Result.push_back(EnableIf);
6194 
6195   std::reverse(Result.begin(), Result.end());
6196   return Result;
6197 }
6198 
6199 static bool
6200 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6201                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6202                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6203                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6204   if (ThisArg) {
6205     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6206     assert(!isa<CXXConstructorDecl>(Method) &&
6207            "Shouldn't have `this` for ctors!");
6208     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6209     ExprResult R = S.PerformObjectArgumentInitialization(
6210         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6211     if (R.isInvalid())
6212       return false;
6213     ConvertedThis = R.get();
6214   } else {
6215     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6216       (void)MD;
6217       assert((MissingImplicitThis || MD->isStatic() ||
6218               isa<CXXConstructorDecl>(MD)) &&
6219              "Expected `this` for non-ctor instance methods");
6220     }
6221     ConvertedThis = nullptr;
6222   }
6223 
6224   // Ignore any variadic arguments. Converting them is pointless, since the
6225   // user can't refer to them in the function condition.
6226   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6227 
6228   // Convert the arguments.
6229   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6230     ExprResult R;
6231     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6232                                         S.Context, Function->getParamDecl(I)),
6233                                     SourceLocation(), Args[I]);
6234 
6235     if (R.isInvalid())
6236       return false;
6237 
6238     ConvertedArgs.push_back(R.get());
6239   }
6240 
6241   if (Trap.hasErrorOccurred())
6242     return false;
6243 
6244   // Push default arguments if needed.
6245   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6246     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6247       ParmVarDecl *P = Function->getParamDecl(i);
6248       ExprResult R = S.PerformCopyInitialization(
6249           InitializedEntity::InitializeParameter(S.Context,
6250                                                  Function->getParamDecl(i)),
6251           SourceLocation(),
6252           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6253                                            : P->getDefaultArg());
6254       if (R.isInvalid())
6255         return false;
6256       ConvertedArgs.push_back(R.get());
6257     }
6258 
6259     if (Trap.hasErrorOccurred())
6260       return false;
6261   }
6262   return true;
6263 }
6264 
6265 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6266                                   bool MissingImplicitThis) {
6267   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6268       getOrderedEnableIfAttrs(Function);
6269   if (EnableIfAttrs.empty())
6270     return nullptr;
6271 
6272   SFINAETrap Trap(*this);
6273   SmallVector<Expr *, 16> ConvertedArgs;
6274   // FIXME: We should look into making enable_if late-parsed.
6275   Expr *DiscardedThis;
6276   if (!convertArgsForAvailabilityChecks(
6277           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6278           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6279     return EnableIfAttrs[0];
6280 
6281   for (auto *EIA : EnableIfAttrs) {
6282     APValue Result;
6283     // FIXME: This doesn't consider value-dependent cases, because doing so is
6284     // very difficult. Ideally, we should handle them more gracefully.
6285     if (!EIA->getCond()->EvaluateWithSubstitution(
6286             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6287       return EIA;
6288 
6289     if (!Result.isInt() || !Result.getInt().getBoolValue())
6290       return EIA;
6291   }
6292   return nullptr;
6293 }
6294 
6295 template <typename CheckFn>
6296 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6297                                         bool ArgDependent, SourceLocation Loc,
6298                                         CheckFn &&IsSuccessful) {
6299   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6300   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6301     if (ArgDependent == DIA->getArgDependent())
6302       Attrs.push_back(DIA);
6303   }
6304 
6305   // Common case: No diagnose_if attributes, so we can quit early.
6306   if (Attrs.empty())
6307     return false;
6308 
6309   auto WarningBegin = std::stable_partition(
6310       Attrs.begin(), Attrs.end(),
6311       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6312 
6313   // Note that diagnose_if attributes are late-parsed, so they appear in the
6314   // correct order (unlike enable_if attributes).
6315   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6316                                IsSuccessful);
6317   if (ErrAttr != WarningBegin) {
6318     const DiagnoseIfAttr *DIA = *ErrAttr;
6319     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6320     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6321         << DIA->getParent() << DIA->getCond()->getSourceRange();
6322     return true;
6323   }
6324 
6325   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6326     if (IsSuccessful(DIA)) {
6327       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6328       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6329           << DIA->getParent() << DIA->getCond()->getSourceRange();
6330     }
6331 
6332   return false;
6333 }
6334 
6335 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6336                                                const Expr *ThisArg,
6337                                                ArrayRef<const Expr *> Args,
6338                                                SourceLocation Loc) {
6339   return diagnoseDiagnoseIfAttrsWith(
6340       *this, Function, /*ArgDependent=*/true, Loc,
6341       [&](const DiagnoseIfAttr *DIA) {
6342         APValue Result;
6343         // It's sane to use the same Args for any redecl of this function, since
6344         // EvaluateWithSubstitution only cares about the position of each
6345         // argument in the arg list, not the ParmVarDecl* it maps to.
6346         if (!DIA->getCond()->EvaluateWithSubstitution(
6347                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6348           return false;
6349         return Result.isInt() && Result.getInt().getBoolValue();
6350       });
6351 }
6352 
6353 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6354                                                  SourceLocation Loc) {
6355   return diagnoseDiagnoseIfAttrsWith(
6356       *this, ND, /*ArgDependent=*/false, Loc,
6357       [&](const DiagnoseIfAttr *DIA) {
6358         bool Result;
6359         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6360                Result;
6361       });
6362 }
6363 
6364 /// \brief Add all of the function declarations in the given function set to
6365 /// the overload candidate set.
6366 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6367                                  ArrayRef<Expr *> Args,
6368                                  OverloadCandidateSet& CandidateSet,
6369                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6370                                  bool SuppressUserConversions,
6371                                  bool PartialOverloading,
6372                                  bool FirstArgumentIsBase) {
6373   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6374     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6375     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6376       ArrayRef<Expr *> FunctionArgs = Args;
6377       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6378         QualType ObjectType;
6379         Expr::Classification ObjectClassification;
6380         if (Args.size() > 0) {
6381           if (Expr *E = Args[0]) {
6382             // Use the explit base to restrict the lookup:
6383             ObjectType = E->getType();
6384             ObjectClassification = E->Classify(Context);
6385           } // .. else there is an implit base.
6386           FunctionArgs = Args.slice(1);
6387         }
6388         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6389                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6390                            ObjectClassification, FunctionArgs, CandidateSet,
6391                            SuppressUserConversions, PartialOverloading);
6392       } else {
6393         // Slice the first argument (which is the base) when we access
6394         // static method as non-static
6395         if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6396                                              !isa<CXXConstructorDecl>(FD)))) {
6397           assert(cast<CXXMethodDecl>(FD)->isStatic());
6398           FunctionArgs = Args.slice(1);
6399         }
6400         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6401                              SuppressUserConversions, PartialOverloading);
6402       }
6403     } else {
6404       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6405       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6406           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6407         QualType ObjectType;
6408         Expr::Classification ObjectClassification;
6409         if (Expr *E = Args[0]) {
6410           // Use the explit base to restrict the lookup:
6411           ObjectType = E->getType();
6412           ObjectClassification = E->Classify(Context);
6413         } // .. else there is an implit base.
6414         AddMethodTemplateCandidate(
6415             FunTmpl, F.getPair(),
6416             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6417             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6418             Args.slice(1), CandidateSet, SuppressUserConversions,
6419             PartialOverloading);
6420       } else {
6421         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6422                                      ExplicitTemplateArgs, Args,
6423                                      CandidateSet, SuppressUserConversions,
6424                                      PartialOverloading);
6425       }
6426     }
6427   }
6428 }
6429 
6430 /// AddMethodCandidate - Adds a named decl (which is some kind of
6431 /// method) as a method candidate to the given overload set.
6432 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6433                               QualType ObjectType,
6434                               Expr::Classification ObjectClassification,
6435                               ArrayRef<Expr *> Args,
6436                               OverloadCandidateSet& CandidateSet,
6437                               bool SuppressUserConversions) {
6438   NamedDecl *Decl = FoundDecl.getDecl();
6439   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6440 
6441   if (isa<UsingShadowDecl>(Decl))
6442     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6443 
6444   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6445     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6446            "Expected a member function template");
6447     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6448                                /*ExplicitArgs*/ nullptr, ObjectType,
6449                                ObjectClassification, Args, CandidateSet,
6450                                SuppressUserConversions);
6451   } else {
6452     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6453                        ObjectType, ObjectClassification, Args, CandidateSet,
6454                        SuppressUserConversions);
6455   }
6456 }
6457 
6458 /// AddMethodCandidate - Adds the given C++ member function to the set
6459 /// of candidate functions, using the given function call arguments
6460 /// and the object argument (@c Object). For example, in a call
6461 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6462 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6463 /// allow user-defined conversions via constructors or conversion
6464 /// operators.
6465 void
6466 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6467                          CXXRecordDecl *ActingContext, QualType ObjectType,
6468                          Expr::Classification ObjectClassification,
6469                          ArrayRef<Expr *> Args,
6470                          OverloadCandidateSet &CandidateSet,
6471                          bool SuppressUserConversions,
6472                          bool PartialOverloading,
6473                          ConversionSequenceList EarlyConversions) {
6474   const FunctionProtoType *Proto
6475     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6476   assert(Proto && "Methods without a prototype cannot be overloaded");
6477   assert(!isa<CXXConstructorDecl>(Method) &&
6478          "Use AddOverloadCandidate for constructors");
6479 
6480   if (!CandidateSet.isNewCandidate(Method))
6481     return;
6482 
6483   // C++11 [class.copy]p23: [DR1402]
6484   //   A defaulted move assignment operator that is defined as deleted is
6485   //   ignored by overload resolution.
6486   if (Method->isDefaulted() && Method->isDeleted() &&
6487       Method->isMoveAssignmentOperator())
6488     return;
6489 
6490   // Overload resolution is always an unevaluated context.
6491   EnterExpressionEvaluationContext Unevaluated(
6492       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6493 
6494   // Add this candidate
6495   OverloadCandidate &Candidate =
6496       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6497   Candidate.FoundDecl = FoundDecl;
6498   Candidate.Function = Method;
6499   Candidate.IsSurrogate = false;
6500   Candidate.IgnoreObjectArgument = false;
6501   Candidate.ExplicitCallArguments = Args.size();
6502 
6503   unsigned NumParams = Proto->getNumParams();
6504 
6505   // (C++ 13.3.2p2): A candidate function having fewer than m
6506   // parameters is viable only if it has an ellipsis in its parameter
6507   // list (8.3.5).
6508   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6509       !Proto->isVariadic()) {
6510     Candidate.Viable = false;
6511     Candidate.FailureKind = ovl_fail_too_many_arguments;
6512     return;
6513   }
6514 
6515   // (C++ 13.3.2p2): A candidate function having more than m parameters
6516   // is viable only if the (m+1)st parameter has a default argument
6517   // (8.3.6). For the purposes of overload resolution, the
6518   // parameter list is truncated on the right, so that there are
6519   // exactly m parameters.
6520   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6521   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6522     // Not enough arguments.
6523     Candidate.Viable = false;
6524     Candidate.FailureKind = ovl_fail_too_few_arguments;
6525     return;
6526   }
6527 
6528   Candidate.Viable = true;
6529 
6530   if (Method->isStatic() || ObjectType.isNull())
6531     // The implicit object argument is ignored.
6532     Candidate.IgnoreObjectArgument = true;
6533   else {
6534     // Determine the implicit conversion sequence for the object
6535     // parameter.
6536     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6537         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6538         Method, ActingContext);
6539     if (Candidate.Conversions[0].isBad()) {
6540       Candidate.Viable = false;
6541       Candidate.FailureKind = ovl_fail_bad_conversion;
6542       return;
6543     }
6544   }
6545 
6546   // (CUDA B.1): Check for invalid calls between targets.
6547   if (getLangOpts().CUDA)
6548     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6549       if (!IsAllowedCUDACall(Caller, Method)) {
6550         Candidate.Viable = false;
6551         Candidate.FailureKind = ovl_fail_bad_target;
6552         return;
6553       }
6554 
6555   // Determine the implicit conversion sequences for each of the
6556   // arguments.
6557   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6558     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6559       // We already formed a conversion sequence for this parameter during
6560       // template argument deduction.
6561     } else if (ArgIdx < NumParams) {
6562       // (C++ 13.3.2p3): for F to be a viable function, there shall
6563       // exist for each argument an implicit conversion sequence
6564       // (13.3.3.1) that converts that argument to the corresponding
6565       // parameter of F.
6566       QualType ParamType = Proto->getParamType(ArgIdx);
6567       Candidate.Conversions[ArgIdx + 1]
6568         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6569                                 SuppressUserConversions,
6570                                 /*InOverloadResolution=*/true,
6571                                 /*AllowObjCWritebackConversion=*/
6572                                   getLangOpts().ObjCAutoRefCount);
6573       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6574         Candidate.Viable = false;
6575         Candidate.FailureKind = ovl_fail_bad_conversion;
6576         return;
6577       }
6578     } else {
6579       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6580       // argument for which there is no corresponding parameter is
6581       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6582       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6583     }
6584   }
6585 
6586   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6587     Candidate.Viable = false;
6588     Candidate.FailureKind = ovl_fail_enable_if;
6589     Candidate.DeductionFailure.Data = FailedAttr;
6590     return;
6591   }
6592 
6593   if (Method->isMultiVersion() &&
6594       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6595     Candidate.Viable = false;
6596     Candidate.FailureKind = ovl_non_default_multiversion_function;
6597   }
6598 }
6599 
6600 /// \brief Add a C++ member function template as a candidate to the candidate
6601 /// set, using template argument deduction to produce an appropriate member
6602 /// function template specialization.
6603 void
6604 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6605                                  DeclAccessPair FoundDecl,
6606                                  CXXRecordDecl *ActingContext,
6607                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6608                                  QualType ObjectType,
6609                                  Expr::Classification ObjectClassification,
6610                                  ArrayRef<Expr *> Args,
6611                                  OverloadCandidateSet& CandidateSet,
6612                                  bool SuppressUserConversions,
6613                                  bool PartialOverloading) {
6614   if (!CandidateSet.isNewCandidate(MethodTmpl))
6615     return;
6616 
6617   // C++ [over.match.funcs]p7:
6618   //   In each case where a candidate is a function template, candidate
6619   //   function template specializations are generated using template argument
6620   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6621   //   candidate functions in the usual way.113) A given name can refer to one
6622   //   or more function templates and also to a set of overloaded non-template
6623   //   functions. In such a case, the candidate functions generated from each
6624   //   function template are combined with the set of non-template candidate
6625   //   functions.
6626   TemplateDeductionInfo Info(CandidateSet.getLocation());
6627   FunctionDecl *Specialization = nullptr;
6628   ConversionSequenceList Conversions;
6629   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6630           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6631           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6632             return CheckNonDependentConversions(
6633                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6634                 SuppressUserConversions, ActingContext, ObjectType,
6635                 ObjectClassification);
6636           })) {
6637     OverloadCandidate &Candidate =
6638         CandidateSet.addCandidate(Conversions.size(), Conversions);
6639     Candidate.FoundDecl = FoundDecl;
6640     Candidate.Function = MethodTmpl->getTemplatedDecl();
6641     Candidate.Viable = false;
6642     Candidate.IsSurrogate = false;
6643     Candidate.IgnoreObjectArgument =
6644         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6645         ObjectType.isNull();
6646     Candidate.ExplicitCallArguments = Args.size();
6647     if (Result == TDK_NonDependentConversionFailure)
6648       Candidate.FailureKind = ovl_fail_bad_conversion;
6649     else {
6650       Candidate.FailureKind = ovl_fail_bad_deduction;
6651       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6652                                                             Info);
6653     }
6654     return;
6655   }
6656 
6657   // Add the function template specialization produced by template argument
6658   // deduction as a candidate.
6659   assert(Specialization && "Missing member function template specialization?");
6660   assert(isa<CXXMethodDecl>(Specialization) &&
6661          "Specialization is not a member function?");
6662   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6663                      ActingContext, ObjectType, ObjectClassification, Args,
6664                      CandidateSet, SuppressUserConversions, PartialOverloading,
6665                      Conversions);
6666 }
6667 
6668 /// \brief Add a C++ function template specialization as a candidate
6669 /// in the candidate set, using template argument deduction to produce
6670 /// an appropriate function template specialization.
6671 void
6672 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6673                                    DeclAccessPair FoundDecl,
6674                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6675                                    ArrayRef<Expr *> Args,
6676                                    OverloadCandidateSet& CandidateSet,
6677                                    bool SuppressUserConversions,
6678                                    bool PartialOverloading) {
6679   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6680     return;
6681 
6682   // C++ [over.match.funcs]p7:
6683   //   In each case where a candidate is a function template, candidate
6684   //   function template specializations are generated using template argument
6685   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6686   //   candidate functions in the usual way.113) A given name can refer to one
6687   //   or more function templates and also to a set of overloaded non-template
6688   //   functions. In such a case, the candidate functions generated from each
6689   //   function template are combined with the set of non-template candidate
6690   //   functions.
6691   TemplateDeductionInfo Info(CandidateSet.getLocation());
6692   FunctionDecl *Specialization = nullptr;
6693   ConversionSequenceList Conversions;
6694   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6695           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6696           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6697             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6698                                                 Args, CandidateSet, Conversions,
6699                                                 SuppressUserConversions);
6700           })) {
6701     OverloadCandidate &Candidate =
6702         CandidateSet.addCandidate(Conversions.size(), Conversions);
6703     Candidate.FoundDecl = FoundDecl;
6704     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6705     Candidate.Viable = false;
6706     Candidate.IsSurrogate = false;
6707     // Ignore the object argument if there is one, since we don't have an object
6708     // type.
6709     Candidate.IgnoreObjectArgument =
6710         isa<CXXMethodDecl>(Candidate.Function) &&
6711         !isa<CXXConstructorDecl>(Candidate.Function);
6712     Candidate.ExplicitCallArguments = Args.size();
6713     if (Result == TDK_NonDependentConversionFailure)
6714       Candidate.FailureKind = ovl_fail_bad_conversion;
6715     else {
6716       Candidate.FailureKind = ovl_fail_bad_deduction;
6717       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6718                                                             Info);
6719     }
6720     return;
6721   }
6722 
6723   // Add the function template specialization produced by template argument
6724   // deduction as a candidate.
6725   assert(Specialization && "Missing function template specialization?");
6726   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6727                        SuppressUserConversions, PartialOverloading,
6728                        /*AllowExplicit*/false, Conversions);
6729 }
6730 
6731 /// Check that implicit conversion sequences can be formed for each argument
6732 /// whose corresponding parameter has a non-dependent type, per DR1391's
6733 /// [temp.deduct.call]p10.
6734 bool Sema::CheckNonDependentConversions(
6735     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6736     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6737     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6738     CXXRecordDecl *ActingContext, QualType ObjectType,
6739     Expr::Classification ObjectClassification) {
6740   // FIXME: The cases in which we allow explicit conversions for constructor
6741   // arguments never consider calling a constructor template. It's not clear
6742   // that is correct.
6743   const bool AllowExplicit = false;
6744 
6745   auto *FD = FunctionTemplate->getTemplatedDecl();
6746   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6747   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6748   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6749 
6750   Conversions =
6751       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6752 
6753   // Overload resolution is always an unevaluated context.
6754   EnterExpressionEvaluationContext Unevaluated(
6755       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6756 
6757   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6758   // require that, but this check should never result in a hard error, and
6759   // overload resolution is permitted to sidestep instantiations.
6760   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6761       !ObjectType.isNull()) {
6762     Conversions[0] = TryObjectArgumentInitialization(
6763         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6764         Method, ActingContext);
6765     if (Conversions[0].isBad())
6766       return true;
6767   }
6768 
6769   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6770        ++I) {
6771     QualType ParamType = ParamTypes[I];
6772     if (!ParamType->isDependentType()) {
6773       Conversions[ThisConversions + I]
6774         = TryCopyInitialization(*this, Args[I], ParamType,
6775                                 SuppressUserConversions,
6776                                 /*InOverloadResolution=*/true,
6777                                 /*AllowObjCWritebackConversion=*/
6778                                   getLangOpts().ObjCAutoRefCount,
6779                                 AllowExplicit);
6780       if (Conversions[ThisConversions + I].isBad())
6781         return true;
6782     }
6783   }
6784 
6785   return false;
6786 }
6787 
6788 /// Determine whether this is an allowable conversion from the result
6789 /// of an explicit conversion operator to the expected type, per C++
6790 /// [over.match.conv]p1 and [over.match.ref]p1.
6791 ///
6792 /// \param ConvType The return type of the conversion function.
6793 ///
6794 /// \param ToType The type we are converting to.
6795 ///
6796 /// \param AllowObjCPointerConversion Allow a conversion from one
6797 /// Objective-C pointer to another.
6798 ///
6799 /// \returns true if the conversion is allowable, false otherwise.
6800 static bool isAllowableExplicitConversion(Sema &S,
6801                                           QualType ConvType, QualType ToType,
6802                                           bool AllowObjCPointerConversion) {
6803   QualType ToNonRefType = ToType.getNonReferenceType();
6804 
6805   // Easy case: the types are the same.
6806   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6807     return true;
6808 
6809   // Allow qualification conversions.
6810   bool ObjCLifetimeConversion;
6811   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6812                                   ObjCLifetimeConversion))
6813     return true;
6814 
6815   // If we're not allowed to consider Objective-C pointer conversions,
6816   // we're done.
6817   if (!AllowObjCPointerConversion)
6818     return false;
6819 
6820   // Is this an Objective-C pointer conversion?
6821   bool IncompatibleObjC = false;
6822   QualType ConvertedType;
6823   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6824                                    IncompatibleObjC);
6825 }
6826 
6827 /// AddConversionCandidate - Add a C++ conversion function as a
6828 /// candidate in the candidate set (C++ [over.match.conv],
6829 /// C++ [over.match.copy]). From is the expression we're converting from,
6830 /// and ToType is the type that we're eventually trying to convert to
6831 /// (which may or may not be the same type as the type that the
6832 /// conversion function produces).
6833 void
6834 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6835                              DeclAccessPair FoundDecl,
6836                              CXXRecordDecl *ActingContext,
6837                              Expr *From, QualType ToType,
6838                              OverloadCandidateSet& CandidateSet,
6839                              bool AllowObjCConversionOnExplicit,
6840                              bool AllowResultConversion) {
6841   assert(!Conversion->getDescribedFunctionTemplate() &&
6842          "Conversion function templates use AddTemplateConversionCandidate");
6843   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6844   if (!CandidateSet.isNewCandidate(Conversion))
6845     return;
6846 
6847   // If the conversion function has an undeduced return type, trigger its
6848   // deduction now.
6849   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6850     if (DeduceReturnType(Conversion, From->getExprLoc()))
6851       return;
6852     ConvType = Conversion->getConversionType().getNonReferenceType();
6853   }
6854 
6855   // If we don't allow any conversion of the result type, ignore conversion
6856   // functions that don't convert to exactly (possibly cv-qualified) T.
6857   if (!AllowResultConversion &&
6858       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6859     return;
6860 
6861   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6862   // operator is only a candidate if its return type is the target type or
6863   // can be converted to the target type with a qualification conversion.
6864   if (Conversion->isExplicit() &&
6865       !isAllowableExplicitConversion(*this, ConvType, ToType,
6866                                      AllowObjCConversionOnExplicit))
6867     return;
6868 
6869   // Overload resolution is always an unevaluated context.
6870   EnterExpressionEvaluationContext Unevaluated(
6871       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6872 
6873   // Add this candidate
6874   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6875   Candidate.FoundDecl = FoundDecl;
6876   Candidate.Function = Conversion;
6877   Candidate.IsSurrogate = false;
6878   Candidate.IgnoreObjectArgument = false;
6879   Candidate.FinalConversion.setAsIdentityConversion();
6880   Candidate.FinalConversion.setFromType(ConvType);
6881   Candidate.FinalConversion.setAllToTypes(ToType);
6882   Candidate.Viable = true;
6883   Candidate.ExplicitCallArguments = 1;
6884 
6885   // C++ [over.match.funcs]p4:
6886   //   For conversion functions, the function is considered to be a member of
6887   //   the class of the implicit implied object argument for the purpose of
6888   //   defining the type of the implicit object parameter.
6889   //
6890   // Determine the implicit conversion sequence for the implicit
6891   // object parameter.
6892   QualType ImplicitParamType = From->getType();
6893   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6894     ImplicitParamType = FromPtrType->getPointeeType();
6895   CXXRecordDecl *ConversionContext
6896     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6897 
6898   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6899       *this, CandidateSet.getLocation(), From->getType(),
6900       From->Classify(Context), Conversion, ConversionContext);
6901 
6902   if (Candidate.Conversions[0].isBad()) {
6903     Candidate.Viable = false;
6904     Candidate.FailureKind = ovl_fail_bad_conversion;
6905     return;
6906   }
6907 
6908   // We won't go through a user-defined type conversion function to convert a
6909   // derived to base as such conversions are given Conversion Rank. They only
6910   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6911   QualType FromCanon
6912     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6913   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6914   if (FromCanon == ToCanon ||
6915       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6916     Candidate.Viable = false;
6917     Candidate.FailureKind = ovl_fail_trivial_conversion;
6918     return;
6919   }
6920 
6921   // To determine what the conversion from the result of calling the
6922   // conversion function to the type we're eventually trying to
6923   // convert to (ToType), we need to synthesize a call to the
6924   // conversion function and attempt copy initialization from it. This
6925   // makes sure that we get the right semantics with respect to
6926   // lvalues/rvalues and the type. Fortunately, we can allocate this
6927   // call on the stack and we don't need its arguments to be
6928   // well-formed.
6929   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6930                             VK_LValue, From->getLocStart());
6931   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6932                                 Context.getPointerType(Conversion->getType()),
6933                                 CK_FunctionToPointerDecay,
6934                                 &ConversionRef, VK_RValue);
6935 
6936   QualType ConversionType = Conversion->getConversionType();
6937   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6938     Candidate.Viable = false;
6939     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6940     return;
6941   }
6942 
6943   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6944 
6945   // Note that it is safe to allocate CallExpr on the stack here because
6946   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6947   // allocator).
6948   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6949   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6950                 From->getLocStart());
6951   ImplicitConversionSequence ICS =
6952     TryCopyInitialization(*this, &Call, ToType,
6953                           /*SuppressUserConversions=*/true,
6954                           /*InOverloadResolution=*/false,
6955                           /*AllowObjCWritebackConversion=*/false);
6956 
6957   switch (ICS.getKind()) {
6958   case ImplicitConversionSequence::StandardConversion:
6959     Candidate.FinalConversion = ICS.Standard;
6960 
6961     // C++ [over.ics.user]p3:
6962     //   If the user-defined conversion is specified by a specialization of a
6963     //   conversion function template, the second standard conversion sequence
6964     //   shall have exact match rank.
6965     if (Conversion->getPrimaryTemplate() &&
6966         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6967       Candidate.Viable = false;
6968       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6969       return;
6970     }
6971 
6972     // C++0x [dcl.init.ref]p5:
6973     //    In the second case, if the reference is an rvalue reference and
6974     //    the second standard conversion sequence of the user-defined
6975     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6976     //    program is ill-formed.
6977     if (ToType->isRValueReferenceType() &&
6978         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6979       Candidate.Viable = false;
6980       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6981       return;
6982     }
6983     break;
6984 
6985   case ImplicitConversionSequence::BadConversion:
6986     Candidate.Viable = false;
6987     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6988     return;
6989 
6990   default:
6991     llvm_unreachable(
6992            "Can only end up with a standard conversion sequence or failure");
6993   }
6994 
6995   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6996     Candidate.Viable = false;
6997     Candidate.FailureKind = ovl_fail_enable_if;
6998     Candidate.DeductionFailure.Data = FailedAttr;
6999     return;
7000   }
7001 
7002   if (Conversion->isMultiVersion() &&
7003       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7004     Candidate.Viable = false;
7005     Candidate.FailureKind = ovl_non_default_multiversion_function;
7006   }
7007 }
7008 
7009 /// \brief Adds a conversion function template specialization
7010 /// candidate to the overload set, using template argument deduction
7011 /// to deduce the template arguments of the conversion function
7012 /// template from the type that we are converting to (C++
7013 /// [temp.deduct.conv]).
7014 void
7015 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7016                                      DeclAccessPair FoundDecl,
7017                                      CXXRecordDecl *ActingDC,
7018                                      Expr *From, QualType ToType,
7019                                      OverloadCandidateSet &CandidateSet,
7020                                      bool AllowObjCConversionOnExplicit,
7021                                      bool AllowResultConversion) {
7022   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7023          "Only conversion function templates permitted here");
7024 
7025   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7026     return;
7027 
7028   TemplateDeductionInfo Info(CandidateSet.getLocation());
7029   CXXConversionDecl *Specialization = nullptr;
7030   if (TemplateDeductionResult Result
7031         = DeduceTemplateArguments(FunctionTemplate, ToType,
7032                                   Specialization, Info)) {
7033     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7034     Candidate.FoundDecl = FoundDecl;
7035     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7036     Candidate.Viable = false;
7037     Candidate.FailureKind = ovl_fail_bad_deduction;
7038     Candidate.IsSurrogate = false;
7039     Candidate.IgnoreObjectArgument = false;
7040     Candidate.ExplicitCallArguments = 1;
7041     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7042                                                           Info);
7043     return;
7044   }
7045 
7046   // Add the conversion function template specialization produced by
7047   // template argument deduction as a candidate.
7048   assert(Specialization && "Missing function template specialization?");
7049   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7050                          CandidateSet, AllowObjCConversionOnExplicit,
7051                          AllowResultConversion);
7052 }
7053 
7054 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7055 /// converts the given @c Object to a function pointer via the
7056 /// conversion function @c Conversion, and then attempts to call it
7057 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7058 /// the type of function that we'll eventually be calling.
7059 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7060                                  DeclAccessPair FoundDecl,
7061                                  CXXRecordDecl *ActingContext,
7062                                  const FunctionProtoType *Proto,
7063                                  Expr *Object,
7064                                  ArrayRef<Expr *> Args,
7065                                  OverloadCandidateSet& CandidateSet) {
7066   if (!CandidateSet.isNewCandidate(Conversion))
7067     return;
7068 
7069   // Overload resolution is always an unevaluated context.
7070   EnterExpressionEvaluationContext Unevaluated(
7071       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7072 
7073   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7074   Candidate.FoundDecl = FoundDecl;
7075   Candidate.Function = nullptr;
7076   Candidate.Surrogate = Conversion;
7077   Candidate.Viable = true;
7078   Candidate.IsSurrogate = true;
7079   Candidate.IgnoreObjectArgument = false;
7080   Candidate.ExplicitCallArguments = Args.size();
7081 
7082   // Determine the implicit conversion sequence for the implicit
7083   // object parameter.
7084   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7085       *this, CandidateSet.getLocation(), Object->getType(),
7086       Object->Classify(Context), Conversion, ActingContext);
7087   if (ObjectInit.isBad()) {
7088     Candidate.Viable = false;
7089     Candidate.FailureKind = ovl_fail_bad_conversion;
7090     Candidate.Conversions[0] = ObjectInit;
7091     return;
7092   }
7093 
7094   // The first conversion is actually a user-defined conversion whose
7095   // first conversion is ObjectInit's standard conversion (which is
7096   // effectively a reference binding). Record it as such.
7097   Candidate.Conversions[0].setUserDefined();
7098   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7099   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7100   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7101   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7102   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7103   Candidate.Conversions[0].UserDefined.After
7104     = Candidate.Conversions[0].UserDefined.Before;
7105   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7106 
7107   // Find the
7108   unsigned NumParams = Proto->getNumParams();
7109 
7110   // (C++ 13.3.2p2): A candidate function having fewer than m
7111   // parameters is viable only if it has an ellipsis in its parameter
7112   // list (8.3.5).
7113   if (Args.size() > NumParams && !Proto->isVariadic()) {
7114     Candidate.Viable = false;
7115     Candidate.FailureKind = ovl_fail_too_many_arguments;
7116     return;
7117   }
7118 
7119   // Function types don't have any default arguments, so just check if
7120   // we have enough arguments.
7121   if (Args.size() < NumParams) {
7122     // Not enough arguments.
7123     Candidate.Viable = false;
7124     Candidate.FailureKind = ovl_fail_too_few_arguments;
7125     return;
7126   }
7127 
7128   // Determine the implicit conversion sequences for each of the
7129   // arguments.
7130   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7131     if (ArgIdx < NumParams) {
7132       // (C++ 13.3.2p3): for F to be a viable function, there shall
7133       // exist for each argument an implicit conversion sequence
7134       // (13.3.3.1) that converts that argument to the corresponding
7135       // parameter of F.
7136       QualType ParamType = Proto->getParamType(ArgIdx);
7137       Candidate.Conversions[ArgIdx + 1]
7138         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7139                                 /*SuppressUserConversions=*/false,
7140                                 /*InOverloadResolution=*/false,
7141                                 /*AllowObjCWritebackConversion=*/
7142                                   getLangOpts().ObjCAutoRefCount);
7143       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7144         Candidate.Viable = false;
7145         Candidate.FailureKind = ovl_fail_bad_conversion;
7146         return;
7147       }
7148     } else {
7149       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7150       // argument for which there is no corresponding parameter is
7151       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7152       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7153     }
7154   }
7155 
7156   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7157     Candidate.Viable = false;
7158     Candidate.FailureKind = ovl_fail_enable_if;
7159     Candidate.DeductionFailure.Data = FailedAttr;
7160     return;
7161   }
7162 }
7163 
7164 /// \brief Add overload candidates for overloaded operators that are
7165 /// member functions.
7166 ///
7167 /// Add the overloaded operator candidates that are member functions
7168 /// for the operator Op that was used in an operator expression such
7169 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7170 /// CandidateSet will store the added overload candidates. (C++
7171 /// [over.match.oper]).
7172 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7173                                        SourceLocation OpLoc,
7174                                        ArrayRef<Expr *> Args,
7175                                        OverloadCandidateSet& CandidateSet,
7176                                        SourceRange OpRange) {
7177   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7178 
7179   // C++ [over.match.oper]p3:
7180   //   For a unary operator @ with an operand of a type whose
7181   //   cv-unqualified version is T1, and for a binary operator @ with
7182   //   a left operand of a type whose cv-unqualified version is T1 and
7183   //   a right operand of a type whose cv-unqualified version is T2,
7184   //   three sets of candidate functions, designated member
7185   //   candidates, non-member candidates and built-in candidates, are
7186   //   constructed as follows:
7187   QualType T1 = Args[0]->getType();
7188 
7189   //     -- If T1 is a complete class type or a class currently being
7190   //        defined, the set of member candidates is the result of the
7191   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7192   //        the set of member candidates is empty.
7193   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7194     // Complete the type if it can be completed.
7195     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7196       return;
7197     // If the type is neither complete nor being defined, bail out now.
7198     if (!T1Rec->getDecl()->getDefinition())
7199       return;
7200 
7201     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7202     LookupQualifiedName(Operators, T1Rec->getDecl());
7203     Operators.suppressDiagnostics();
7204 
7205     for (LookupResult::iterator Oper = Operators.begin(),
7206                              OperEnd = Operators.end();
7207          Oper != OperEnd;
7208          ++Oper)
7209       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7210                          Args[0]->Classify(Context), Args.slice(1),
7211                          CandidateSet, /*SuppressUserConversions=*/false);
7212   }
7213 }
7214 
7215 /// AddBuiltinCandidate - Add a candidate for a built-in
7216 /// operator. ResultTy and ParamTys are the result and parameter types
7217 /// of the built-in candidate, respectively. Args and NumArgs are the
7218 /// arguments being passed to the candidate. IsAssignmentOperator
7219 /// should be true when this built-in candidate is an assignment
7220 /// operator. NumContextualBoolArguments is the number of arguments
7221 /// (at the beginning of the argument list) that will be contextually
7222 /// converted to bool.
7223 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7224                                OverloadCandidateSet& CandidateSet,
7225                                bool IsAssignmentOperator,
7226                                unsigned NumContextualBoolArguments) {
7227   // Overload resolution is always an unevaluated context.
7228   EnterExpressionEvaluationContext Unevaluated(
7229       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7230 
7231   // Add this candidate
7232   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7233   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7234   Candidate.Function = nullptr;
7235   Candidate.IsSurrogate = false;
7236   Candidate.IgnoreObjectArgument = false;
7237   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7238 
7239   // Determine the implicit conversion sequences for each of the
7240   // arguments.
7241   Candidate.Viable = true;
7242   Candidate.ExplicitCallArguments = Args.size();
7243   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7244     // C++ [over.match.oper]p4:
7245     //   For the built-in assignment operators, conversions of the
7246     //   left operand are restricted as follows:
7247     //     -- no temporaries are introduced to hold the left operand, and
7248     //     -- no user-defined conversions are applied to the left
7249     //        operand to achieve a type match with the left-most
7250     //        parameter of a built-in candidate.
7251     //
7252     // We block these conversions by turning off user-defined
7253     // conversions, since that is the only way that initialization of
7254     // a reference to a non-class type can occur from something that
7255     // is not of the same type.
7256     if (ArgIdx < NumContextualBoolArguments) {
7257       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7258              "Contextual conversion to bool requires bool type");
7259       Candidate.Conversions[ArgIdx]
7260         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7261     } else {
7262       Candidate.Conversions[ArgIdx]
7263         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7264                                 ArgIdx == 0 && IsAssignmentOperator,
7265                                 /*InOverloadResolution=*/false,
7266                                 /*AllowObjCWritebackConversion=*/
7267                                   getLangOpts().ObjCAutoRefCount);
7268     }
7269     if (Candidate.Conversions[ArgIdx].isBad()) {
7270       Candidate.Viable = false;
7271       Candidate.FailureKind = ovl_fail_bad_conversion;
7272       break;
7273     }
7274   }
7275 }
7276 
7277 namespace {
7278 
7279 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7280 /// candidate operator functions for built-in operators (C++
7281 /// [over.built]). The types are separated into pointer types and
7282 /// enumeration types.
7283 class BuiltinCandidateTypeSet  {
7284   /// TypeSet - A set of types.
7285   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7286                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7287 
7288   /// PointerTypes - The set of pointer types that will be used in the
7289   /// built-in candidates.
7290   TypeSet PointerTypes;
7291 
7292   /// MemberPointerTypes - The set of member pointer types that will be
7293   /// used in the built-in candidates.
7294   TypeSet MemberPointerTypes;
7295 
7296   /// EnumerationTypes - The set of enumeration types that will be
7297   /// used in the built-in candidates.
7298   TypeSet EnumerationTypes;
7299 
7300   /// \brief The set of vector types that will be used in the built-in
7301   /// candidates.
7302   TypeSet VectorTypes;
7303 
7304   /// \brief A flag indicating non-record types are viable candidates
7305   bool HasNonRecordTypes;
7306 
7307   /// \brief A flag indicating whether either arithmetic or enumeration types
7308   /// were present in the candidate set.
7309   bool HasArithmeticOrEnumeralTypes;
7310 
7311   /// \brief A flag indicating whether the nullptr type was present in the
7312   /// candidate set.
7313   bool HasNullPtrType;
7314 
7315   /// Sema - The semantic analysis instance where we are building the
7316   /// candidate type set.
7317   Sema &SemaRef;
7318 
7319   /// Context - The AST context in which we will build the type sets.
7320   ASTContext &Context;
7321 
7322   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7323                                                const Qualifiers &VisibleQuals);
7324   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7325 
7326 public:
7327   /// iterator - Iterates through the types that are part of the set.
7328   typedef TypeSet::iterator iterator;
7329 
7330   BuiltinCandidateTypeSet(Sema &SemaRef)
7331     : HasNonRecordTypes(false),
7332       HasArithmeticOrEnumeralTypes(false),
7333       HasNullPtrType(false),
7334       SemaRef(SemaRef),
7335       Context(SemaRef.Context) { }
7336 
7337   void AddTypesConvertedFrom(QualType Ty,
7338                              SourceLocation Loc,
7339                              bool AllowUserConversions,
7340                              bool AllowExplicitConversions,
7341                              const Qualifiers &VisibleTypeConversionsQuals);
7342 
7343   /// pointer_begin - First pointer type found;
7344   iterator pointer_begin() { return PointerTypes.begin(); }
7345 
7346   /// pointer_end - Past the last pointer type found;
7347   iterator pointer_end() { return PointerTypes.end(); }
7348 
7349   /// member_pointer_begin - First member pointer type found;
7350   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7351 
7352   /// member_pointer_end - Past the last member pointer type found;
7353   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7354 
7355   /// enumeration_begin - First enumeration type found;
7356   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7357 
7358   /// enumeration_end - Past the last enumeration type found;
7359   iterator enumeration_end() { return EnumerationTypes.end(); }
7360 
7361   iterator vector_begin() { return VectorTypes.begin(); }
7362   iterator vector_end() { return VectorTypes.end(); }
7363 
7364   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7365   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7366   bool hasNullPtrType() const { return HasNullPtrType; }
7367 };
7368 
7369 } // end anonymous namespace
7370 
7371 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7372 /// the set of pointer types along with any more-qualified variants of
7373 /// that type. For example, if @p Ty is "int const *", this routine
7374 /// will add "int const *", "int const volatile *", "int const
7375 /// restrict *", and "int const volatile restrict *" to the set of
7376 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7377 /// false otherwise.
7378 ///
7379 /// FIXME: what to do about extended qualifiers?
7380 bool
7381 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7382                                              const Qualifiers &VisibleQuals) {
7383 
7384   // Insert this type.
7385   if (!PointerTypes.insert(Ty))
7386     return false;
7387 
7388   QualType PointeeTy;
7389   const PointerType *PointerTy = Ty->getAs<PointerType>();
7390   bool buildObjCPtr = false;
7391   if (!PointerTy) {
7392     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7393     PointeeTy = PTy->getPointeeType();
7394     buildObjCPtr = true;
7395   } else {
7396     PointeeTy = PointerTy->getPointeeType();
7397   }
7398 
7399   // Don't add qualified variants of arrays. For one, they're not allowed
7400   // (the qualifier would sink to the element type), and for another, the
7401   // only overload situation where it matters is subscript or pointer +- int,
7402   // and those shouldn't have qualifier variants anyway.
7403   if (PointeeTy->isArrayType())
7404     return true;
7405 
7406   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7407   bool hasVolatile = VisibleQuals.hasVolatile();
7408   bool hasRestrict = VisibleQuals.hasRestrict();
7409 
7410   // Iterate through all strict supersets of BaseCVR.
7411   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7412     if ((CVR | BaseCVR) != CVR) continue;
7413     // Skip over volatile if no volatile found anywhere in the types.
7414     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7415 
7416     // Skip over restrict if no restrict found anywhere in the types, or if
7417     // the type cannot be restrict-qualified.
7418     if ((CVR & Qualifiers::Restrict) &&
7419         (!hasRestrict ||
7420          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7421       continue;
7422 
7423     // Build qualified pointee type.
7424     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7425 
7426     // Build qualified pointer type.
7427     QualType QPointerTy;
7428     if (!buildObjCPtr)
7429       QPointerTy = Context.getPointerType(QPointeeTy);
7430     else
7431       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7432 
7433     // Insert qualified pointer type.
7434     PointerTypes.insert(QPointerTy);
7435   }
7436 
7437   return true;
7438 }
7439 
7440 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7441 /// to the set of pointer types along with any more-qualified variants of
7442 /// that type. For example, if @p Ty is "int const *", this routine
7443 /// will add "int const *", "int const volatile *", "int const
7444 /// restrict *", and "int const volatile restrict *" to the set of
7445 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7446 /// false otherwise.
7447 ///
7448 /// FIXME: what to do about extended qualifiers?
7449 bool
7450 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7451     QualType Ty) {
7452   // Insert this type.
7453   if (!MemberPointerTypes.insert(Ty))
7454     return false;
7455 
7456   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7457   assert(PointerTy && "type was not a member pointer type!");
7458 
7459   QualType PointeeTy = PointerTy->getPointeeType();
7460   // Don't add qualified variants of arrays. For one, they're not allowed
7461   // (the qualifier would sink to the element type), and for another, the
7462   // only overload situation where it matters is subscript or pointer +- int,
7463   // and those shouldn't have qualifier variants anyway.
7464   if (PointeeTy->isArrayType())
7465     return true;
7466   const Type *ClassTy = PointerTy->getClass();
7467 
7468   // Iterate through all strict supersets of the pointee type's CVR
7469   // qualifiers.
7470   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7471   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7472     if ((CVR | BaseCVR) != CVR) continue;
7473 
7474     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7475     MemberPointerTypes.insert(
7476       Context.getMemberPointerType(QPointeeTy, ClassTy));
7477   }
7478 
7479   return true;
7480 }
7481 
7482 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7483 /// Ty can be implicit converted to the given set of @p Types. We're
7484 /// primarily interested in pointer types and enumeration types. We also
7485 /// take member pointer types, for the conditional operator.
7486 /// AllowUserConversions is true if we should look at the conversion
7487 /// functions of a class type, and AllowExplicitConversions if we
7488 /// should also include the explicit conversion functions of a class
7489 /// type.
7490 void
7491 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7492                                                SourceLocation Loc,
7493                                                bool AllowUserConversions,
7494                                                bool AllowExplicitConversions,
7495                                                const Qualifiers &VisibleQuals) {
7496   // Only deal with canonical types.
7497   Ty = Context.getCanonicalType(Ty);
7498 
7499   // Look through reference types; they aren't part of the type of an
7500   // expression for the purposes of conversions.
7501   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7502     Ty = RefTy->getPointeeType();
7503 
7504   // If we're dealing with an array type, decay to the pointer.
7505   if (Ty->isArrayType())
7506     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7507 
7508   // Otherwise, we don't care about qualifiers on the type.
7509   Ty = Ty.getLocalUnqualifiedType();
7510 
7511   // Flag if we ever add a non-record type.
7512   const RecordType *TyRec = Ty->getAs<RecordType>();
7513   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7514 
7515   // Flag if we encounter an arithmetic type.
7516   HasArithmeticOrEnumeralTypes =
7517     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7518 
7519   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7520     PointerTypes.insert(Ty);
7521   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7522     // Insert our type, and its more-qualified variants, into the set
7523     // of types.
7524     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7525       return;
7526   } else if (Ty->isMemberPointerType()) {
7527     // Member pointers are far easier, since the pointee can't be converted.
7528     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7529       return;
7530   } else if (Ty->isEnumeralType()) {
7531     HasArithmeticOrEnumeralTypes = true;
7532     EnumerationTypes.insert(Ty);
7533   } else if (Ty->isVectorType()) {
7534     // We treat vector types as arithmetic types in many contexts as an
7535     // extension.
7536     HasArithmeticOrEnumeralTypes = true;
7537     VectorTypes.insert(Ty);
7538   } else if (Ty->isNullPtrType()) {
7539     HasNullPtrType = true;
7540   } else if (AllowUserConversions && TyRec) {
7541     // No conversion functions in incomplete types.
7542     if (!SemaRef.isCompleteType(Loc, Ty))
7543       return;
7544 
7545     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7546     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7547       if (isa<UsingShadowDecl>(D))
7548         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7549 
7550       // Skip conversion function templates; they don't tell us anything
7551       // about which builtin types we can convert to.
7552       if (isa<FunctionTemplateDecl>(D))
7553         continue;
7554 
7555       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7556       if (AllowExplicitConversions || !Conv->isExplicit()) {
7557         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7558                               VisibleQuals);
7559       }
7560     }
7561   }
7562 }
7563 
7564 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7565 /// the volatile- and non-volatile-qualified assignment operators for the
7566 /// given type to the candidate set.
7567 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7568                                                    QualType T,
7569                                                    ArrayRef<Expr *> Args,
7570                                     OverloadCandidateSet &CandidateSet) {
7571   QualType ParamTypes[2];
7572 
7573   // T& operator=(T&, T)
7574   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7575   ParamTypes[1] = T;
7576   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7577                         /*IsAssignmentOperator=*/true);
7578 
7579   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7580     // volatile T& operator=(volatile T&, T)
7581     ParamTypes[0]
7582       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7583     ParamTypes[1] = T;
7584     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7585                           /*IsAssignmentOperator=*/true);
7586   }
7587 }
7588 
7589 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7590 /// if any, found in visible type conversion functions found in ArgExpr's type.
7591 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7592     Qualifiers VRQuals;
7593     const RecordType *TyRec;
7594     if (const MemberPointerType *RHSMPType =
7595         ArgExpr->getType()->getAs<MemberPointerType>())
7596       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7597     else
7598       TyRec = ArgExpr->getType()->getAs<RecordType>();
7599     if (!TyRec) {
7600       // Just to be safe, assume the worst case.
7601       VRQuals.addVolatile();
7602       VRQuals.addRestrict();
7603       return VRQuals;
7604     }
7605 
7606     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7607     if (!ClassDecl->hasDefinition())
7608       return VRQuals;
7609 
7610     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7611       if (isa<UsingShadowDecl>(D))
7612         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7613       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7614         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7615         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7616           CanTy = ResTypeRef->getPointeeType();
7617         // Need to go down the pointer/mempointer chain and add qualifiers
7618         // as see them.
7619         bool done = false;
7620         while (!done) {
7621           if (CanTy.isRestrictQualified())
7622             VRQuals.addRestrict();
7623           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7624             CanTy = ResTypePtr->getPointeeType();
7625           else if (const MemberPointerType *ResTypeMPtr =
7626                 CanTy->getAs<MemberPointerType>())
7627             CanTy = ResTypeMPtr->getPointeeType();
7628           else
7629             done = true;
7630           if (CanTy.isVolatileQualified())
7631             VRQuals.addVolatile();
7632           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7633             return VRQuals;
7634         }
7635       }
7636     }
7637     return VRQuals;
7638 }
7639 
7640 namespace {
7641 
7642 /// \brief Helper class to manage the addition of builtin operator overload
7643 /// candidates. It provides shared state and utility methods used throughout
7644 /// the process, as well as a helper method to add each group of builtin
7645 /// operator overloads from the standard to a candidate set.
7646 class BuiltinOperatorOverloadBuilder {
7647   // Common instance state available to all overload candidate addition methods.
7648   Sema &S;
7649   ArrayRef<Expr *> Args;
7650   Qualifiers VisibleTypeConversionsQuals;
7651   bool HasArithmeticOrEnumeralCandidateType;
7652   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7653   OverloadCandidateSet &CandidateSet;
7654 
7655   static constexpr int ArithmeticTypesCap = 24;
7656   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7657 
7658   // Define some indices used to iterate over the arithemetic types in
7659   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7660   // types are that preserved by promotion (C++ [over.built]p2).
7661   unsigned FirstIntegralType,
7662            LastIntegralType;
7663   unsigned FirstPromotedIntegralType,
7664            LastPromotedIntegralType;
7665   unsigned FirstPromotedArithmeticType,
7666            LastPromotedArithmeticType;
7667   unsigned NumArithmeticTypes;
7668 
7669   void InitArithmeticTypes() {
7670     // Start of promoted types.
7671     FirstPromotedArithmeticType = 0;
7672     ArithmeticTypes.push_back(S.Context.FloatTy);
7673     ArithmeticTypes.push_back(S.Context.DoubleTy);
7674     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7675     if (S.Context.getTargetInfo().hasFloat128Type())
7676       ArithmeticTypes.push_back(S.Context.Float128Ty);
7677 
7678     // Start of integral types.
7679     FirstIntegralType = ArithmeticTypes.size();
7680     FirstPromotedIntegralType = ArithmeticTypes.size();
7681     ArithmeticTypes.push_back(S.Context.IntTy);
7682     ArithmeticTypes.push_back(S.Context.LongTy);
7683     ArithmeticTypes.push_back(S.Context.LongLongTy);
7684     if (S.Context.getTargetInfo().hasInt128Type())
7685       ArithmeticTypes.push_back(S.Context.Int128Ty);
7686     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7687     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7688     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7689     if (S.Context.getTargetInfo().hasInt128Type())
7690       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7691     LastPromotedIntegralType = ArithmeticTypes.size();
7692     LastPromotedArithmeticType = ArithmeticTypes.size();
7693     // End of promoted types.
7694 
7695     ArithmeticTypes.push_back(S.Context.BoolTy);
7696     ArithmeticTypes.push_back(S.Context.CharTy);
7697     ArithmeticTypes.push_back(S.Context.WCharTy);
7698     ArithmeticTypes.push_back(S.Context.Char16Ty);
7699     ArithmeticTypes.push_back(S.Context.Char32Ty);
7700     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7701     ArithmeticTypes.push_back(S.Context.ShortTy);
7702     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7703     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7704     LastIntegralType = ArithmeticTypes.size();
7705     NumArithmeticTypes = ArithmeticTypes.size();
7706     // End of integral types.
7707     // FIXME: What about complex? What about half?
7708 
7709     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7710            "Enough inline storage for all arithmetic types.");
7711   }
7712 
7713   /// \brief Helper method to factor out the common pattern of adding overloads
7714   /// for '++' and '--' builtin operators.
7715   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7716                                            bool HasVolatile,
7717                                            bool HasRestrict) {
7718     QualType ParamTypes[2] = {
7719       S.Context.getLValueReferenceType(CandidateTy),
7720       S.Context.IntTy
7721     };
7722 
7723     // Non-volatile version.
7724     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7725 
7726     // Use a heuristic to reduce number of builtin candidates in the set:
7727     // add volatile version only if there are conversions to a volatile type.
7728     if (HasVolatile) {
7729       ParamTypes[0] =
7730         S.Context.getLValueReferenceType(
7731           S.Context.getVolatileType(CandidateTy));
7732       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7733     }
7734 
7735     // Add restrict version only if there are conversions to a restrict type
7736     // and our candidate type is a non-restrict-qualified pointer.
7737     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7738         !CandidateTy.isRestrictQualified()) {
7739       ParamTypes[0]
7740         = S.Context.getLValueReferenceType(
7741             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7742       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7743 
7744       if (HasVolatile) {
7745         ParamTypes[0]
7746           = S.Context.getLValueReferenceType(
7747               S.Context.getCVRQualifiedType(CandidateTy,
7748                                             (Qualifiers::Volatile |
7749                                              Qualifiers::Restrict)));
7750         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7751       }
7752     }
7753 
7754   }
7755 
7756 public:
7757   BuiltinOperatorOverloadBuilder(
7758     Sema &S, ArrayRef<Expr *> Args,
7759     Qualifiers VisibleTypeConversionsQuals,
7760     bool HasArithmeticOrEnumeralCandidateType,
7761     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7762     OverloadCandidateSet &CandidateSet)
7763     : S(S), Args(Args),
7764       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7765       HasArithmeticOrEnumeralCandidateType(
7766         HasArithmeticOrEnumeralCandidateType),
7767       CandidateTypes(CandidateTypes),
7768       CandidateSet(CandidateSet) {
7769 
7770     InitArithmeticTypes();
7771   }
7772 
7773   // C++ [over.built]p3:
7774   //
7775   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7776   //   is either volatile or empty, there exist candidate operator
7777   //   functions of the form
7778   //
7779   //       VQ T&      operator++(VQ T&);
7780   //       T          operator++(VQ T&, int);
7781   //
7782   // C++ [over.built]p4:
7783   //
7784   //   For every pair (T, VQ), where T is an arithmetic type other
7785   //   than bool, and VQ is either volatile or empty, there exist
7786   //   candidate operator functions of the form
7787   //
7788   //       VQ T&      operator--(VQ T&);
7789   //       T          operator--(VQ T&, int);
7790   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7791     if (!HasArithmeticOrEnumeralCandidateType)
7792       return;
7793 
7794     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7795          Arith < NumArithmeticTypes; ++Arith) {
7796       addPlusPlusMinusMinusStyleOverloads(
7797         ArithmeticTypes[Arith],
7798         VisibleTypeConversionsQuals.hasVolatile(),
7799         VisibleTypeConversionsQuals.hasRestrict());
7800     }
7801   }
7802 
7803   // C++ [over.built]p5:
7804   //
7805   //   For every pair (T, VQ), where T is a cv-qualified or
7806   //   cv-unqualified object type, and VQ is either volatile or
7807   //   empty, there exist candidate operator functions of the form
7808   //
7809   //       T*VQ&      operator++(T*VQ&);
7810   //       T*VQ&      operator--(T*VQ&);
7811   //       T*         operator++(T*VQ&, int);
7812   //       T*         operator--(T*VQ&, int);
7813   void addPlusPlusMinusMinusPointerOverloads() {
7814     for (BuiltinCandidateTypeSet::iterator
7815               Ptr = CandidateTypes[0].pointer_begin(),
7816            PtrEnd = CandidateTypes[0].pointer_end();
7817          Ptr != PtrEnd; ++Ptr) {
7818       // Skip pointer types that aren't pointers to object types.
7819       if (!(*Ptr)->getPointeeType()->isObjectType())
7820         continue;
7821 
7822       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7823         (!(*Ptr).isVolatileQualified() &&
7824          VisibleTypeConversionsQuals.hasVolatile()),
7825         (!(*Ptr).isRestrictQualified() &&
7826          VisibleTypeConversionsQuals.hasRestrict()));
7827     }
7828   }
7829 
7830   // C++ [over.built]p6:
7831   //   For every cv-qualified or cv-unqualified object type T, there
7832   //   exist candidate operator functions of the form
7833   //
7834   //       T&         operator*(T*);
7835   //
7836   // C++ [over.built]p7:
7837   //   For every function type T that does not have cv-qualifiers or a
7838   //   ref-qualifier, there exist candidate operator functions of the form
7839   //       T&         operator*(T*);
7840   void addUnaryStarPointerOverloads() {
7841     for (BuiltinCandidateTypeSet::iterator
7842               Ptr = CandidateTypes[0].pointer_begin(),
7843            PtrEnd = CandidateTypes[0].pointer_end();
7844          Ptr != PtrEnd; ++Ptr) {
7845       QualType ParamTy = *Ptr;
7846       QualType PointeeTy = ParamTy->getPointeeType();
7847       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7848         continue;
7849 
7850       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7851         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7852           continue;
7853 
7854       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7855     }
7856   }
7857 
7858   // C++ [over.built]p9:
7859   //  For every promoted arithmetic type T, there exist candidate
7860   //  operator functions of the form
7861   //
7862   //       T         operator+(T);
7863   //       T         operator-(T);
7864   void addUnaryPlusOrMinusArithmeticOverloads() {
7865     if (!HasArithmeticOrEnumeralCandidateType)
7866       return;
7867 
7868     for (unsigned Arith = FirstPromotedArithmeticType;
7869          Arith < LastPromotedArithmeticType; ++Arith) {
7870       QualType ArithTy = ArithmeticTypes[Arith];
7871       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7872     }
7873 
7874     // Extension: We also add these operators for vector types.
7875     for (BuiltinCandidateTypeSet::iterator
7876               Vec = CandidateTypes[0].vector_begin(),
7877            VecEnd = CandidateTypes[0].vector_end();
7878          Vec != VecEnd; ++Vec) {
7879       QualType VecTy = *Vec;
7880       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7881     }
7882   }
7883 
7884   // C++ [over.built]p8:
7885   //   For every type T, there exist candidate operator functions of
7886   //   the form
7887   //
7888   //       T*         operator+(T*);
7889   void addUnaryPlusPointerOverloads() {
7890     for (BuiltinCandidateTypeSet::iterator
7891               Ptr = CandidateTypes[0].pointer_begin(),
7892            PtrEnd = CandidateTypes[0].pointer_end();
7893          Ptr != PtrEnd; ++Ptr) {
7894       QualType ParamTy = *Ptr;
7895       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7896     }
7897   }
7898 
7899   // C++ [over.built]p10:
7900   //   For every promoted integral type T, there exist candidate
7901   //   operator functions of the form
7902   //
7903   //        T         operator~(T);
7904   void addUnaryTildePromotedIntegralOverloads() {
7905     if (!HasArithmeticOrEnumeralCandidateType)
7906       return;
7907 
7908     for (unsigned Int = FirstPromotedIntegralType;
7909          Int < LastPromotedIntegralType; ++Int) {
7910       QualType IntTy = ArithmeticTypes[Int];
7911       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7912     }
7913 
7914     // Extension: We also add this operator for vector types.
7915     for (BuiltinCandidateTypeSet::iterator
7916               Vec = CandidateTypes[0].vector_begin(),
7917            VecEnd = CandidateTypes[0].vector_end();
7918          Vec != VecEnd; ++Vec) {
7919       QualType VecTy = *Vec;
7920       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7921     }
7922   }
7923 
7924   // C++ [over.match.oper]p16:
7925   //   For every pointer to member type T or type std::nullptr_t, there
7926   //   exist candidate operator functions of the form
7927   //
7928   //        bool operator==(T,T);
7929   //        bool operator!=(T,T);
7930   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7931     /// Set of (canonical) types that we've already handled.
7932     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7933 
7934     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7935       for (BuiltinCandidateTypeSet::iterator
7936                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7937              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7938            MemPtr != MemPtrEnd;
7939            ++MemPtr) {
7940         // Don't add the same builtin candidate twice.
7941         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7942           continue;
7943 
7944         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7945         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7946       }
7947 
7948       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7949         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7950         if (AddedTypes.insert(NullPtrTy).second) {
7951           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7952           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7953         }
7954       }
7955     }
7956   }
7957 
7958   // C++ [over.built]p15:
7959   //
7960   //   For every T, where T is an enumeration type or a pointer type,
7961   //   there exist candidate operator functions of the form
7962   //
7963   //        bool       operator<(T, T);
7964   //        bool       operator>(T, T);
7965   //        bool       operator<=(T, T);
7966   //        bool       operator>=(T, T);
7967   //        bool       operator==(T, T);
7968   //        bool       operator!=(T, T);
7969   void addRelationalPointerOrEnumeralOverloads() {
7970     // C++ [over.match.oper]p3:
7971     //   [...]the built-in candidates include all of the candidate operator
7972     //   functions defined in 13.6 that, compared to the given operator, [...]
7973     //   do not have the same parameter-type-list as any non-template non-member
7974     //   candidate.
7975     //
7976     // Note that in practice, this only affects enumeration types because there
7977     // aren't any built-in candidates of record type, and a user-defined operator
7978     // must have an operand of record or enumeration type. Also, the only other
7979     // overloaded operator with enumeration arguments, operator=,
7980     // cannot be overloaded for enumeration types, so this is the only place
7981     // where we must suppress candidates like this.
7982     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7983       UserDefinedBinaryOperators;
7984 
7985     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7986       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7987           CandidateTypes[ArgIdx].enumeration_end()) {
7988         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7989                                          CEnd = CandidateSet.end();
7990              C != CEnd; ++C) {
7991           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7992             continue;
7993 
7994           if (C->Function->isFunctionTemplateSpecialization())
7995             continue;
7996 
7997           QualType FirstParamType =
7998             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7999           QualType SecondParamType =
8000             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8001 
8002           // Skip if either parameter isn't of enumeral type.
8003           if (!FirstParamType->isEnumeralType() ||
8004               !SecondParamType->isEnumeralType())
8005             continue;
8006 
8007           // Add this operator to the set of known user-defined operators.
8008           UserDefinedBinaryOperators.insert(
8009             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8010                            S.Context.getCanonicalType(SecondParamType)));
8011         }
8012       }
8013     }
8014 
8015     /// Set of (canonical) types that we've already handled.
8016     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8017 
8018     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8019       for (BuiltinCandidateTypeSet::iterator
8020                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8021              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8022            Ptr != PtrEnd; ++Ptr) {
8023         // Don't add the same builtin candidate twice.
8024         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8025           continue;
8026 
8027         QualType ParamTypes[2] = { *Ptr, *Ptr };
8028         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8029       }
8030       for (BuiltinCandidateTypeSet::iterator
8031                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8032              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8033            Enum != EnumEnd; ++Enum) {
8034         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8035 
8036         // Don't add the same builtin candidate twice, or if a user defined
8037         // candidate exists.
8038         if (!AddedTypes.insert(CanonType).second ||
8039             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8040                                                             CanonType)))
8041           continue;
8042 
8043         QualType ParamTypes[2] = { *Enum, *Enum };
8044         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8045       }
8046     }
8047   }
8048 
8049   // C++ [over.built]p13:
8050   //
8051   //   For every cv-qualified or cv-unqualified object type T
8052   //   there exist candidate operator functions of the form
8053   //
8054   //      T*         operator+(T*, ptrdiff_t);
8055   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8056   //      T*         operator-(T*, ptrdiff_t);
8057   //      T*         operator+(ptrdiff_t, T*);
8058   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8059   //
8060   // C++ [over.built]p14:
8061   //
8062   //   For every T, where T is a pointer to object type, there
8063   //   exist candidate operator functions of the form
8064   //
8065   //      ptrdiff_t  operator-(T, T);
8066   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8067     /// Set of (canonical) types that we've already handled.
8068     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8069 
8070     for (int Arg = 0; Arg < 2; ++Arg) {
8071       QualType AsymmetricParamTypes[2] = {
8072         S.Context.getPointerDiffType(),
8073         S.Context.getPointerDiffType(),
8074       };
8075       for (BuiltinCandidateTypeSet::iterator
8076                 Ptr = CandidateTypes[Arg].pointer_begin(),
8077              PtrEnd = CandidateTypes[Arg].pointer_end();
8078            Ptr != PtrEnd; ++Ptr) {
8079         QualType PointeeTy = (*Ptr)->getPointeeType();
8080         if (!PointeeTy->isObjectType())
8081           continue;
8082 
8083         AsymmetricParamTypes[Arg] = *Ptr;
8084         if (Arg == 0 || Op == OO_Plus) {
8085           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8086           // T* operator+(ptrdiff_t, T*);
8087           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8088         }
8089         if (Op == OO_Minus) {
8090           // ptrdiff_t operator-(T, T);
8091           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8092             continue;
8093 
8094           QualType ParamTypes[2] = { *Ptr, *Ptr };
8095           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8096         }
8097       }
8098     }
8099   }
8100 
8101   // C++ [over.built]p12:
8102   //
8103   //   For every pair of promoted arithmetic types L and R, there
8104   //   exist candidate operator functions of the form
8105   //
8106   //        LR         operator*(L, R);
8107   //        LR         operator/(L, R);
8108   //        LR         operator+(L, R);
8109   //        LR         operator-(L, R);
8110   //        bool       operator<(L, R);
8111   //        bool       operator>(L, R);
8112   //        bool       operator<=(L, R);
8113   //        bool       operator>=(L, R);
8114   //        bool       operator==(L, R);
8115   //        bool       operator!=(L, R);
8116   //
8117   //   where LR is the result of the usual arithmetic conversions
8118   //   between types L and R.
8119   //
8120   // C++ [over.built]p24:
8121   //
8122   //   For every pair of promoted arithmetic types L and R, there exist
8123   //   candidate operator functions of the form
8124   //
8125   //        LR       operator?(bool, L, R);
8126   //
8127   //   where LR is the result of the usual arithmetic conversions
8128   //   between types L and R.
8129   // Our candidates ignore the first parameter.
8130   void addGenericBinaryArithmeticOverloads() {
8131     if (!HasArithmeticOrEnumeralCandidateType)
8132       return;
8133 
8134     for (unsigned Left = FirstPromotedArithmeticType;
8135          Left < LastPromotedArithmeticType; ++Left) {
8136       for (unsigned Right = FirstPromotedArithmeticType;
8137            Right < LastPromotedArithmeticType; ++Right) {
8138         QualType LandR[2] = { ArithmeticTypes[Left],
8139                               ArithmeticTypes[Right] };
8140         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8141       }
8142     }
8143 
8144     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8145     // conditional operator for vector types.
8146     for (BuiltinCandidateTypeSet::iterator
8147               Vec1 = CandidateTypes[0].vector_begin(),
8148            Vec1End = CandidateTypes[0].vector_end();
8149          Vec1 != Vec1End; ++Vec1) {
8150       for (BuiltinCandidateTypeSet::iterator
8151                 Vec2 = CandidateTypes[1].vector_begin(),
8152              Vec2End = CandidateTypes[1].vector_end();
8153            Vec2 != Vec2End; ++Vec2) {
8154         QualType LandR[2] = { *Vec1, *Vec2 };
8155         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8156       }
8157     }
8158   }
8159 
8160   // C++ [over.built]p17:
8161   //
8162   //   For every pair of promoted integral types L and R, there
8163   //   exist candidate operator functions of the form
8164   //
8165   //      LR         operator%(L, R);
8166   //      LR         operator&(L, R);
8167   //      LR         operator^(L, R);
8168   //      LR         operator|(L, R);
8169   //      L          operator<<(L, R);
8170   //      L          operator>>(L, R);
8171   //
8172   //   where LR is the result of the usual arithmetic conversions
8173   //   between types L and R.
8174   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8175     if (!HasArithmeticOrEnumeralCandidateType)
8176       return;
8177 
8178     for (unsigned Left = FirstPromotedIntegralType;
8179          Left < LastPromotedIntegralType; ++Left) {
8180       for (unsigned Right = FirstPromotedIntegralType;
8181            Right < LastPromotedIntegralType; ++Right) {
8182         QualType LandR[2] = { ArithmeticTypes[Left],
8183                               ArithmeticTypes[Right] };
8184         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8185       }
8186     }
8187   }
8188 
8189   // C++ [over.built]p20:
8190   //
8191   //   For every pair (T, VQ), where T is an enumeration or
8192   //   pointer to member type and VQ is either volatile or
8193   //   empty, there exist candidate operator functions of the form
8194   //
8195   //        VQ T&      operator=(VQ T&, T);
8196   void addAssignmentMemberPointerOrEnumeralOverloads() {
8197     /// Set of (canonical) types that we've already handled.
8198     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8199 
8200     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8201       for (BuiltinCandidateTypeSet::iterator
8202                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8203              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8204            Enum != EnumEnd; ++Enum) {
8205         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8206           continue;
8207 
8208         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8209       }
8210 
8211       for (BuiltinCandidateTypeSet::iterator
8212                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8213              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8214            MemPtr != MemPtrEnd; ++MemPtr) {
8215         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8216           continue;
8217 
8218         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8219       }
8220     }
8221   }
8222 
8223   // C++ [over.built]p19:
8224   //
8225   //   For every pair (T, VQ), where T is any type and VQ is either
8226   //   volatile or empty, there exist candidate operator functions
8227   //   of the form
8228   //
8229   //        T*VQ&      operator=(T*VQ&, T*);
8230   //
8231   // C++ [over.built]p21:
8232   //
8233   //   For every pair (T, VQ), where T is a cv-qualified or
8234   //   cv-unqualified object type and VQ is either volatile or
8235   //   empty, there exist candidate operator functions of the form
8236   //
8237   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8238   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8239   void addAssignmentPointerOverloads(bool isEqualOp) {
8240     /// Set of (canonical) types that we've already handled.
8241     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8242 
8243     for (BuiltinCandidateTypeSet::iterator
8244               Ptr = CandidateTypes[0].pointer_begin(),
8245            PtrEnd = CandidateTypes[0].pointer_end();
8246          Ptr != PtrEnd; ++Ptr) {
8247       // If this is operator=, keep track of the builtin candidates we added.
8248       if (isEqualOp)
8249         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8250       else if (!(*Ptr)->getPointeeType()->isObjectType())
8251         continue;
8252 
8253       // non-volatile version
8254       QualType ParamTypes[2] = {
8255         S.Context.getLValueReferenceType(*Ptr),
8256         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8257       };
8258       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8259                             /*IsAssigmentOperator=*/ isEqualOp);
8260 
8261       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8262                           VisibleTypeConversionsQuals.hasVolatile();
8263       if (NeedVolatile) {
8264         // volatile version
8265         ParamTypes[0] =
8266           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8267         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8268                               /*IsAssigmentOperator=*/isEqualOp);
8269       }
8270 
8271       if (!(*Ptr).isRestrictQualified() &&
8272           VisibleTypeConversionsQuals.hasRestrict()) {
8273         // restrict version
8274         ParamTypes[0]
8275           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8276         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8277                               /*IsAssigmentOperator=*/isEqualOp);
8278 
8279         if (NeedVolatile) {
8280           // volatile restrict version
8281           ParamTypes[0]
8282             = S.Context.getLValueReferenceType(
8283                 S.Context.getCVRQualifiedType(*Ptr,
8284                                               (Qualifiers::Volatile |
8285                                                Qualifiers::Restrict)));
8286           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8287                                 /*IsAssigmentOperator=*/isEqualOp);
8288         }
8289       }
8290     }
8291 
8292     if (isEqualOp) {
8293       for (BuiltinCandidateTypeSet::iterator
8294                 Ptr = CandidateTypes[1].pointer_begin(),
8295              PtrEnd = CandidateTypes[1].pointer_end();
8296            Ptr != PtrEnd; ++Ptr) {
8297         // Make sure we don't add the same candidate twice.
8298         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8299           continue;
8300 
8301         QualType ParamTypes[2] = {
8302           S.Context.getLValueReferenceType(*Ptr),
8303           *Ptr,
8304         };
8305 
8306         // non-volatile version
8307         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8308                               /*IsAssigmentOperator=*/true);
8309 
8310         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8311                            VisibleTypeConversionsQuals.hasVolatile();
8312         if (NeedVolatile) {
8313           // volatile version
8314           ParamTypes[0] =
8315             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8316           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8317                                 /*IsAssigmentOperator=*/true);
8318         }
8319 
8320         if (!(*Ptr).isRestrictQualified() &&
8321             VisibleTypeConversionsQuals.hasRestrict()) {
8322           // restrict version
8323           ParamTypes[0]
8324             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8325           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8326                                 /*IsAssigmentOperator=*/true);
8327 
8328           if (NeedVolatile) {
8329             // volatile restrict version
8330             ParamTypes[0]
8331               = S.Context.getLValueReferenceType(
8332                   S.Context.getCVRQualifiedType(*Ptr,
8333                                                 (Qualifiers::Volatile |
8334                                                  Qualifiers::Restrict)));
8335             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8336                                   /*IsAssigmentOperator=*/true);
8337           }
8338         }
8339       }
8340     }
8341   }
8342 
8343   // C++ [over.built]p18:
8344   //
8345   //   For every triple (L, VQ, R), where L is an arithmetic type,
8346   //   VQ is either volatile or empty, and R is a promoted
8347   //   arithmetic type, there exist candidate operator functions of
8348   //   the form
8349   //
8350   //        VQ L&      operator=(VQ L&, R);
8351   //        VQ L&      operator*=(VQ L&, R);
8352   //        VQ L&      operator/=(VQ L&, R);
8353   //        VQ L&      operator+=(VQ L&, R);
8354   //        VQ L&      operator-=(VQ L&, R);
8355   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8356     if (!HasArithmeticOrEnumeralCandidateType)
8357       return;
8358 
8359     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8360       for (unsigned Right = FirstPromotedArithmeticType;
8361            Right < LastPromotedArithmeticType; ++Right) {
8362         QualType ParamTypes[2];
8363         ParamTypes[1] = ArithmeticTypes[Right];
8364 
8365         // Add this built-in operator as a candidate (VQ is empty).
8366         ParamTypes[0] =
8367           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8368         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8369                               /*IsAssigmentOperator=*/isEqualOp);
8370 
8371         // Add this built-in operator as a candidate (VQ is 'volatile').
8372         if (VisibleTypeConversionsQuals.hasVolatile()) {
8373           ParamTypes[0] =
8374             S.Context.getVolatileType(ArithmeticTypes[Left]);
8375           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8376           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8377                                 /*IsAssigmentOperator=*/isEqualOp);
8378         }
8379       }
8380     }
8381 
8382     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8383     for (BuiltinCandidateTypeSet::iterator
8384               Vec1 = CandidateTypes[0].vector_begin(),
8385            Vec1End = CandidateTypes[0].vector_end();
8386          Vec1 != Vec1End; ++Vec1) {
8387       for (BuiltinCandidateTypeSet::iterator
8388                 Vec2 = CandidateTypes[1].vector_begin(),
8389              Vec2End = CandidateTypes[1].vector_end();
8390            Vec2 != Vec2End; ++Vec2) {
8391         QualType ParamTypes[2];
8392         ParamTypes[1] = *Vec2;
8393         // Add this built-in operator as a candidate (VQ is empty).
8394         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8395         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8396                               /*IsAssigmentOperator=*/isEqualOp);
8397 
8398         // Add this built-in operator as a candidate (VQ is 'volatile').
8399         if (VisibleTypeConversionsQuals.hasVolatile()) {
8400           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8401           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8402           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8403                                 /*IsAssigmentOperator=*/isEqualOp);
8404         }
8405       }
8406     }
8407   }
8408 
8409   // C++ [over.built]p22:
8410   //
8411   //   For every triple (L, VQ, R), where L is an integral type, VQ
8412   //   is either volatile or empty, and R is a promoted integral
8413   //   type, there exist candidate operator functions of the form
8414   //
8415   //        VQ L&       operator%=(VQ L&, R);
8416   //        VQ L&       operator<<=(VQ L&, R);
8417   //        VQ L&       operator>>=(VQ L&, R);
8418   //        VQ L&       operator&=(VQ L&, R);
8419   //        VQ L&       operator^=(VQ L&, R);
8420   //        VQ L&       operator|=(VQ L&, R);
8421   void addAssignmentIntegralOverloads() {
8422     if (!HasArithmeticOrEnumeralCandidateType)
8423       return;
8424 
8425     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8426       for (unsigned Right = FirstPromotedIntegralType;
8427            Right < LastPromotedIntegralType; ++Right) {
8428         QualType ParamTypes[2];
8429         ParamTypes[1] = ArithmeticTypes[Right];
8430 
8431         // Add this built-in operator as a candidate (VQ is empty).
8432         ParamTypes[0] =
8433           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8434         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8435         if (VisibleTypeConversionsQuals.hasVolatile()) {
8436           // Add this built-in operator as a candidate (VQ is 'volatile').
8437           ParamTypes[0] = ArithmeticTypes[Left];
8438           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8439           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8440           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8441         }
8442       }
8443     }
8444   }
8445 
8446   // C++ [over.operator]p23:
8447   //
8448   //   There also exist candidate operator functions of the form
8449   //
8450   //        bool        operator!(bool);
8451   //        bool        operator&&(bool, bool);
8452   //        bool        operator||(bool, bool);
8453   void addExclaimOverload() {
8454     QualType ParamTy = S.Context.BoolTy;
8455     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8456                           /*IsAssignmentOperator=*/false,
8457                           /*NumContextualBoolArguments=*/1);
8458   }
8459   void addAmpAmpOrPipePipeOverload() {
8460     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8461     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8462                           /*IsAssignmentOperator=*/false,
8463                           /*NumContextualBoolArguments=*/2);
8464   }
8465 
8466   // C++ [over.built]p13:
8467   //
8468   //   For every cv-qualified or cv-unqualified object type T there
8469   //   exist candidate operator functions of the form
8470   //
8471   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8472   //        T&         operator[](T*, ptrdiff_t);
8473   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8474   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8475   //        T&         operator[](ptrdiff_t, T*);
8476   void addSubscriptOverloads() {
8477     for (BuiltinCandidateTypeSet::iterator
8478               Ptr = CandidateTypes[0].pointer_begin(),
8479            PtrEnd = CandidateTypes[0].pointer_end();
8480          Ptr != PtrEnd; ++Ptr) {
8481       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8482       QualType PointeeType = (*Ptr)->getPointeeType();
8483       if (!PointeeType->isObjectType())
8484         continue;
8485 
8486       // T& operator[](T*, ptrdiff_t)
8487       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8488     }
8489 
8490     for (BuiltinCandidateTypeSet::iterator
8491               Ptr = CandidateTypes[1].pointer_begin(),
8492            PtrEnd = CandidateTypes[1].pointer_end();
8493          Ptr != PtrEnd; ++Ptr) {
8494       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8495       QualType PointeeType = (*Ptr)->getPointeeType();
8496       if (!PointeeType->isObjectType())
8497         continue;
8498 
8499       // T& operator[](ptrdiff_t, T*)
8500       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8501     }
8502   }
8503 
8504   // C++ [over.built]p11:
8505   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8506   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8507   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8508   //    there exist candidate operator functions of the form
8509   //
8510   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8511   //
8512   //    where CV12 is the union of CV1 and CV2.
8513   void addArrowStarOverloads() {
8514     for (BuiltinCandidateTypeSet::iterator
8515              Ptr = CandidateTypes[0].pointer_begin(),
8516            PtrEnd = CandidateTypes[0].pointer_end();
8517          Ptr != PtrEnd; ++Ptr) {
8518       QualType C1Ty = (*Ptr);
8519       QualType C1;
8520       QualifierCollector Q1;
8521       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8522       if (!isa<RecordType>(C1))
8523         continue;
8524       // heuristic to reduce number of builtin candidates in the set.
8525       // Add volatile/restrict version only if there are conversions to a
8526       // volatile/restrict type.
8527       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8528         continue;
8529       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8530         continue;
8531       for (BuiltinCandidateTypeSet::iterator
8532                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8533              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8534            MemPtr != MemPtrEnd; ++MemPtr) {
8535         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8536         QualType C2 = QualType(mptr->getClass(), 0);
8537         C2 = C2.getUnqualifiedType();
8538         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8539           break;
8540         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8541         // build CV12 T&
8542         QualType T = mptr->getPointeeType();
8543         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8544             T.isVolatileQualified())
8545           continue;
8546         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8547             T.isRestrictQualified())
8548           continue;
8549         T = Q1.apply(S.Context, T);
8550         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8551       }
8552     }
8553   }
8554 
8555   // Note that we don't consider the first argument, since it has been
8556   // contextually converted to bool long ago. The candidates below are
8557   // therefore added as binary.
8558   //
8559   // C++ [over.built]p25:
8560   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8561   //   enumeration type, there exist candidate operator functions of the form
8562   //
8563   //        T        operator?(bool, T, T);
8564   //
8565   void addConditionalOperatorOverloads() {
8566     /// Set of (canonical) types that we've already handled.
8567     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8568 
8569     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8570       for (BuiltinCandidateTypeSet::iterator
8571                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8572              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8573            Ptr != PtrEnd; ++Ptr) {
8574         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8575           continue;
8576 
8577         QualType ParamTypes[2] = { *Ptr, *Ptr };
8578         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8579       }
8580 
8581       for (BuiltinCandidateTypeSet::iterator
8582                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8583              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8584            MemPtr != MemPtrEnd; ++MemPtr) {
8585         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8586           continue;
8587 
8588         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8589         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8590       }
8591 
8592       if (S.getLangOpts().CPlusPlus11) {
8593         for (BuiltinCandidateTypeSet::iterator
8594                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8595                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8596              Enum != EnumEnd; ++Enum) {
8597           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8598             continue;
8599 
8600           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8601             continue;
8602 
8603           QualType ParamTypes[2] = { *Enum, *Enum };
8604           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8605         }
8606       }
8607     }
8608   }
8609 };
8610 
8611 } // end anonymous namespace
8612 
8613 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8614 /// operator overloads to the candidate set (C++ [over.built]), based
8615 /// on the operator @p Op and the arguments given. For example, if the
8616 /// operator is a binary '+', this routine might add "int
8617 /// operator+(int, int)" to cover integer addition.
8618 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8619                                         SourceLocation OpLoc,
8620                                         ArrayRef<Expr *> Args,
8621                                         OverloadCandidateSet &CandidateSet) {
8622   // Find all of the types that the arguments can convert to, but only
8623   // if the operator we're looking at has built-in operator candidates
8624   // that make use of these types. Also record whether we encounter non-record
8625   // candidate types or either arithmetic or enumeral candidate types.
8626   Qualifiers VisibleTypeConversionsQuals;
8627   VisibleTypeConversionsQuals.addConst();
8628   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8629     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8630 
8631   bool HasNonRecordCandidateType = false;
8632   bool HasArithmeticOrEnumeralCandidateType = false;
8633   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8634   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8635     CandidateTypes.emplace_back(*this);
8636     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8637                                                  OpLoc,
8638                                                  true,
8639                                                  (Op == OO_Exclaim ||
8640                                                   Op == OO_AmpAmp ||
8641                                                   Op == OO_PipePipe),
8642                                                  VisibleTypeConversionsQuals);
8643     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8644         CandidateTypes[ArgIdx].hasNonRecordTypes();
8645     HasArithmeticOrEnumeralCandidateType =
8646         HasArithmeticOrEnumeralCandidateType ||
8647         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8648   }
8649 
8650   // Exit early when no non-record types have been added to the candidate set
8651   // for any of the arguments to the operator.
8652   //
8653   // We can't exit early for !, ||, or &&, since there we have always have
8654   // 'bool' overloads.
8655   if (!HasNonRecordCandidateType &&
8656       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8657     return;
8658 
8659   // Setup an object to manage the common state for building overloads.
8660   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8661                                            VisibleTypeConversionsQuals,
8662                                            HasArithmeticOrEnumeralCandidateType,
8663                                            CandidateTypes, CandidateSet);
8664 
8665   // Dispatch over the operation to add in only those overloads which apply.
8666   switch (Op) {
8667   case OO_None:
8668   case NUM_OVERLOADED_OPERATORS:
8669     llvm_unreachable("Expected an overloaded operator");
8670 
8671   case OO_New:
8672   case OO_Delete:
8673   case OO_Array_New:
8674   case OO_Array_Delete:
8675   case OO_Call:
8676     llvm_unreachable(
8677                     "Special operators don't use AddBuiltinOperatorCandidates");
8678 
8679   case OO_Comma:
8680   case OO_Arrow:
8681   case OO_Coawait:
8682     // C++ [over.match.oper]p3:
8683     //   -- For the operator ',', the unary operator '&', the
8684     //      operator '->', or the operator 'co_await', the
8685     //      built-in candidates set is empty.
8686     break;
8687 
8688   case OO_Plus: // '+' is either unary or binary
8689     if (Args.size() == 1)
8690       OpBuilder.addUnaryPlusPointerOverloads();
8691     LLVM_FALLTHROUGH;
8692 
8693   case OO_Minus: // '-' is either unary or binary
8694     if (Args.size() == 1) {
8695       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8696     } else {
8697       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8698       OpBuilder.addGenericBinaryArithmeticOverloads();
8699     }
8700     break;
8701 
8702   case OO_Star: // '*' is either unary or binary
8703     if (Args.size() == 1)
8704       OpBuilder.addUnaryStarPointerOverloads();
8705     else
8706       OpBuilder.addGenericBinaryArithmeticOverloads();
8707     break;
8708 
8709   case OO_Slash:
8710     OpBuilder.addGenericBinaryArithmeticOverloads();
8711     break;
8712 
8713   case OO_PlusPlus:
8714   case OO_MinusMinus:
8715     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8716     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8717     break;
8718 
8719   case OO_EqualEqual:
8720   case OO_ExclaimEqual:
8721     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8722     LLVM_FALLTHROUGH;
8723 
8724   case OO_Less:
8725   case OO_Greater:
8726   case OO_LessEqual:
8727   case OO_GreaterEqual:
8728     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8729     OpBuilder.addGenericBinaryArithmeticOverloads();
8730     break;
8731 
8732   case OO_Spaceship:
8733     llvm_unreachable("<=> expressions not supported yet");
8734 
8735   case OO_Percent:
8736   case OO_Caret:
8737   case OO_Pipe:
8738   case OO_LessLess:
8739   case OO_GreaterGreater:
8740     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8741     break;
8742 
8743   case OO_Amp: // '&' is either unary or binary
8744     if (Args.size() == 1)
8745       // C++ [over.match.oper]p3:
8746       //   -- For the operator ',', the unary operator '&', or the
8747       //      operator '->', the built-in candidates set is empty.
8748       break;
8749 
8750     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8751     break;
8752 
8753   case OO_Tilde:
8754     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8755     break;
8756 
8757   case OO_Equal:
8758     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8759     LLVM_FALLTHROUGH;
8760 
8761   case OO_PlusEqual:
8762   case OO_MinusEqual:
8763     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8764     LLVM_FALLTHROUGH;
8765 
8766   case OO_StarEqual:
8767   case OO_SlashEqual:
8768     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8769     break;
8770 
8771   case OO_PercentEqual:
8772   case OO_LessLessEqual:
8773   case OO_GreaterGreaterEqual:
8774   case OO_AmpEqual:
8775   case OO_CaretEqual:
8776   case OO_PipeEqual:
8777     OpBuilder.addAssignmentIntegralOverloads();
8778     break;
8779 
8780   case OO_Exclaim:
8781     OpBuilder.addExclaimOverload();
8782     break;
8783 
8784   case OO_AmpAmp:
8785   case OO_PipePipe:
8786     OpBuilder.addAmpAmpOrPipePipeOverload();
8787     break;
8788 
8789   case OO_Subscript:
8790     OpBuilder.addSubscriptOverloads();
8791     break;
8792 
8793   case OO_ArrowStar:
8794     OpBuilder.addArrowStarOverloads();
8795     break;
8796 
8797   case OO_Conditional:
8798     OpBuilder.addConditionalOperatorOverloads();
8799     OpBuilder.addGenericBinaryArithmeticOverloads();
8800     break;
8801   }
8802 }
8803 
8804 /// \brief Add function candidates found via argument-dependent lookup
8805 /// to the set of overloading candidates.
8806 ///
8807 /// This routine performs argument-dependent name lookup based on the
8808 /// given function name (which may also be an operator name) and adds
8809 /// all of the overload candidates found by ADL to the overload
8810 /// candidate set (C++ [basic.lookup.argdep]).
8811 void
8812 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8813                                            SourceLocation Loc,
8814                                            ArrayRef<Expr *> Args,
8815                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8816                                            OverloadCandidateSet& CandidateSet,
8817                                            bool PartialOverloading) {
8818   ADLResult Fns;
8819 
8820   // FIXME: This approach for uniquing ADL results (and removing
8821   // redundant candidates from the set) relies on pointer-equality,
8822   // which means we need to key off the canonical decl.  However,
8823   // always going back to the canonical decl might not get us the
8824   // right set of default arguments.  What default arguments are
8825   // we supposed to consider on ADL candidates, anyway?
8826 
8827   // FIXME: Pass in the explicit template arguments?
8828   ArgumentDependentLookup(Name, Loc, Args, Fns);
8829 
8830   // Erase all of the candidates we already knew about.
8831   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8832                                    CandEnd = CandidateSet.end();
8833        Cand != CandEnd; ++Cand)
8834     if (Cand->Function) {
8835       Fns.erase(Cand->Function);
8836       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8837         Fns.erase(FunTmpl);
8838     }
8839 
8840   // For each of the ADL candidates we found, add it to the overload
8841   // set.
8842   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8843     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8844     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8845       if (ExplicitTemplateArgs)
8846         continue;
8847 
8848       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8849                            PartialOverloading);
8850     } else
8851       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8852                                    FoundDecl, ExplicitTemplateArgs,
8853                                    Args, CandidateSet, PartialOverloading);
8854   }
8855 }
8856 
8857 namespace {
8858 enum class Comparison { Equal, Better, Worse };
8859 }
8860 
8861 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8862 /// overload resolution.
8863 ///
8864 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8865 /// Cand1's first N enable_if attributes have precisely the same conditions as
8866 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8867 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8868 ///
8869 /// Note that you can have a pair of candidates such that Cand1's enable_if
8870 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8871 /// worse than Cand1's.
8872 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8873                                        const FunctionDecl *Cand2) {
8874   // Common case: One (or both) decls don't have enable_if attrs.
8875   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8876   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8877   if (!Cand1Attr || !Cand2Attr) {
8878     if (Cand1Attr == Cand2Attr)
8879       return Comparison::Equal;
8880     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8881   }
8882 
8883   // FIXME: The next several lines are just
8884   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8885   // instead of reverse order which is how they're stored in the AST.
8886   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8887   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8888 
8889   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8890   // has fewer enable_if attributes than Cand2.
8891   if (Cand1Attrs.size() < Cand2Attrs.size())
8892     return Comparison::Worse;
8893 
8894   auto Cand1I = Cand1Attrs.begin();
8895   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8896   for (auto &Cand2A : Cand2Attrs) {
8897     Cand1ID.clear();
8898     Cand2ID.clear();
8899 
8900     auto &Cand1A = *Cand1I++;
8901     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8902     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8903     if (Cand1ID != Cand2ID)
8904       return Comparison::Worse;
8905   }
8906 
8907   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8908 }
8909 
8910 /// isBetterOverloadCandidate - Determines whether the first overload
8911 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8912 bool clang::isBetterOverloadCandidate(
8913     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8914     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8915   // Define viable functions to be better candidates than non-viable
8916   // functions.
8917   if (!Cand2.Viable)
8918     return Cand1.Viable;
8919   else if (!Cand1.Viable)
8920     return false;
8921 
8922   // C++ [over.match.best]p1:
8923   //
8924   //   -- if F is a static member function, ICS1(F) is defined such
8925   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8926   //      any function G, and, symmetrically, ICS1(G) is neither
8927   //      better nor worse than ICS1(F).
8928   unsigned StartArg = 0;
8929   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8930     StartArg = 1;
8931 
8932   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8933     // We don't allow incompatible pointer conversions in C++.
8934     if (!S.getLangOpts().CPlusPlus)
8935       return ICS.isStandard() &&
8936              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8937 
8938     // The only ill-formed conversion we allow in C++ is the string literal to
8939     // char* conversion, which is only considered ill-formed after C++11.
8940     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8941            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8942   };
8943 
8944   // Define functions that don't require ill-formed conversions for a given
8945   // argument to be better candidates than functions that do.
8946   unsigned NumArgs = Cand1.Conversions.size();
8947   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8948   bool HasBetterConversion = false;
8949   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8950     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8951     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8952     if (Cand1Bad != Cand2Bad) {
8953       if (Cand1Bad)
8954         return false;
8955       HasBetterConversion = true;
8956     }
8957   }
8958 
8959   if (HasBetterConversion)
8960     return true;
8961 
8962   // C++ [over.match.best]p1:
8963   //   A viable function F1 is defined to be a better function than another
8964   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8965   //   conversion sequence than ICSi(F2), and then...
8966   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8967     switch (CompareImplicitConversionSequences(S, Loc,
8968                                                Cand1.Conversions[ArgIdx],
8969                                                Cand2.Conversions[ArgIdx])) {
8970     case ImplicitConversionSequence::Better:
8971       // Cand1 has a better conversion sequence.
8972       HasBetterConversion = true;
8973       break;
8974 
8975     case ImplicitConversionSequence::Worse:
8976       // Cand1 can't be better than Cand2.
8977       return false;
8978 
8979     case ImplicitConversionSequence::Indistinguishable:
8980       // Do nothing.
8981       break;
8982     }
8983   }
8984 
8985   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8986   //       ICSj(F2), or, if not that,
8987   if (HasBetterConversion)
8988     return true;
8989 
8990   //   -- the context is an initialization by user-defined conversion
8991   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8992   //      from the return type of F1 to the destination type (i.e.,
8993   //      the type of the entity being initialized) is a better
8994   //      conversion sequence than the standard conversion sequence
8995   //      from the return type of F2 to the destination type.
8996   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
8997       Cand1.Function && Cand2.Function &&
8998       isa<CXXConversionDecl>(Cand1.Function) &&
8999       isa<CXXConversionDecl>(Cand2.Function)) {
9000     // First check whether we prefer one of the conversion functions over the
9001     // other. This only distinguishes the results in non-standard, extension
9002     // cases such as the conversion from a lambda closure type to a function
9003     // pointer or block.
9004     ImplicitConversionSequence::CompareKind Result =
9005         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9006     if (Result == ImplicitConversionSequence::Indistinguishable)
9007       Result = CompareStandardConversionSequences(S, Loc,
9008                                                   Cand1.FinalConversion,
9009                                                   Cand2.FinalConversion);
9010 
9011     if (Result != ImplicitConversionSequence::Indistinguishable)
9012       return Result == ImplicitConversionSequence::Better;
9013 
9014     // FIXME: Compare kind of reference binding if conversion functions
9015     // convert to a reference type used in direct reference binding, per
9016     // C++14 [over.match.best]p1 section 2 bullet 3.
9017   }
9018 
9019   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9020   // as combined with the resolution to CWG issue 243.
9021   //
9022   // When the context is initialization by constructor ([over.match.ctor] or
9023   // either phase of [over.match.list]), a constructor is preferred over
9024   // a conversion function.
9025   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9026       Cand1.Function && Cand2.Function &&
9027       isa<CXXConstructorDecl>(Cand1.Function) !=
9028           isa<CXXConstructorDecl>(Cand2.Function))
9029     return isa<CXXConstructorDecl>(Cand1.Function);
9030 
9031   //    -- F1 is a non-template function and F2 is a function template
9032   //       specialization, or, if not that,
9033   bool Cand1IsSpecialization = Cand1.Function &&
9034                                Cand1.Function->getPrimaryTemplate();
9035   bool Cand2IsSpecialization = Cand2.Function &&
9036                                Cand2.Function->getPrimaryTemplate();
9037   if (Cand1IsSpecialization != Cand2IsSpecialization)
9038     return Cand2IsSpecialization;
9039 
9040   //   -- F1 and F2 are function template specializations, and the function
9041   //      template for F1 is more specialized than the template for F2
9042   //      according to the partial ordering rules described in 14.5.5.2, or,
9043   //      if not that,
9044   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9045     if (FunctionTemplateDecl *BetterTemplate
9046           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9047                                          Cand2.Function->getPrimaryTemplate(),
9048                                          Loc,
9049                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9050                                                              : TPOC_Call,
9051                                          Cand1.ExplicitCallArguments,
9052                                          Cand2.ExplicitCallArguments))
9053       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9054   }
9055 
9056   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9057   // A derived-class constructor beats an (inherited) base class constructor.
9058   bool Cand1IsInherited =
9059       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9060   bool Cand2IsInherited =
9061       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9062   if (Cand1IsInherited != Cand2IsInherited)
9063     return Cand2IsInherited;
9064   else if (Cand1IsInherited) {
9065     assert(Cand2IsInherited);
9066     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9067     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9068     if (Cand1Class->isDerivedFrom(Cand2Class))
9069       return true;
9070     if (Cand2Class->isDerivedFrom(Cand1Class))
9071       return false;
9072     // Inherited from sibling base classes: still ambiguous.
9073   }
9074 
9075   // Check C++17 tie-breakers for deduction guides.
9076   {
9077     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9078     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9079     if (Guide1 && Guide2) {
9080       //  -- F1 is generated from a deduction-guide and F2 is not
9081       if (Guide1->isImplicit() != Guide2->isImplicit())
9082         return Guide2->isImplicit();
9083 
9084       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9085       if (Guide1->isCopyDeductionCandidate())
9086         return true;
9087     }
9088   }
9089 
9090   // Check for enable_if value-based overload resolution.
9091   if (Cand1.Function && Cand2.Function) {
9092     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9093     if (Cmp != Comparison::Equal)
9094       return Cmp == Comparison::Better;
9095   }
9096 
9097   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9098     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9099     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9100            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9101   }
9102 
9103   bool HasPS1 = Cand1.Function != nullptr &&
9104                 functionHasPassObjectSizeParams(Cand1.Function);
9105   bool HasPS2 = Cand2.Function != nullptr &&
9106                 functionHasPassObjectSizeParams(Cand2.Function);
9107   return HasPS1 != HasPS2 && HasPS1;
9108 }
9109 
9110 /// Determine whether two declarations are "equivalent" for the purposes of
9111 /// name lookup and overload resolution. This applies when the same internal/no
9112 /// linkage entity is defined by two modules (probably by textually including
9113 /// the same header). In such a case, we don't consider the declarations to
9114 /// declare the same entity, but we also don't want lookups with both
9115 /// declarations visible to be ambiguous in some cases (this happens when using
9116 /// a modularized libstdc++).
9117 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9118                                                   const NamedDecl *B) {
9119   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9120   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9121   if (!VA || !VB)
9122     return false;
9123 
9124   // The declarations must be declaring the same name as an internal linkage
9125   // entity in different modules.
9126   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9127           VB->getDeclContext()->getRedeclContext()) ||
9128       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9129           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9130       VA->isExternallyVisible() || VB->isExternallyVisible())
9131     return false;
9132 
9133   // Check that the declarations appear to be equivalent.
9134   //
9135   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9136   // For constants and functions, we should check the initializer or body is
9137   // the same. For non-constant variables, we shouldn't allow it at all.
9138   if (Context.hasSameType(VA->getType(), VB->getType()))
9139     return true;
9140 
9141   // Enum constants within unnamed enumerations will have different types, but
9142   // may still be similar enough to be interchangeable for our purposes.
9143   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9144     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9145       // Only handle anonymous enums. If the enumerations were named and
9146       // equivalent, they would have been merged to the same type.
9147       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9148       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9149       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9150           !Context.hasSameType(EnumA->getIntegerType(),
9151                                EnumB->getIntegerType()))
9152         return false;
9153       // Allow this only if the value is the same for both enumerators.
9154       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9155     }
9156   }
9157 
9158   // Nothing else is sufficiently similar.
9159   return false;
9160 }
9161 
9162 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9163     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9164   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9165 
9166   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9167   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9168       << !M << (M ? M->getFullModuleName() : "");
9169 
9170   for (auto *E : Equiv) {
9171     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9172     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9173         << !M << (M ? M->getFullModuleName() : "");
9174   }
9175 }
9176 
9177 /// \brief Computes the best viable function (C++ 13.3.3)
9178 /// within an overload candidate set.
9179 ///
9180 /// \param Loc The location of the function name (or operator symbol) for
9181 /// which overload resolution occurs.
9182 ///
9183 /// \param Best If overload resolution was successful or found a deleted
9184 /// function, \p Best points to the candidate function found.
9185 ///
9186 /// \returns The result of overload resolution.
9187 OverloadingResult
9188 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9189                                          iterator &Best) {
9190   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9191   std::transform(begin(), end(), std::back_inserter(Candidates),
9192                  [](OverloadCandidate &Cand) { return &Cand; });
9193 
9194   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9195   // are accepted by both clang and NVCC. However, during a particular
9196   // compilation mode only one call variant is viable. We need to
9197   // exclude non-viable overload candidates from consideration based
9198   // only on their host/device attributes. Specifically, if one
9199   // candidate call is WrongSide and the other is SameSide, we ignore
9200   // the WrongSide candidate.
9201   if (S.getLangOpts().CUDA) {
9202     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9203     bool ContainsSameSideCandidate =
9204         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9205           return Cand->Function &&
9206                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9207                      Sema::CFP_SameSide;
9208         });
9209     if (ContainsSameSideCandidate) {
9210       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9211         return Cand->Function &&
9212                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9213                    Sema::CFP_WrongSide;
9214       };
9215       llvm::erase_if(Candidates, IsWrongSideCandidate);
9216     }
9217   }
9218 
9219   // Find the best viable function.
9220   Best = end();
9221   for (auto *Cand : Candidates)
9222     if (Cand->Viable)
9223       if (Best == end() ||
9224           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9225         Best = Cand;
9226 
9227   // If we didn't find any viable functions, abort.
9228   if (Best == end())
9229     return OR_No_Viable_Function;
9230 
9231   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9232 
9233   // Make sure that this function is better than every other viable
9234   // function. If not, we have an ambiguity.
9235   for (auto *Cand : Candidates) {
9236     if (Cand->Viable && Cand != Best &&
9237         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9238       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9239                                                    Cand->Function)) {
9240         EquivalentCands.push_back(Cand->Function);
9241         continue;
9242       }
9243 
9244       Best = end();
9245       return OR_Ambiguous;
9246     }
9247   }
9248 
9249   // Best is the best viable function.
9250   if (Best->Function &&
9251       (Best->Function->isDeleted() ||
9252        S.isFunctionConsideredUnavailable(Best->Function)))
9253     return OR_Deleted;
9254 
9255   if (!EquivalentCands.empty())
9256     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9257                                                     EquivalentCands);
9258 
9259   return OR_Success;
9260 }
9261 
9262 namespace {
9263 
9264 enum OverloadCandidateKind {
9265   oc_function,
9266   oc_method,
9267   oc_constructor,
9268   oc_function_template,
9269   oc_method_template,
9270   oc_constructor_template,
9271   oc_implicit_default_constructor,
9272   oc_implicit_copy_constructor,
9273   oc_implicit_move_constructor,
9274   oc_implicit_copy_assignment,
9275   oc_implicit_move_assignment,
9276   oc_inherited_constructor,
9277   oc_inherited_constructor_template
9278 };
9279 
9280 static OverloadCandidateKind
9281 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9282                           std::string &Description) {
9283   bool isTemplate = false;
9284 
9285   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9286     isTemplate = true;
9287     Description = S.getTemplateArgumentBindingsText(
9288       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9289   }
9290 
9291   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9292     if (!Ctor->isImplicit()) {
9293       if (isa<ConstructorUsingShadowDecl>(Found))
9294         return isTemplate ? oc_inherited_constructor_template
9295                           : oc_inherited_constructor;
9296       else
9297         return isTemplate ? oc_constructor_template : oc_constructor;
9298     }
9299 
9300     if (Ctor->isDefaultConstructor())
9301       return oc_implicit_default_constructor;
9302 
9303     if (Ctor->isMoveConstructor())
9304       return oc_implicit_move_constructor;
9305 
9306     assert(Ctor->isCopyConstructor() &&
9307            "unexpected sort of implicit constructor");
9308     return oc_implicit_copy_constructor;
9309   }
9310 
9311   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9312     // This actually gets spelled 'candidate function' for now, but
9313     // it doesn't hurt to split it out.
9314     if (!Meth->isImplicit())
9315       return isTemplate ? oc_method_template : oc_method;
9316 
9317     if (Meth->isMoveAssignmentOperator())
9318       return oc_implicit_move_assignment;
9319 
9320     if (Meth->isCopyAssignmentOperator())
9321       return oc_implicit_copy_assignment;
9322 
9323     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9324     return oc_method;
9325   }
9326 
9327   return isTemplate ? oc_function_template : oc_function;
9328 }
9329 
9330 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9331   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9332   // set.
9333   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9334     S.Diag(FoundDecl->getLocation(),
9335            diag::note_ovl_candidate_inherited_constructor)
9336       << Shadow->getNominatedBaseClass();
9337 }
9338 
9339 } // end anonymous namespace
9340 
9341 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9342                                     const FunctionDecl *FD) {
9343   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9344     bool AlwaysTrue;
9345     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9346       return false;
9347     if (!AlwaysTrue)
9348       return false;
9349   }
9350   return true;
9351 }
9352 
9353 /// \brief Returns true if we can take the address of the function.
9354 ///
9355 /// \param Complain - If true, we'll emit a diagnostic
9356 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9357 ///   we in overload resolution?
9358 /// \param Loc - The location of the statement we're complaining about. Ignored
9359 ///   if we're not complaining, or if we're in overload resolution.
9360 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9361                                               bool Complain,
9362                                               bool InOverloadResolution,
9363                                               SourceLocation Loc) {
9364   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9365     if (Complain) {
9366       if (InOverloadResolution)
9367         S.Diag(FD->getLocStart(),
9368                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9369       else
9370         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9371     }
9372     return false;
9373   }
9374 
9375   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9376     return P->hasAttr<PassObjectSizeAttr>();
9377   });
9378   if (I == FD->param_end())
9379     return true;
9380 
9381   if (Complain) {
9382     // Add one to ParamNo because it's user-facing
9383     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9384     if (InOverloadResolution)
9385       S.Diag(FD->getLocation(),
9386              diag::note_ovl_candidate_has_pass_object_size_params)
9387           << ParamNo;
9388     else
9389       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9390           << FD << ParamNo;
9391   }
9392   return false;
9393 }
9394 
9395 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9396                                                const FunctionDecl *FD) {
9397   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9398                                            /*InOverloadResolution=*/true,
9399                                            /*Loc=*/SourceLocation());
9400 }
9401 
9402 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9403                                              bool Complain,
9404                                              SourceLocation Loc) {
9405   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9406                                              /*InOverloadResolution=*/false,
9407                                              Loc);
9408 }
9409 
9410 // Notes the location of an overload candidate.
9411 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9412                                  QualType DestType, bool TakingAddress) {
9413   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9414     return;
9415   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9416     return;
9417 
9418   std::string FnDesc;
9419   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9420   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9421                              << (unsigned) K << Fn << FnDesc;
9422 
9423   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9424   Diag(Fn->getLocation(), PD);
9425   MaybeEmitInheritedConstructorNote(*this, Found);
9426 }
9427 
9428 // Notes the location of all overload candidates designated through
9429 // OverloadedExpr
9430 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9431                                      bool TakingAddress) {
9432   assert(OverloadedExpr->getType() == Context.OverloadTy);
9433 
9434   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9435   OverloadExpr *OvlExpr = Ovl.Expression;
9436 
9437   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9438                             IEnd = OvlExpr->decls_end();
9439        I != IEnd; ++I) {
9440     if (FunctionTemplateDecl *FunTmpl =
9441                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9442       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9443                             TakingAddress);
9444     } else if (FunctionDecl *Fun
9445                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9446       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9447     }
9448   }
9449 }
9450 
9451 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9452 /// "lead" diagnostic; it will be given two arguments, the source and
9453 /// target types of the conversion.
9454 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9455                                  Sema &S,
9456                                  SourceLocation CaretLoc,
9457                                  const PartialDiagnostic &PDiag) const {
9458   S.Diag(CaretLoc, PDiag)
9459     << Ambiguous.getFromType() << Ambiguous.getToType();
9460   // FIXME: The note limiting machinery is borrowed from
9461   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9462   // refactoring here.
9463   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9464   unsigned CandsShown = 0;
9465   AmbiguousConversionSequence::const_iterator I, E;
9466   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9467     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9468       break;
9469     ++CandsShown;
9470     S.NoteOverloadCandidate(I->first, I->second);
9471   }
9472   if (I != E)
9473     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9474 }
9475 
9476 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9477                                   unsigned I, bool TakingCandidateAddress) {
9478   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9479   assert(Conv.isBad());
9480   assert(Cand->Function && "for now, candidate must be a function");
9481   FunctionDecl *Fn = Cand->Function;
9482 
9483   // There's a conversion slot for the object argument if this is a
9484   // non-constructor method.  Note that 'I' corresponds the
9485   // conversion-slot index.
9486   bool isObjectArgument = false;
9487   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9488     if (I == 0)
9489       isObjectArgument = true;
9490     else
9491       I--;
9492   }
9493 
9494   std::string FnDesc;
9495   OverloadCandidateKind FnKind =
9496       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9497 
9498   Expr *FromExpr = Conv.Bad.FromExpr;
9499   QualType FromTy = Conv.Bad.getFromType();
9500   QualType ToTy = Conv.Bad.getToType();
9501 
9502   if (FromTy == S.Context.OverloadTy) {
9503     assert(FromExpr && "overload set argument came from implicit argument?");
9504     Expr *E = FromExpr->IgnoreParens();
9505     if (isa<UnaryOperator>(E))
9506       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9507     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9508 
9509     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9510       << (unsigned) FnKind << FnDesc
9511       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9512       << ToTy << Name << I+1;
9513     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9514     return;
9515   }
9516 
9517   // Do some hand-waving analysis to see if the non-viability is due
9518   // to a qualifier mismatch.
9519   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9520   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9521   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9522     CToTy = RT->getPointeeType();
9523   else {
9524     // TODO: detect and diagnose the full richness of const mismatches.
9525     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9526       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9527         CFromTy = FromPT->getPointeeType();
9528         CToTy = ToPT->getPointeeType();
9529       }
9530   }
9531 
9532   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9533       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9534     Qualifiers FromQs = CFromTy.getQualifiers();
9535     Qualifiers ToQs = CToTy.getQualifiers();
9536 
9537     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9538       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9539         << (unsigned) FnKind << FnDesc
9540         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9541         << FromTy
9542         << FromQs.getAddressSpaceAttributePrintValue()
9543         << ToQs.getAddressSpaceAttributePrintValue()
9544         << (unsigned) isObjectArgument << I+1;
9545       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9546       return;
9547     }
9548 
9549     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9550       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9551         << (unsigned) FnKind << FnDesc
9552         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9553         << FromTy
9554         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9555         << (unsigned) isObjectArgument << I+1;
9556       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9557       return;
9558     }
9559 
9560     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9561       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9562       << (unsigned) FnKind << FnDesc
9563       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9564       << FromTy
9565       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9566       << (unsigned) isObjectArgument << I+1;
9567       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9568       return;
9569     }
9570 
9571     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9572       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9573         << (unsigned) FnKind << FnDesc
9574         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9575         << FromTy << FromQs.hasUnaligned() << I+1;
9576       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9577       return;
9578     }
9579 
9580     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9581     assert(CVR && "unexpected qualifiers mismatch");
9582 
9583     if (isObjectArgument) {
9584       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9585         << (unsigned) FnKind << FnDesc
9586         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9587         << FromTy << (CVR - 1);
9588     } else {
9589       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9590         << (unsigned) FnKind << FnDesc
9591         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9592         << FromTy << (CVR - 1) << I+1;
9593     }
9594     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9595     return;
9596   }
9597 
9598   // Special diagnostic for failure to convert an initializer list, since
9599   // telling the user that it has type void is not useful.
9600   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9601     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9602       << (unsigned) FnKind << FnDesc
9603       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9604       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9605     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9606     return;
9607   }
9608 
9609   // Diagnose references or pointers to incomplete types differently,
9610   // since it's far from impossible that the incompleteness triggered
9611   // the failure.
9612   QualType TempFromTy = FromTy.getNonReferenceType();
9613   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9614     TempFromTy = PTy->getPointeeType();
9615   if (TempFromTy->isIncompleteType()) {
9616     // Emit the generic diagnostic and, optionally, add the hints to it.
9617     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9618       << (unsigned) FnKind << FnDesc
9619       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9620       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9621       << (unsigned) (Cand->Fix.Kind);
9622 
9623     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9624     return;
9625   }
9626 
9627   // Diagnose base -> derived pointer conversions.
9628   unsigned BaseToDerivedConversion = 0;
9629   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9630     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9631       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9632                                                FromPtrTy->getPointeeType()) &&
9633           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9634           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9635           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9636                           FromPtrTy->getPointeeType()))
9637         BaseToDerivedConversion = 1;
9638     }
9639   } else if (const ObjCObjectPointerType *FromPtrTy
9640                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9641     if (const ObjCObjectPointerType *ToPtrTy
9642                                         = ToTy->getAs<ObjCObjectPointerType>())
9643       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9644         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9645           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9646                                                 FromPtrTy->getPointeeType()) &&
9647               FromIface->isSuperClassOf(ToIface))
9648             BaseToDerivedConversion = 2;
9649   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9650     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9651         !FromTy->isIncompleteType() &&
9652         !ToRefTy->getPointeeType()->isIncompleteType() &&
9653         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9654       BaseToDerivedConversion = 3;
9655     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9656                ToTy.getNonReferenceType().getCanonicalType() ==
9657                FromTy.getNonReferenceType().getCanonicalType()) {
9658       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9659         << (unsigned) FnKind << FnDesc
9660         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9661         << (unsigned) isObjectArgument << I + 1;
9662       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9663       return;
9664     }
9665   }
9666 
9667   if (BaseToDerivedConversion) {
9668     S.Diag(Fn->getLocation(),
9669            diag::note_ovl_candidate_bad_base_to_derived_conv)
9670       << (unsigned) FnKind << FnDesc
9671       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9672       << (BaseToDerivedConversion - 1)
9673       << FromTy << ToTy << I+1;
9674     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9675     return;
9676   }
9677 
9678   if (isa<ObjCObjectPointerType>(CFromTy) &&
9679       isa<PointerType>(CToTy)) {
9680       Qualifiers FromQs = CFromTy.getQualifiers();
9681       Qualifiers ToQs = CToTy.getQualifiers();
9682       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9683         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9684         << (unsigned) FnKind << FnDesc
9685         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9686         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9687         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9688         return;
9689       }
9690   }
9691 
9692   if (TakingCandidateAddress &&
9693       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9694     return;
9695 
9696   // Emit the generic diagnostic and, optionally, add the hints to it.
9697   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9698   FDiag << (unsigned) FnKind << FnDesc
9699     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9700     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9701     << (unsigned) (Cand->Fix.Kind);
9702 
9703   // If we can fix the conversion, suggest the FixIts.
9704   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9705        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9706     FDiag << *HI;
9707   S.Diag(Fn->getLocation(), FDiag);
9708 
9709   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9710 }
9711 
9712 /// Additional arity mismatch diagnosis specific to a function overload
9713 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9714 /// over a candidate in any candidate set.
9715 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9716                                unsigned NumArgs) {
9717   FunctionDecl *Fn = Cand->Function;
9718   unsigned MinParams = Fn->getMinRequiredArguments();
9719 
9720   // With invalid overloaded operators, it's possible that we think we
9721   // have an arity mismatch when in fact it looks like we have the
9722   // right number of arguments, because only overloaded operators have
9723   // the weird behavior of overloading member and non-member functions.
9724   // Just don't report anything.
9725   if (Fn->isInvalidDecl() &&
9726       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9727     return true;
9728 
9729   if (NumArgs < MinParams) {
9730     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9731            (Cand->FailureKind == ovl_fail_bad_deduction &&
9732             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9733   } else {
9734     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9735            (Cand->FailureKind == ovl_fail_bad_deduction &&
9736             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9737   }
9738 
9739   return false;
9740 }
9741 
9742 /// General arity mismatch diagnosis over a candidate in a candidate set.
9743 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9744                                   unsigned NumFormalArgs) {
9745   assert(isa<FunctionDecl>(D) &&
9746       "The templated declaration should at least be a function"
9747       " when diagnosing bad template argument deduction due to too many"
9748       " or too few arguments");
9749 
9750   FunctionDecl *Fn = cast<FunctionDecl>(D);
9751 
9752   // TODO: treat calls to a missing default constructor as a special case
9753   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9754   unsigned MinParams = Fn->getMinRequiredArguments();
9755 
9756   // at least / at most / exactly
9757   unsigned mode, modeCount;
9758   if (NumFormalArgs < MinParams) {
9759     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9760         FnTy->isTemplateVariadic())
9761       mode = 0; // "at least"
9762     else
9763       mode = 2; // "exactly"
9764     modeCount = MinParams;
9765   } else {
9766     if (MinParams != FnTy->getNumParams())
9767       mode = 1; // "at most"
9768     else
9769       mode = 2; // "exactly"
9770     modeCount = FnTy->getNumParams();
9771   }
9772 
9773   std::string Description;
9774   OverloadCandidateKind FnKind =
9775       ClassifyOverloadCandidate(S, Found, Fn, Description);
9776 
9777   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9778     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9779       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9780       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9781   else
9782     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9783       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9784       << mode << modeCount << NumFormalArgs;
9785   MaybeEmitInheritedConstructorNote(S, Found);
9786 }
9787 
9788 /// Arity mismatch diagnosis specific to a function overload candidate.
9789 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9790                                   unsigned NumFormalArgs) {
9791   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9792     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9793 }
9794 
9795 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9796   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9797     return TD;
9798   llvm_unreachable("Unsupported: Getting the described template declaration"
9799                    " for bad deduction diagnosis");
9800 }
9801 
9802 /// Diagnose a failed template-argument deduction.
9803 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9804                                  DeductionFailureInfo &DeductionFailure,
9805                                  unsigned NumArgs,
9806                                  bool TakingCandidateAddress) {
9807   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9808   NamedDecl *ParamD;
9809   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9810   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9811   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9812   switch (DeductionFailure.Result) {
9813   case Sema::TDK_Success:
9814     llvm_unreachable("TDK_success while diagnosing bad deduction");
9815 
9816   case Sema::TDK_Incomplete: {
9817     assert(ParamD && "no parameter found for incomplete deduction result");
9818     S.Diag(Templated->getLocation(),
9819            diag::note_ovl_candidate_incomplete_deduction)
9820         << ParamD->getDeclName();
9821     MaybeEmitInheritedConstructorNote(S, Found);
9822     return;
9823   }
9824 
9825   case Sema::TDK_Underqualified: {
9826     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9827     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9828 
9829     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9830 
9831     // Param will have been canonicalized, but it should just be a
9832     // qualified version of ParamD, so move the qualifiers to that.
9833     QualifierCollector Qs;
9834     Qs.strip(Param);
9835     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9836     assert(S.Context.hasSameType(Param, NonCanonParam));
9837 
9838     // Arg has also been canonicalized, but there's nothing we can do
9839     // about that.  It also doesn't matter as much, because it won't
9840     // have any template parameters in it (because deduction isn't
9841     // done on dependent types).
9842     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9843 
9844     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9845         << ParamD->getDeclName() << Arg << NonCanonParam;
9846     MaybeEmitInheritedConstructorNote(S, Found);
9847     return;
9848   }
9849 
9850   case Sema::TDK_Inconsistent: {
9851     assert(ParamD && "no parameter found for inconsistent deduction result");
9852     int which = 0;
9853     if (isa<TemplateTypeParmDecl>(ParamD))
9854       which = 0;
9855     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9856       // Deduction might have failed because we deduced arguments of two
9857       // different types for a non-type template parameter.
9858       // FIXME: Use a different TDK value for this.
9859       QualType T1 =
9860           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9861       QualType T2 =
9862           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9863       if (!S.Context.hasSameType(T1, T2)) {
9864         S.Diag(Templated->getLocation(),
9865                diag::note_ovl_candidate_inconsistent_deduction_types)
9866           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9867           << *DeductionFailure.getSecondArg() << T2;
9868         MaybeEmitInheritedConstructorNote(S, Found);
9869         return;
9870       }
9871 
9872       which = 1;
9873     } else {
9874       which = 2;
9875     }
9876 
9877     S.Diag(Templated->getLocation(),
9878            diag::note_ovl_candidate_inconsistent_deduction)
9879         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9880         << *DeductionFailure.getSecondArg();
9881     MaybeEmitInheritedConstructorNote(S, Found);
9882     return;
9883   }
9884 
9885   case Sema::TDK_InvalidExplicitArguments:
9886     assert(ParamD && "no parameter found for invalid explicit arguments");
9887     if (ParamD->getDeclName())
9888       S.Diag(Templated->getLocation(),
9889              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9890           << ParamD->getDeclName();
9891     else {
9892       int index = 0;
9893       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9894         index = TTP->getIndex();
9895       else if (NonTypeTemplateParmDecl *NTTP
9896                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9897         index = NTTP->getIndex();
9898       else
9899         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9900       S.Diag(Templated->getLocation(),
9901              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9902           << (index + 1);
9903     }
9904     MaybeEmitInheritedConstructorNote(S, Found);
9905     return;
9906 
9907   case Sema::TDK_TooManyArguments:
9908   case Sema::TDK_TooFewArguments:
9909     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9910     return;
9911 
9912   case Sema::TDK_InstantiationDepth:
9913     S.Diag(Templated->getLocation(),
9914            diag::note_ovl_candidate_instantiation_depth);
9915     MaybeEmitInheritedConstructorNote(S, Found);
9916     return;
9917 
9918   case Sema::TDK_SubstitutionFailure: {
9919     // Format the template argument list into the argument string.
9920     SmallString<128> TemplateArgString;
9921     if (TemplateArgumentList *Args =
9922             DeductionFailure.getTemplateArgumentList()) {
9923       TemplateArgString = " ";
9924       TemplateArgString += S.getTemplateArgumentBindingsText(
9925           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9926     }
9927 
9928     // If this candidate was disabled by enable_if, say so.
9929     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9930     if (PDiag && PDiag->second.getDiagID() ==
9931           diag::err_typename_nested_not_found_enable_if) {
9932       // FIXME: Use the source range of the condition, and the fully-qualified
9933       //        name of the enable_if template. These are both present in PDiag.
9934       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9935         << "'enable_if'" << TemplateArgString;
9936       return;
9937     }
9938 
9939     // We found a specific requirement that disabled the enable_if.
9940     if (PDiag && PDiag->second.getDiagID() ==
9941         diag::err_typename_nested_not_found_requirement) {
9942       S.Diag(Templated->getLocation(),
9943              diag::note_ovl_candidate_disabled_by_requirement)
9944         << PDiag->second.getStringArg(0) << TemplateArgString;
9945       return;
9946     }
9947 
9948     // Format the SFINAE diagnostic into the argument string.
9949     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9950     //        formatted message in another diagnostic.
9951     SmallString<128> SFINAEArgString;
9952     SourceRange R;
9953     if (PDiag) {
9954       SFINAEArgString = ": ";
9955       R = SourceRange(PDiag->first, PDiag->first);
9956       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9957     }
9958 
9959     S.Diag(Templated->getLocation(),
9960            diag::note_ovl_candidate_substitution_failure)
9961         << TemplateArgString << SFINAEArgString << R;
9962     MaybeEmitInheritedConstructorNote(S, Found);
9963     return;
9964   }
9965 
9966   case Sema::TDK_DeducedMismatch:
9967   case Sema::TDK_DeducedMismatchNested: {
9968     // Format the template argument list into the argument string.
9969     SmallString<128> TemplateArgString;
9970     if (TemplateArgumentList *Args =
9971             DeductionFailure.getTemplateArgumentList()) {
9972       TemplateArgString = " ";
9973       TemplateArgString += S.getTemplateArgumentBindingsText(
9974           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9975     }
9976 
9977     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9978         << (*DeductionFailure.getCallArgIndex() + 1)
9979         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9980         << TemplateArgString
9981         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9982     break;
9983   }
9984 
9985   case Sema::TDK_NonDeducedMismatch: {
9986     // FIXME: Provide a source location to indicate what we couldn't match.
9987     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9988     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9989     if (FirstTA.getKind() == TemplateArgument::Template &&
9990         SecondTA.getKind() == TemplateArgument::Template) {
9991       TemplateName FirstTN = FirstTA.getAsTemplate();
9992       TemplateName SecondTN = SecondTA.getAsTemplate();
9993       if (FirstTN.getKind() == TemplateName::Template &&
9994           SecondTN.getKind() == TemplateName::Template) {
9995         if (FirstTN.getAsTemplateDecl()->getName() ==
9996             SecondTN.getAsTemplateDecl()->getName()) {
9997           // FIXME: This fixes a bad diagnostic where both templates are named
9998           // the same.  This particular case is a bit difficult since:
9999           // 1) It is passed as a string to the diagnostic printer.
10000           // 2) The diagnostic printer only attempts to find a better
10001           //    name for types, not decls.
10002           // Ideally, this should folded into the diagnostic printer.
10003           S.Diag(Templated->getLocation(),
10004                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10005               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10006           return;
10007         }
10008       }
10009     }
10010 
10011     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10012         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10013       return;
10014 
10015     // FIXME: For generic lambda parameters, check if the function is a lambda
10016     // call operator, and if so, emit a prettier and more informative
10017     // diagnostic that mentions 'auto' and lambda in addition to
10018     // (or instead of?) the canonical template type parameters.
10019     S.Diag(Templated->getLocation(),
10020            diag::note_ovl_candidate_non_deduced_mismatch)
10021         << FirstTA << SecondTA;
10022     return;
10023   }
10024   // TODO: diagnose these individually, then kill off
10025   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10026   case Sema::TDK_MiscellaneousDeductionFailure:
10027     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10028     MaybeEmitInheritedConstructorNote(S, Found);
10029     return;
10030   case Sema::TDK_CUDATargetMismatch:
10031     S.Diag(Templated->getLocation(),
10032            diag::note_cuda_ovl_candidate_target_mismatch);
10033     return;
10034   }
10035 }
10036 
10037 /// Diagnose a failed template-argument deduction, for function calls.
10038 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10039                                  unsigned NumArgs,
10040                                  bool TakingCandidateAddress) {
10041   unsigned TDK = Cand->DeductionFailure.Result;
10042   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10043     if (CheckArityMismatch(S, Cand, NumArgs))
10044       return;
10045   }
10046   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10047                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10048 }
10049 
10050 /// CUDA: diagnose an invalid call across targets.
10051 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10052   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10053   FunctionDecl *Callee = Cand->Function;
10054 
10055   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10056                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10057 
10058   std::string FnDesc;
10059   OverloadCandidateKind FnKind =
10060       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10061 
10062   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10063       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10064 
10065   // This could be an implicit constructor for which we could not infer the
10066   // target due to a collsion. Diagnose that case.
10067   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10068   if (Meth != nullptr && Meth->isImplicit()) {
10069     CXXRecordDecl *ParentClass = Meth->getParent();
10070     Sema::CXXSpecialMember CSM;
10071 
10072     switch (FnKind) {
10073     default:
10074       return;
10075     case oc_implicit_default_constructor:
10076       CSM = Sema::CXXDefaultConstructor;
10077       break;
10078     case oc_implicit_copy_constructor:
10079       CSM = Sema::CXXCopyConstructor;
10080       break;
10081     case oc_implicit_move_constructor:
10082       CSM = Sema::CXXMoveConstructor;
10083       break;
10084     case oc_implicit_copy_assignment:
10085       CSM = Sema::CXXCopyAssignment;
10086       break;
10087     case oc_implicit_move_assignment:
10088       CSM = Sema::CXXMoveAssignment;
10089       break;
10090     };
10091 
10092     bool ConstRHS = false;
10093     if (Meth->getNumParams()) {
10094       if (const ReferenceType *RT =
10095               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10096         ConstRHS = RT->getPointeeType().isConstQualified();
10097       }
10098     }
10099 
10100     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10101                                               /* ConstRHS */ ConstRHS,
10102                                               /* Diagnose */ true);
10103   }
10104 }
10105 
10106 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10107   FunctionDecl *Callee = Cand->Function;
10108   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10109 
10110   S.Diag(Callee->getLocation(),
10111          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10112       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10113 }
10114 
10115 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10116   FunctionDecl *Callee = Cand->Function;
10117 
10118   S.Diag(Callee->getLocation(),
10119          diag::note_ovl_candidate_disabled_by_extension);
10120 }
10121 
10122 /// Generates a 'note' diagnostic for an overload candidate.  We've
10123 /// already generated a primary error at the call site.
10124 ///
10125 /// It really does need to be a single diagnostic with its caret
10126 /// pointed at the candidate declaration.  Yes, this creates some
10127 /// major challenges of technical writing.  Yes, this makes pointing
10128 /// out problems with specific arguments quite awkward.  It's still
10129 /// better than generating twenty screens of text for every failed
10130 /// overload.
10131 ///
10132 /// It would be great to be able to express per-candidate problems
10133 /// more richly for those diagnostic clients that cared, but we'd
10134 /// still have to be just as careful with the default diagnostics.
10135 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10136                                   unsigned NumArgs,
10137                                   bool TakingCandidateAddress) {
10138   FunctionDecl *Fn = Cand->Function;
10139 
10140   // Note deleted candidates, but only if they're viable.
10141   if (Cand->Viable) {
10142     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10143       std::string FnDesc;
10144       OverloadCandidateKind FnKind =
10145         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10146 
10147       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10148         << FnKind << FnDesc
10149         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10150       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10151       return;
10152     }
10153 
10154     // We don't really have anything else to say about viable candidates.
10155     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10156     return;
10157   }
10158 
10159   switch (Cand->FailureKind) {
10160   case ovl_fail_too_many_arguments:
10161   case ovl_fail_too_few_arguments:
10162     return DiagnoseArityMismatch(S, Cand, NumArgs);
10163 
10164   case ovl_fail_bad_deduction:
10165     return DiagnoseBadDeduction(S, Cand, NumArgs,
10166                                 TakingCandidateAddress);
10167 
10168   case ovl_fail_illegal_constructor: {
10169     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10170       << (Fn->getPrimaryTemplate() ? 1 : 0);
10171     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10172     return;
10173   }
10174 
10175   case ovl_fail_trivial_conversion:
10176   case ovl_fail_bad_final_conversion:
10177   case ovl_fail_final_conversion_not_exact:
10178     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10179 
10180   case ovl_fail_bad_conversion: {
10181     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10182     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10183       if (Cand->Conversions[I].isBad())
10184         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10185 
10186     // FIXME: this currently happens when we're called from SemaInit
10187     // when user-conversion overload fails.  Figure out how to handle
10188     // those conditions and diagnose them well.
10189     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10190   }
10191 
10192   case ovl_fail_bad_target:
10193     return DiagnoseBadTarget(S, Cand);
10194 
10195   case ovl_fail_enable_if:
10196     return DiagnoseFailedEnableIfAttr(S, Cand);
10197 
10198   case ovl_fail_ext_disabled:
10199     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10200 
10201   case ovl_fail_inhctor_slice:
10202     // It's generally not interesting to note copy/move constructors here.
10203     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10204       return;
10205     S.Diag(Fn->getLocation(),
10206            diag::note_ovl_candidate_inherited_constructor_slice)
10207       << (Fn->getPrimaryTemplate() ? 1 : 0)
10208       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10209     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10210     return;
10211 
10212   case ovl_fail_addr_not_available: {
10213     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10214     (void)Available;
10215     assert(!Available);
10216     break;
10217   }
10218   case ovl_non_default_multiversion_function:
10219     // Do nothing, these should simply be ignored.
10220     break;
10221   }
10222 }
10223 
10224 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10225   // Desugar the type of the surrogate down to a function type,
10226   // retaining as many typedefs as possible while still showing
10227   // the function type (and, therefore, its parameter types).
10228   QualType FnType = Cand->Surrogate->getConversionType();
10229   bool isLValueReference = false;
10230   bool isRValueReference = false;
10231   bool isPointer = false;
10232   if (const LValueReferenceType *FnTypeRef =
10233         FnType->getAs<LValueReferenceType>()) {
10234     FnType = FnTypeRef->getPointeeType();
10235     isLValueReference = true;
10236   } else if (const RValueReferenceType *FnTypeRef =
10237                FnType->getAs<RValueReferenceType>()) {
10238     FnType = FnTypeRef->getPointeeType();
10239     isRValueReference = true;
10240   }
10241   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10242     FnType = FnTypePtr->getPointeeType();
10243     isPointer = true;
10244   }
10245   // Desugar down to a function type.
10246   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10247   // Reconstruct the pointer/reference as appropriate.
10248   if (isPointer) FnType = S.Context.getPointerType(FnType);
10249   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10250   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10251 
10252   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10253     << FnType;
10254 }
10255 
10256 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10257                                          SourceLocation OpLoc,
10258                                          OverloadCandidate *Cand) {
10259   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10260   std::string TypeStr("operator");
10261   TypeStr += Opc;
10262   TypeStr += "(";
10263   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10264   if (Cand->Conversions.size() == 1) {
10265     TypeStr += ")";
10266     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10267   } else {
10268     TypeStr += ", ";
10269     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10270     TypeStr += ")";
10271     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10272   }
10273 }
10274 
10275 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10276                                          OverloadCandidate *Cand) {
10277   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10278     if (ICS.isBad()) break; // all meaningless after first invalid
10279     if (!ICS.isAmbiguous()) continue;
10280 
10281     ICS.DiagnoseAmbiguousConversion(
10282         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10283   }
10284 }
10285 
10286 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10287   if (Cand->Function)
10288     return Cand->Function->getLocation();
10289   if (Cand->IsSurrogate)
10290     return Cand->Surrogate->getLocation();
10291   return SourceLocation();
10292 }
10293 
10294 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10295   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10296   case Sema::TDK_Success:
10297   case Sema::TDK_NonDependentConversionFailure:
10298     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10299 
10300   case Sema::TDK_Invalid:
10301   case Sema::TDK_Incomplete:
10302     return 1;
10303 
10304   case Sema::TDK_Underqualified:
10305   case Sema::TDK_Inconsistent:
10306     return 2;
10307 
10308   case Sema::TDK_SubstitutionFailure:
10309   case Sema::TDK_DeducedMismatch:
10310   case Sema::TDK_DeducedMismatchNested:
10311   case Sema::TDK_NonDeducedMismatch:
10312   case Sema::TDK_MiscellaneousDeductionFailure:
10313   case Sema::TDK_CUDATargetMismatch:
10314     return 3;
10315 
10316   case Sema::TDK_InstantiationDepth:
10317     return 4;
10318 
10319   case Sema::TDK_InvalidExplicitArguments:
10320     return 5;
10321 
10322   case Sema::TDK_TooManyArguments:
10323   case Sema::TDK_TooFewArguments:
10324     return 6;
10325   }
10326   llvm_unreachable("Unhandled deduction result");
10327 }
10328 
10329 namespace {
10330 struct CompareOverloadCandidatesForDisplay {
10331   Sema &S;
10332   SourceLocation Loc;
10333   size_t NumArgs;
10334   OverloadCandidateSet::CandidateSetKind CSK;
10335 
10336   CompareOverloadCandidatesForDisplay(
10337       Sema &S, SourceLocation Loc, size_t NArgs,
10338       OverloadCandidateSet::CandidateSetKind CSK)
10339       : S(S), NumArgs(NArgs), CSK(CSK) {}
10340 
10341   bool operator()(const OverloadCandidate *L,
10342                   const OverloadCandidate *R) {
10343     // Fast-path this check.
10344     if (L == R) return false;
10345 
10346     // Order first by viability.
10347     if (L->Viable) {
10348       if (!R->Viable) return true;
10349 
10350       // TODO: introduce a tri-valued comparison for overload
10351       // candidates.  Would be more worthwhile if we had a sort
10352       // that could exploit it.
10353       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10354         return true;
10355       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10356         return false;
10357     } else if (R->Viable)
10358       return false;
10359 
10360     assert(L->Viable == R->Viable);
10361 
10362     // Criteria by which we can sort non-viable candidates:
10363     if (!L->Viable) {
10364       // 1. Arity mismatches come after other candidates.
10365       if (L->FailureKind == ovl_fail_too_many_arguments ||
10366           L->FailureKind == ovl_fail_too_few_arguments) {
10367         if (R->FailureKind == ovl_fail_too_many_arguments ||
10368             R->FailureKind == ovl_fail_too_few_arguments) {
10369           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10370           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10371           if (LDist == RDist) {
10372             if (L->FailureKind == R->FailureKind)
10373               // Sort non-surrogates before surrogates.
10374               return !L->IsSurrogate && R->IsSurrogate;
10375             // Sort candidates requiring fewer parameters than there were
10376             // arguments given after candidates requiring more parameters
10377             // than there were arguments given.
10378             return L->FailureKind == ovl_fail_too_many_arguments;
10379           }
10380           return LDist < RDist;
10381         }
10382         return false;
10383       }
10384       if (R->FailureKind == ovl_fail_too_many_arguments ||
10385           R->FailureKind == ovl_fail_too_few_arguments)
10386         return true;
10387 
10388       // 2. Bad conversions come first and are ordered by the number
10389       // of bad conversions and quality of good conversions.
10390       if (L->FailureKind == ovl_fail_bad_conversion) {
10391         if (R->FailureKind != ovl_fail_bad_conversion)
10392           return true;
10393 
10394         // The conversion that can be fixed with a smaller number of changes,
10395         // comes first.
10396         unsigned numLFixes = L->Fix.NumConversionsFixed;
10397         unsigned numRFixes = R->Fix.NumConversionsFixed;
10398         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10399         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10400         if (numLFixes != numRFixes) {
10401           return numLFixes < numRFixes;
10402         }
10403 
10404         // If there's any ordering between the defined conversions...
10405         // FIXME: this might not be transitive.
10406         assert(L->Conversions.size() == R->Conversions.size());
10407 
10408         int leftBetter = 0;
10409         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10410         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10411           switch (CompareImplicitConversionSequences(S, Loc,
10412                                                      L->Conversions[I],
10413                                                      R->Conversions[I])) {
10414           case ImplicitConversionSequence::Better:
10415             leftBetter++;
10416             break;
10417 
10418           case ImplicitConversionSequence::Worse:
10419             leftBetter--;
10420             break;
10421 
10422           case ImplicitConversionSequence::Indistinguishable:
10423             break;
10424           }
10425         }
10426         if (leftBetter > 0) return true;
10427         if (leftBetter < 0) return false;
10428 
10429       } else if (R->FailureKind == ovl_fail_bad_conversion)
10430         return false;
10431 
10432       if (L->FailureKind == ovl_fail_bad_deduction) {
10433         if (R->FailureKind != ovl_fail_bad_deduction)
10434           return true;
10435 
10436         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10437           return RankDeductionFailure(L->DeductionFailure)
10438                < RankDeductionFailure(R->DeductionFailure);
10439       } else if (R->FailureKind == ovl_fail_bad_deduction)
10440         return false;
10441 
10442       // TODO: others?
10443     }
10444 
10445     // Sort everything else by location.
10446     SourceLocation LLoc = GetLocationForCandidate(L);
10447     SourceLocation RLoc = GetLocationForCandidate(R);
10448 
10449     // Put candidates without locations (e.g. builtins) at the end.
10450     if (LLoc.isInvalid()) return false;
10451     if (RLoc.isInvalid()) return true;
10452 
10453     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10454   }
10455 };
10456 }
10457 
10458 /// CompleteNonViableCandidate - Normally, overload resolution only
10459 /// computes up to the first bad conversion. Produces the FixIt set if
10460 /// possible.
10461 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10462                                        ArrayRef<Expr *> Args) {
10463   assert(!Cand->Viable);
10464 
10465   // Don't do anything on failures other than bad conversion.
10466   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10467 
10468   // We only want the FixIts if all the arguments can be corrected.
10469   bool Unfixable = false;
10470   // Use a implicit copy initialization to check conversion fixes.
10471   Cand->Fix.setConversionChecker(TryCopyInitialization);
10472 
10473   // Attempt to fix the bad conversion.
10474   unsigned ConvCount = Cand->Conversions.size();
10475   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10476        ++ConvIdx) {
10477     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10478     if (Cand->Conversions[ConvIdx].isInitialized() &&
10479         Cand->Conversions[ConvIdx].isBad()) {
10480       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10481       break;
10482     }
10483   }
10484 
10485   // FIXME: this should probably be preserved from the overload
10486   // operation somehow.
10487   bool SuppressUserConversions = false;
10488 
10489   unsigned ConvIdx = 0;
10490   ArrayRef<QualType> ParamTypes;
10491 
10492   if (Cand->IsSurrogate) {
10493     QualType ConvType
10494       = Cand->Surrogate->getConversionType().getNonReferenceType();
10495     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10496       ConvType = ConvPtrType->getPointeeType();
10497     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10498     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10499     ConvIdx = 1;
10500   } else if (Cand->Function) {
10501     ParamTypes =
10502         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10503     if (isa<CXXMethodDecl>(Cand->Function) &&
10504         !isa<CXXConstructorDecl>(Cand->Function)) {
10505       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10506       ConvIdx = 1;
10507     }
10508   } else {
10509     // Builtin operator.
10510     assert(ConvCount <= 3);
10511     ParamTypes = Cand->BuiltinParamTypes;
10512   }
10513 
10514   // Fill in the rest of the conversions.
10515   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10516     if (Cand->Conversions[ConvIdx].isInitialized()) {
10517       // We've already checked this conversion.
10518     } else if (ArgIdx < ParamTypes.size()) {
10519       if (ParamTypes[ArgIdx]->isDependentType())
10520         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10521             Args[ArgIdx]->getType());
10522       else {
10523         Cand->Conversions[ConvIdx] =
10524             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10525                                   SuppressUserConversions,
10526                                   /*InOverloadResolution=*/true,
10527                                   /*AllowObjCWritebackConversion=*/
10528                                   S.getLangOpts().ObjCAutoRefCount);
10529         // Store the FixIt in the candidate if it exists.
10530         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10531           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10532       }
10533     } else
10534       Cand->Conversions[ConvIdx].setEllipsis();
10535   }
10536 }
10537 
10538 /// When overload resolution fails, prints diagnostic messages containing the
10539 /// candidates in the candidate set.
10540 void OverloadCandidateSet::NoteCandidates(
10541     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10542     StringRef Opc, SourceLocation OpLoc,
10543     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10544   // Sort the candidates by viability and position.  Sorting directly would
10545   // be prohibitive, so we make a set of pointers and sort those.
10546   SmallVector<OverloadCandidate*, 32> Cands;
10547   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10548   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10549     if (!Filter(*Cand))
10550       continue;
10551     if (Cand->Viable)
10552       Cands.push_back(Cand);
10553     else if (OCD == OCD_AllCandidates) {
10554       CompleteNonViableCandidate(S, Cand, Args);
10555       if (Cand->Function || Cand->IsSurrogate)
10556         Cands.push_back(Cand);
10557       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10558       // want to list every possible builtin candidate.
10559     }
10560   }
10561 
10562   std::stable_sort(Cands.begin(), Cands.end(),
10563             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10564 
10565   bool ReportedAmbiguousConversions = false;
10566 
10567   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10568   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10569   unsigned CandsShown = 0;
10570   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10571     OverloadCandidate *Cand = *I;
10572 
10573     // Set an arbitrary limit on the number of candidate functions we'll spam
10574     // the user with.  FIXME: This limit should depend on details of the
10575     // candidate list.
10576     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10577       break;
10578     }
10579     ++CandsShown;
10580 
10581     if (Cand->Function)
10582       NoteFunctionCandidate(S, Cand, Args.size(),
10583                             /*TakingCandidateAddress=*/false);
10584     else if (Cand->IsSurrogate)
10585       NoteSurrogateCandidate(S, Cand);
10586     else {
10587       assert(Cand->Viable &&
10588              "Non-viable built-in candidates are not added to Cands.");
10589       // Generally we only see ambiguities including viable builtin
10590       // operators if overload resolution got screwed up by an
10591       // ambiguous user-defined conversion.
10592       //
10593       // FIXME: It's quite possible for different conversions to see
10594       // different ambiguities, though.
10595       if (!ReportedAmbiguousConversions) {
10596         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10597         ReportedAmbiguousConversions = true;
10598       }
10599 
10600       // If this is a viable builtin, print it.
10601       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10602     }
10603   }
10604 
10605   if (I != E)
10606     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10607 }
10608 
10609 static SourceLocation
10610 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10611   return Cand->Specialization ? Cand->Specialization->getLocation()
10612                               : SourceLocation();
10613 }
10614 
10615 namespace {
10616 struct CompareTemplateSpecCandidatesForDisplay {
10617   Sema &S;
10618   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10619 
10620   bool operator()(const TemplateSpecCandidate *L,
10621                   const TemplateSpecCandidate *R) {
10622     // Fast-path this check.
10623     if (L == R)
10624       return false;
10625 
10626     // Assuming that both candidates are not matches...
10627 
10628     // Sort by the ranking of deduction failures.
10629     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10630       return RankDeductionFailure(L->DeductionFailure) <
10631              RankDeductionFailure(R->DeductionFailure);
10632 
10633     // Sort everything else by location.
10634     SourceLocation LLoc = GetLocationForCandidate(L);
10635     SourceLocation RLoc = GetLocationForCandidate(R);
10636 
10637     // Put candidates without locations (e.g. builtins) at the end.
10638     if (LLoc.isInvalid())
10639       return false;
10640     if (RLoc.isInvalid())
10641       return true;
10642 
10643     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10644   }
10645 };
10646 }
10647 
10648 /// Diagnose a template argument deduction failure.
10649 /// We are treating these failures as overload failures due to bad
10650 /// deductions.
10651 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10652                                                  bool ForTakingAddress) {
10653   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10654                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10655 }
10656 
10657 void TemplateSpecCandidateSet::destroyCandidates() {
10658   for (iterator i = begin(), e = end(); i != e; ++i) {
10659     i->DeductionFailure.Destroy();
10660   }
10661 }
10662 
10663 void TemplateSpecCandidateSet::clear() {
10664   destroyCandidates();
10665   Candidates.clear();
10666 }
10667 
10668 /// NoteCandidates - When no template specialization match is found, prints
10669 /// diagnostic messages containing the non-matching specializations that form
10670 /// the candidate set.
10671 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10672 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10673 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10674   // Sort the candidates by position (assuming no candidate is a match).
10675   // Sorting directly would be prohibitive, so we make a set of pointers
10676   // and sort those.
10677   SmallVector<TemplateSpecCandidate *, 32> Cands;
10678   Cands.reserve(size());
10679   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10680     if (Cand->Specialization)
10681       Cands.push_back(Cand);
10682     // Otherwise, this is a non-matching builtin candidate.  We do not,
10683     // in general, want to list every possible builtin candidate.
10684   }
10685 
10686   std::sort(Cands.begin(), Cands.end(),
10687             CompareTemplateSpecCandidatesForDisplay(S));
10688 
10689   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10690   // for generalization purposes (?).
10691   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10692 
10693   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10694   unsigned CandsShown = 0;
10695   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10696     TemplateSpecCandidate *Cand = *I;
10697 
10698     // Set an arbitrary limit on the number of candidates we'll spam
10699     // the user with.  FIXME: This limit should depend on details of the
10700     // candidate list.
10701     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10702       break;
10703     ++CandsShown;
10704 
10705     assert(Cand->Specialization &&
10706            "Non-matching built-in candidates are not added to Cands.");
10707     Cand->NoteDeductionFailure(S, ForTakingAddress);
10708   }
10709 
10710   if (I != E)
10711     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10712 }
10713 
10714 // [PossiblyAFunctionType]  -->   [Return]
10715 // NonFunctionType --> NonFunctionType
10716 // R (A) --> R(A)
10717 // R (*)(A) --> R (A)
10718 // R (&)(A) --> R (A)
10719 // R (S::*)(A) --> R (A)
10720 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10721   QualType Ret = PossiblyAFunctionType;
10722   if (const PointerType *ToTypePtr =
10723     PossiblyAFunctionType->getAs<PointerType>())
10724     Ret = ToTypePtr->getPointeeType();
10725   else if (const ReferenceType *ToTypeRef =
10726     PossiblyAFunctionType->getAs<ReferenceType>())
10727     Ret = ToTypeRef->getPointeeType();
10728   else if (const MemberPointerType *MemTypePtr =
10729     PossiblyAFunctionType->getAs<MemberPointerType>())
10730     Ret = MemTypePtr->getPointeeType();
10731   Ret =
10732     Context.getCanonicalType(Ret).getUnqualifiedType();
10733   return Ret;
10734 }
10735 
10736 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10737                                  bool Complain = true) {
10738   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10739       S.DeduceReturnType(FD, Loc, Complain))
10740     return true;
10741 
10742   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10743   if (S.getLangOpts().CPlusPlus17 &&
10744       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10745       !S.ResolveExceptionSpec(Loc, FPT))
10746     return true;
10747 
10748   return false;
10749 }
10750 
10751 namespace {
10752 // A helper class to help with address of function resolution
10753 // - allows us to avoid passing around all those ugly parameters
10754 class AddressOfFunctionResolver {
10755   Sema& S;
10756   Expr* SourceExpr;
10757   const QualType& TargetType;
10758   QualType TargetFunctionType; // Extracted function type from target type
10759 
10760   bool Complain;
10761   //DeclAccessPair& ResultFunctionAccessPair;
10762   ASTContext& Context;
10763 
10764   bool TargetTypeIsNonStaticMemberFunction;
10765   bool FoundNonTemplateFunction;
10766   bool StaticMemberFunctionFromBoundPointer;
10767   bool HasComplained;
10768 
10769   OverloadExpr::FindResult OvlExprInfo;
10770   OverloadExpr *OvlExpr;
10771   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10772   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10773   TemplateSpecCandidateSet FailedCandidates;
10774 
10775 public:
10776   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10777                             const QualType &TargetType, bool Complain)
10778       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10779         Complain(Complain), Context(S.getASTContext()),
10780         TargetTypeIsNonStaticMemberFunction(
10781             !!TargetType->getAs<MemberPointerType>()),
10782         FoundNonTemplateFunction(false),
10783         StaticMemberFunctionFromBoundPointer(false),
10784         HasComplained(false),
10785         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10786         OvlExpr(OvlExprInfo.Expression),
10787         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10788     ExtractUnqualifiedFunctionTypeFromTargetType();
10789 
10790     if (TargetFunctionType->isFunctionType()) {
10791       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10792         if (!UME->isImplicitAccess() &&
10793             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10794           StaticMemberFunctionFromBoundPointer = true;
10795     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10796       DeclAccessPair dap;
10797       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10798               OvlExpr, false, &dap)) {
10799         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10800           if (!Method->isStatic()) {
10801             // If the target type is a non-function type and the function found
10802             // is a non-static member function, pretend as if that was the
10803             // target, it's the only possible type to end up with.
10804             TargetTypeIsNonStaticMemberFunction = true;
10805 
10806             // And skip adding the function if its not in the proper form.
10807             // We'll diagnose this due to an empty set of functions.
10808             if (!OvlExprInfo.HasFormOfMemberPointer)
10809               return;
10810           }
10811 
10812         Matches.push_back(std::make_pair(dap, Fn));
10813       }
10814       return;
10815     }
10816 
10817     if (OvlExpr->hasExplicitTemplateArgs())
10818       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10819 
10820     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10821       // C++ [over.over]p4:
10822       //   If more than one function is selected, [...]
10823       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10824         if (FoundNonTemplateFunction)
10825           EliminateAllTemplateMatches();
10826         else
10827           EliminateAllExceptMostSpecializedTemplate();
10828       }
10829     }
10830 
10831     if (S.getLangOpts().CUDA && Matches.size() > 1)
10832       EliminateSuboptimalCudaMatches();
10833   }
10834 
10835   bool hasComplained() const { return HasComplained; }
10836 
10837 private:
10838   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10839     QualType Discard;
10840     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10841            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10842   }
10843 
10844   /// \return true if A is considered a better overload candidate for the
10845   /// desired type than B.
10846   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10847     // If A doesn't have exactly the correct type, we don't want to classify it
10848     // as "better" than anything else. This way, the user is required to
10849     // disambiguate for us if there are multiple candidates and no exact match.
10850     return candidateHasExactlyCorrectType(A) &&
10851            (!candidateHasExactlyCorrectType(B) ||
10852             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10853   }
10854 
10855   /// \return true if we were able to eliminate all but one overload candidate,
10856   /// false otherwise.
10857   bool eliminiateSuboptimalOverloadCandidates() {
10858     // Same algorithm as overload resolution -- one pass to pick the "best",
10859     // another pass to be sure that nothing is better than the best.
10860     auto Best = Matches.begin();
10861     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10862       if (isBetterCandidate(I->second, Best->second))
10863         Best = I;
10864 
10865     const FunctionDecl *BestFn = Best->second;
10866     auto IsBestOrInferiorToBest = [this, BestFn](
10867         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10868       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10869     };
10870 
10871     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10872     // option, so we can potentially give the user a better error
10873     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10874       return false;
10875     Matches[0] = *Best;
10876     Matches.resize(1);
10877     return true;
10878   }
10879 
10880   bool isTargetTypeAFunction() const {
10881     return TargetFunctionType->isFunctionType();
10882   }
10883 
10884   // [ToType]     [Return]
10885 
10886   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10887   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10888   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10889   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10890     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10891   }
10892 
10893   // return true if any matching specializations were found
10894   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10895                                    const DeclAccessPair& CurAccessFunPair) {
10896     if (CXXMethodDecl *Method
10897               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10898       // Skip non-static function templates when converting to pointer, and
10899       // static when converting to member pointer.
10900       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10901         return false;
10902     }
10903     else if (TargetTypeIsNonStaticMemberFunction)
10904       return false;
10905 
10906     // C++ [over.over]p2:
10907     //   If the name is a function template, template argument deduction is
10908     //   done (14.8.2.2), and if the argument deduction succeeds, the
10909     //   resulting template argument list is used to generate a single
10910     //   function template specialization, which is added to the set of
10911     //   overloaded functions considered.
10912     FunctionDecl *Specialization = nullptr;
10913     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10914     if (Sema::TemplateDeductionResult Result
10915           = S.DeduceTemplateArguments(FunctionTemplate,
10916                                       &OvlExplicitTemplateArgs,
10917                                       TargetFunctionType, Specialization,
10918                                       Info, /*IsAddressOfFunction*/true)) {
10919       // Make a note of the failed deduction for diagnostics.
10920       FailedCandidates.addCandidate()
10921           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10922                MakeDeductionFailureInfo(Context, Result, Info));
10923       return false;
10924     }
10925 
10926     // Template argument deduction ensures that we have an exact match or
10927     // compatible pointer-to-function arguments that would be adjusted by ICS.
10928     // This function template specicalization works.
10929     assert(S.isSameOrCompatibleFunctionType(
10930               Context.getCanonicalType(Specialization->getType()),
10931               Context.getCanonicalType(TargetFunctionType)));
10932 
10933     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10934       return false;
10935 
10936     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10937     return true;
10938   }
10939 
10940   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10941                                       const DeclAccessPair& CurAccessFunPair) {
10942     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10943       // Skip non-static functions when converting to pointer, and static
10944       // when converting to member pointer.
10945       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10946         return false;
10947     }
10948     else if (TargetTypeIsNonStaticMemberFunction)
10949       return false;
10950 
10951     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10952       if (S.getLangOpts().CUDA)
10953         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10954           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10955             return false;
10956       if (FunDecl->isMultiVersion()) {
10957         const auto *TA = FunDecl->getAttr<TargetAttr>();
10958         assert(TA && "Multiversioned functions require a target attribute");
10959         if (!TA->isDefaultVersion())
10960           return false;
10961       }
10962 
10963       // If any candidate has a placeholder return type, trigger its deduction
10964       // now.
10965       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10966                                Complain)) {
10967         HasComplained |= Complain;
10968         return false;
10969       }
10970 
10971       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10972         return false;
10973 
10974       // If we're in C, we need to support types that aren't exactly identical.
10975       if (!S.getLangOpts().CPlusPlus ||
10976           candidateHasExactlyCorrectType(FunDecl)) {
10977         Matches.push_back(std::make_pair(
10978             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10979         FoundNonTemplateFunction = true;
10980         return true;
10981       }
10982     }
10983 
10984     return false;
10985   }
10986 
10987   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10988     bool Ret = false;
10989 
10990     // If the overload expression doesn't have the form of a pointer to
10991     // member, don't try to convert it to a pointer-to-member type.
10992     if (IsInvalidFormOfPointerToMemberFunction())
10993       return false;
10994 
10995     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10996                                E = OvlExpr->decls_end();
10997          I != E; ++I) {
10998       // Look through any using declarations to find the underlying function.
10999       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11000 
11001       // C++ [over.over]p3:
11002       //   Non-member functions and static member functions match
11003       //   targets of type "pointer-to-function" or "reference-to-function."
11004       //   Nonstatic member functions match targets of
11005       //   type "pointer-to-member-function."
11006       // Note that according to DR 247, the containing class does not matter.
11007       if (FunctionTemplateDecl *FunctionTemplate
11008                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11009         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11010           Ret = true;
11011       }
11012       // If we have explicit template arguments supplied, skip non-templates.
11013       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11014                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11015         Ret = true;
11016     }
11017     assert(Ret || Matches.empty());
11018     return Ret;
11019   }
11020 
11021   void EliminateAllExceptMostSpecializedTemplate() {
11022     //   [...] and any given function template specialization F1 is
11023     //   eliminated if the set contains a second function template
11024     //   specialization whose function template is more specialized
11025     //   than the function template of F1 according to the partial
11026     //   ordering rules of 14.5.5.2.
11027 
11028     // The algorithm specified above is quadratic. We instead use a
11029     // two-pass algorithm (similar to the one used to identify the
11030     // best viable function in an overload set) that identifies the
11031     // best function template (if it exists).
11032 
11033     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11034     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11035       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11036 
11037     // TODO: It looks like FailedCandidates does not serve much purpose
11038     // here, since the no_viable diagnostic has index 0.
11039     UnresolvedSetIterator Result = S.getMostSpecialized(
11040         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11041         SourceExpr->getLocStart(), S.PDiag(),
11042         S.PDiag(diag::err_addr_ovl_ambiguous)
11043           << Matches[0].second->getDeclName(),
11044         S.PDiag(diag::note_ovl_candidate)
11045           << (unsigned)oc_function_template,
11046         Complain, TargetFunctionType);
11047 
11048     if (Result != MatchesCopy.end()) {
11049       // Make it the first and only element
11050       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11051       Matches[0].second = cast<FunctionDecl>(*Result);
11052       Matches.resize(1);
11053     } else
11054       HasComplained |= Complain;
11055   }
11056 
11057   void EliminateAllTemplateMatches() {
11058     //   [...] any function template specializations in the set are
11059     //   eliminated if the set also contains a non-template function, [...]
11060     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11061       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11062         ++I;
11063       else {
11064         Matches[I] = Matches[--N];
11065         Matches.resize(N);
11066       }
11067     }
11068   }
11069 
11070   void EliminateSuboptimalCudaMatches() {
11071     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11072   }
11073 
11074 public:
11075   void ComplainNoMatchesFound() const {
11076     assert(Matches.empty());
11077     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11078         << OvlExpr->getName() << TargetFunctionType
11079         << OvlExpr->getSourceRange();
11080     if (FailedCandidates.empty())
11081       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11082                                   /*TakingAddress=*/true);
11083     else {
11084       // We have some deduction failure messages. Use them to diagnose
11085       // the function templates, and diagnose the non-template candidates
11086       // normally.
11087       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11088                                  IEnd = OvlExpr->decls_end();
11089            I != IEnd; ++I)
11090         if (FunctionDecl *Fun =
11091                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11092           if (!functionHasPassObjectSizeParams(Fun))
11093             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11094                                     /*TakingAddress=*/true);
11095       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11096     }
11097   }
11098 
11099   bool IsInvalidFormOfPointerToMemberFunction() const {
11100     return TargetTypeIsNonStaticMemberFunction &&
11101       !OvlExprInfo.HasFormOfMemberPointer;
11102   }
11103 
11104   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11105       // TODO: Should we condition this on whether any functions might
11106       // have matched, or is it more appropriate to do that in callers?
11107       // TODO: a fixit wouldn't hurt.
11108       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11109         << TargetType << OvlExpr->getSourceRange();
11110   }
11111 
11112   bool IsStaticMemberFunctionFromBoundPointer() const {
11113     return StaticMemberFunctionFromBoundPointer;
11114   }
11115 
11116   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11117     S.Diag(OvlExpr->getLocStart(),
11118            diag::err_invalid_form_pointer_member_function)
11119       << OvlExpr->getSourceRange();
11120   }
11121 
11122   void ComplainOfInvalidConversion() const {
11123     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11124       << OvlExpr->getName() << TargetType;
11125   }
11126 
11127   void ComplainMultipleMatchesFound() const {
11128     assert(Matches.size() > 1);
11129     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11130       << OvlExpr->getName()
11131       << OvlExpr->getSourceRange();
11132     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11133                                 /*TakingAddress=*/true);
11134   }
11135 
11136   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11137 
11138   int getNumMatches() const { return Matches.size(); }
11139 
11140   FunctionDecl* getMatchingFunctionDecl() const {
11141     if (Matches.size() != 1) return nullptr;
11142     return Matches[0].second;
11143   }
11144 
11145   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11146     if (Matches.size() != 1) return nullptr;
11147     return &Matches[0].first;
11148   }
11149 };
11150 }
11151 
11152 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11153 /// an overloaded function (C++ [over.over]), where @p From is an
11154 /// expression with overloaded function type and @p ToType is the type
11155 /// we're trying to resolve to. For example:
11156 ///
11157 /// @code
11158 /// int f(double);
11159 /// int f(int);
11160 ///
11161 /// int (*pfd)(double) = f; // selects f(double)
11162 /// @endcode
11163 ///
11164 /// This routine returns the resulting FunctionDecl if it could be
11165 /// resolved, and NULL otherwise. When @p Complain is true, this
11166 /// routine will emit diagnostics if there is an error.
11167 FunctionDecl *
11168 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11169                                          QualType TargetType,
11170                                          bool Complain,
11171                                          DeclAccessPair &FoundResult,
11172                                          bool *pHadMultipleCandidates) {
11173   assert(AddressOfExpr->getType() == Context.OverloadTy);
11174 
11175   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11176                                      Complain);
11177   int NumMatches = Resolver.getNumMatches();
11178   FunctionDecl *Fn = nullptr;
11179   bool ShouldComplain = Complain && !Resolver.hasComplained();
11180   if (NumMatches == 0 && ShouldComplain) {
11181     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11182       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11183     else
11184       Resolver.ComplainNoMatchesFound();
11185   }
11186   else if (NumMatches > 1 && ShouldComplain)
11187     Resolver.ComplainMultipleMatchesFound();
11188   else if (NumMatches == 1) {
11189     Fn = Resolver.getMatchingFunctionDecl();
11190     assert(Fn);
11191     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11192       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11193     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11194     if (Complain) {
11195       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11196         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11197       else
11198         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11199     }
11200   }
11201 
11202   if (pHadMultipleCandidates)
11203     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11204   return Fn;
11205 }
11206 
11207 /// \brief Given an expression that refers to an overloaded function, try to
11208 /// resolve that function to a single function that can have its address taken.
11209 /// This will modify `Pair` iff it returns non-null.
11210 ///
11211 /// This routine can only realistically succeed if all but one candidates in the
11212 /// overload set for SrcExpr cannot have their addresses taken.
11213 FunctionDecl *
11214 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11215                                                   DeclAccessPair &Pair) {
11216   OverloadExpr::FindResult R = OverloadExpr::find(E);
11217   OverloadExpr *Ovl = R.Expression;
11218   FunctionDecl *Result = nullptr;
11219   DeclAccessPair DAP;
11220   // Don't use the AddressOfResolver because we're specifically looking for
11221   // cases where we have one overload candidate that lacks
11222   // enable_if/pass_object_size/...
11223   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11224     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11225     if (!FD)
11226       return nullptr;
11227 
11228     if (!checkAddressOfFunctionIsAvailable(FD))
11229       continue;
11230 
11231     // We have more than one result; quit.
11232     if (Result)
11233       return nullptr;
11234     DAP = I.getPair();
11235     Result = FD;
11236   }
11237 
11238   if (Result)
11239     Pair = DAP;
11240   return Result;
11241 }
11242 
11243 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11244 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11245 /// will perform access checks, diagnose the use of the resultant decl, and, if
11246 /// requested, potentially perform a function-to-pointer decay.
11247 ///
11248 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11249 /// Otherwise, returns true. This may emit diagnostics and return true.
11250 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11251     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11252   Expr *E = SrcExpr.get();
11253   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11254 
11255   DeclAccessPair DAP;
11256   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11257   if (!Found)
11258     return false;
11259 
11260   // Emitting multiple diagnostics for a function that is both inaccessible and
11261   // unavailable is consistent with our behavior elsewhere. So, always check
11262   // for both.
11263   DiagnoseUseOfDecl(Found, E->getExprLoc());
11264   CheckAddressOfMemberAccess(E, DAP);
11265   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11266   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11267     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11268   else
11269     SrcExpr = Fixed;
11270   return true;
11271 }
11272 
11273 /// \brief Given an expression that refers to an overloaded function, try to
11274 /// resolve that overloaded function expression down to a single function.
11275 ///
11276 /// This routine can only resolve template-ids that refer to a single function
11277 /// template, where that template-id refers to a single template whose template
11278 /// arguments are either provided by the template-id or have defaults,
11279 /// as described in C++0x [temp.arg.explicit]p3.
11280 ///
11281 /// If no template-ids are found, no diagnostics are emitted and NULL is
11282 /// returned.
11283 FunctionDecl *
11284 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11285                                                   bool Complain,
11286                                                   DeclAccessPair *FoundResult) {
11287   // C++ [over.over]p1:
11288   //   [...] [Note: any redundant set of parentheses surrounding the
11289   //   overloaded function name is ignored (5.1). ]
11290   // C++ [over.over]p1:
11291   //   [...] The overloaded function name can be preceded by the &
11292   //   operator.
11293 
11294   // If we didn't actually find any template-ids, we're done.
11295   if (!ovl->hasExplicitTemplateArgs())
11296     return nullptr;
11297 
11298   TemplateArgumentListInfo ExplicitTemplateArgs;
11299   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11300   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11301 
11302   // Look through all of the overloaded functions, searching for one
11303   // whose type matches exactly.
11304   FunctionDecl *Matched = nullptr;
11305   for (UnresolvedSetIterator I = ovl->decls_begin(),
11306          E = ovl->decls_end(); I != E; ++I) {
11307     // C++0x [temp.arg.explicit]p3:
11308     //   [...] In contexts where deduction is done and fails, or in contexts
11309     //   where deduction is not done, if a template argument list is
11310     //   specified and it, along with any default template arguments,
11311     //   identifies a single function template specialization, then the
11312     //   template-id is an lvalue for the function template specialization.
11313     FunctionTemplateDecl *FunctionTemplate
11314       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11315 
11316     // C++ [over.over]p2:
11317     //   If the name is a function template, template argument deduction is
11318     //   done (14.8.2.2), and if the argument deduction succeeds, the
11319     //   resulting template argument list is used to generate a single
11320     //   function template specialization, which is added to the set of
11321     //   overloaded functions considered.
11322     FunctionDecl *Specialization = nullptr;
11323     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11324     if (TemplateDeductionResult Result
11325           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11326                                     Specialization, Info,
11327                                     /*IsAddressOfFunction*/true)) {
11328       // Make a note of the failed deduction for diagnostics.
11329       // TODO: Actually use the failed-deduction info?
11330       FailedCandidates.addCandidate()
11331           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11332                MakeDeductionFailureInfo(Context, Result, Info));
11333       continue;
11334     }
11335 
11336     assert(Specialization && "no specialization and no error?");
11337 
11338     // Multiple matches; we can't resolve to a single declaration.
11339     if (Matched) {
11340       if (Complain) {
11341         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11342           << ovl->getName();
11343         NoteAllOverloadCandidates(ovl);
11344       }
11345       return nullptr;
11346     }
11347 
11348     Matched = Specialization;
11349     if (FoundResult) *FoundResult = I.getPair();
11350   }
11351 
11352   if (Matched &&
11353       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11354     return nullptr;
11355 
11356   return Matched;
11357 }
11358 
11359 // Resolve and fix an overloaded expression that can be resolved
11360 // because it identifies a single function template specialization.
11361 //
11362 // Last three arguments should only be supplied if Complain = true
11363 //
11364 // Return true if it was logically possible to so resolve the
11365 // expression, regardless of whether or not it succeeded.  Always
11366 // returns true if 'complain' is set.
11367 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11368                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11369                       bool complain, SourceRange OpRangeForComplaining,
11370                                            QualType DestTypeForComplaining,
11371                                             unsigned DiagIDForComplaining) {
11372   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11373 
11374   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11375 
11376   DeclAccessPair found;
11377   ExprResult SingleFunctionExpression;
11378   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11379                            ovl.Expression, /*complain*/ false, &found)) {
11380     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11381       SrcExpr = ExprError();
11382       return true;
11383     }
11384 
11385     // It is only correct to resolve to an instance method if we're
11386     // resolving a form that's permitted to be a pointer to member.
11387     // Otherwise we'll end up making a bound member expression, which
11388     // is illegal in all the contexts we resolve like this.
11389     if (!ovl.HasFormOfMemberPointer &&
11390         isa<CXXMethodDecl>(fn) &&
11391         cast<CXXMethodDecl>(fn)->isInstance()) {
11392       if (!complain) return false;
11393 
11394       Diag(ovl.Expression->getExprLoc(),
11395            diag::err_bound_member_function)
11396         << 0 << ovl.Expression->getSourceRange();
11397 
11398       // TODO: I believe we only end up here if there's a mix of
11399       // static and non-static candidates (otherwise the expression
11400       // would have 'bound member' type, not 'overload' type).
11401       // Ideally we would note which candidate was chosen and why
11402       // the static candidates were rejected.
11403       SrcExpr = ExprError();
11404       return true;
11405     }
11406 
11407     // Fix the expression to refer to 'fn'.
11408     SingleFunctionExpression =
11409         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11410 
11411     // If desired, do function-to-pointer decay.
11412     if (doFunctionPointerConverion) {
11413       SingleFunctionExpression =
11414         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11415       if (SingleFunctionExpression.isInvalid()) {
11416         SrcExpr = ExprError();
11417         return true;
11418       }
11419     }
11420   }
11421 
11422   if (!SingleFunctionExpression.isUsable()) {
11423     if (complain) {
11424       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11425         << ovl.Expression->getName()
11426         << DestTypeForComplaining
11427         << OpRangeForComplaining
11428         << ovl.Expression->getQualifierLoc().getSourceRange();
11429       NoteAllOverloadCandidates(SrcExpr.get());
11430 
11431       SrcExpr = ExprError();
11432       return true;
11433     }
11434 
11435     return false;
11436   }
11437 
11438   SrcExpr = SingleFunctionExpression;
11439   return true;
11440 }
11441 
11442 /// \brief Add a single candidate to the overload set.
11443 static void AddOverloadedCallCandidate(Sema &S,
11444                                        DeclAccessPair FoundDecl,
11445                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11446                                        ArrayRef<Expr *> Args,
11447                                        OverloadCandidateSet &CandidateSet,
11448                                        bool PartialOverloading,
11449                                        bool KnownValid) {
11450   NamedDecl *Callee = FoundDecl.getDecl();
11451   if (isa<UsingShadowDecl>(Callee))
11452     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11453 
11454   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11455     if (ExplicitTemplateArgs) {
11456       assert(!KnownValid && "Explicit template arguments?");
11457       return;
11458     }
11459     // Prevent ill-formed function decls to be added as overload candidates.
11460     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11461       return;
11462 
11463     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11464                            /*SuppressUsedConversions=*/false,
11465                            PartialOverloading);
11466     return;
11467   }
11468 
11469   if (FunctionTemplateDecl *FuncTemplate
11470       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11471     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11472                                    ExplicitTemplateArgs, Args, CandidateSet,
11473                                    /*SuppressUsedConversions=*/false,
11474                                    PartialOverloading);
11475     return;
11476   }
11477 
11478   assert(!KnownValid && "unhandled case in overloaded call candidate");
11479 }
11480 
11481 /// \brief Add the overload candidates named by callee and/or found by argument
11482 /// dependent lookup to the given overload set.
11483 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11484                                        ArrayRef<Expr *> Args,
11485                                        OverloadCandidateSet &CandidateSet,
11486                                        bool PartialOverloading) {
11487 
11488 #ifndef NDEBUG
11489   // Verify that ArgumentDependentLookup is consistent with the rules
11490   // in C++0x [basic.lookup.argdep]p3:
11491   //
11492   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11493   //   and let Y be the lookup set produced by argument dependent
11494   //   lookup (defined as follows). If X contains
11495   //
11496   //     -- a declaration of a class member, or
11497   //
11498   //     -- a block-scope function declaration that is not a
11499   //        using-declaration, or
11500   //
11501   //     -- a declaration that is neither a function or a function
11502   //        template
11503   //
11504   //   then Y is empty.
11505 
11506   if (ULE->requiresADL()) {
11507     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11508            E = ULE->decls_end(); I != E; ++I) {
11509       assert(!(*I)->getDeclContext()->isRecord());
11510       assert(isa<UsingShadowDecl>(*I) ||
11511              !(*I)->getDeclContext()->isFunctionOrMethod());
11512       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11513     }
11514   }
11515 #endif
11516 
11517   // It would be nice to avoid this copy.
11518   TemplateArgumentListInfo TABuffer;
11519   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11520   if (ULE->hasExplicitTemplateArgs()) {
11521     ULE->copyTemplateArgumentsInto(TABuffer);
11522     ExplicitTemplateArgs = &TABuffer;
11523   }
11524 
11525   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11526          E = ULE->decls_end(); I != E; ++I)
11527     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11528                                CandidateSet, PartialOverloading,
11529                                /*KnownValid*/ true);
11530 
11531   if (ULE->requiresADL())
11532     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11533                                          Args, ExplicitTemplateArgs,
11534                                          CandidateSet, PartialOverloading);
11535 }
11536 
11537 /// Determine whether a declaration with the specified name could be moved into
11538 /// a different namespace.
11539 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11540   switch (Name.getCXXOverloadedOperator()) {
11541   case OO_New: case OO_Array_New:
11542   case OO_Delete: case OO_Array_Delete:
11543     return false;
11544 
11545   default:
11546     return true;
11547   }
11548 }
11549 
11550 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11551 /// template, where the non-dependent name was declared after the template
11552 /// was defined. This is common in code written for a compilers which do not
11553 /// correctly implement two-stage name lookup.
11554 ///
11555 /// Returns true if a viable candidate was found and a diagnostic was issued.
11556 static bool
11557 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11558                        const CXXScopeSpec &SS, LookupResult &R,
11559                        OverloadCandidateSet::CandidateSetKind CSK,
11560                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11561                        ArrayRef<Expr *> Args,
11562                        bool *DoDiagnoseEmptyLookup = nullptr) {
11563   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11564     return false;
11565 
11566   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11567     if (DC->isTransparentContext())
11568       continue;
11569 
11570     SemaRef.LookupQualifiedName(R, DC);
11571 
11572     if (!R.empty()) {
11573       R.suppressDiagnostics();
11574 
11575       if (isa<CXXRecordDecl>(DC)) {
11576         // Don't diagnose names we find in classes; we get much better
11577         // diagnostics for these from DiagnoseEmptyLookup.
11578         R.clear();
11579         if (DoDiagnoseEmptyLookup)
11580           *DoDiagnoseEmptyLookup = true;
11581         return false;
11582       }
11583 
11584       OverloadCandidateSet Candidates(FnLoc, CSK);
11585       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11586         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11587                                    ExplicitTemplateArgs, Args,
11588                                    Candidates, false, /*KnownValid*/ false);
11589 
11590       OverloadCandidateSet::iterator Best;
11591       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11592         // No viable functions. Don't bother the user with notes for functions
11593         // which don't work and shouldn't be found anyway.
11594         R.clear();
11595         return false;
11596       }
11597 
11598       // Find the namespaces where ADL would have looked, and suggest
11599       // declaring the function there instead.
11600       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11601       Sema::AssociatedClassSet AssociatedClasses;
11602       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11603                                                  AssociatedNamespaces,
11604                                                  AssociatedClasses);
11605       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11606       if (canBeDeclaredInNamespace(R.getLookupName())) {
11607         DeclContext *Std = SemaRef.getStdNamespace();
11608         for (Sema::AssociatedNamespaceSet::iterator
11609                it = AssociatedNamespaces.begin(),
11610                end = AssociatedNamespaces.end(); it != end; ++it) {
11611           // Never suggest declaring a function within namespace 'std'.
11612           if (Std && Std->Encloses(*it))
11613             continue;
11614 
11615           // Never suggest declaring a function within a namespace with a
11616           // reserved name, like __gnu_cxx.
11617           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11618           if (NS &&
11619               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11620             continue;
11621 
11622           SuggestedNamespaces.insert(*it);
11623         }
11624       }
11625 
11626       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11627         << R.getLookupName();
11628       if (SuggestedNamespaces.empty()) {
11629         SemaRef.Diag(Best->Function->getLocation(),
11630                      diag::note_not_found_by_two_phase_lookup)
11631           << R.getLookupName() << 0;
11632       } else if (SuggestedNamespaces.size() == 1) {
11633         SemaRef.Diag(Best->Function->getLocation(),
11634                      diag::note_not_found_by_two_phase_lookup)
11635           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11636       } else {
11637         // FIXME: It would be useful to list the associated namespaces here,
11638         // but the diagnostics infrastructure doesn't provide a way to produce
11639         // a localized representation of a list of items.
11640         SemaRef.Diag(Best->Function->getLocation(),
11641                      diag::note_not_found_by_two_phase_lookup)
11642           << R.getLookupName() << 2;
11643       }
11644 
11645       // Try to recover by calling this function.
11646       return true;
11647     }
11648 
11649     R.clear();
11650   }
11651 
11652   return false;
11653 }
11654 
11655 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11656 /// template, where the non-dependent operator was declared after the template
11657 /// was defined.
11658 ///
11659 /// Returns true if a viable candidate was found and a diagnostic was issued.
11660 static bool
11661 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11662                                SourceLocation OpLoc,
11663                                ArrayRef<Expr *> Args) {
11664   DeclarationName OpName =
11665     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11666   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11667   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11668                                 OverloadCandidateSet::CSK_Operator,
11669                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11670 }
11671 
11672 namespace {
11673 class BuildRecoveryCallExprRAII {
11674   Sema &SemaRef;
11675 public:
11676   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11677     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11678     SemaRef.IsBuildingRecoveryCallExpr = true;
11679   }
11680 
11681   ~BuildRecoveryCallExprRAII() {
11682     SemaRef.IsBuildingRecoveryCallExpr = false;
11683   }
11684 };
11685 
11686 }
11687 
11688 static std::unique_ptr<CorrectionCandidateCallback>
11689 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11690               bool HasTemplateArgs, bool AllowTypoCorrection) {
11691   if (!AllowTypoCorrection)
11692     return llvm::make_unique<NoTypoCorrectionCCC>();
11693   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11694                                                   HasTemplateArgs, ME);
11695 }
11696 
11697 /// Attempts to recover from a call where no functions were found.
11698 ///
11699 /// Returns true if new candidates were found.
11700 static ExprResult
11701 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11702                       UnresolvedLookupExpr *ULE,
11703                       SourceLocation LParenLoc,
11704                       MutableArrayRef<Expr *> Args,
11705                       SourceLocation RParenLoc,
11706                       bool EmptyLookup, bool AllowTypoCorrection) {
11707   // Do not try to recover if it is already building a recovery call.
11708   // This stops infinite loops for template instantiations like
11709   //
11710   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11711   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11712   //
11713   if (SemaRef.IsBuildingRecoveryCallExpr)
11714     return ExprError();
11715   BuildRecoveryCallExprRAII RCE(SemaRef);
11716 
11717   CXXScopeSpec SS;
11718   SS.Adopt(ULE->getQualifierLoc());
11719   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11720 
11721   TemplateArgumentListInfo TABuffer;
11722   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11723   if (ULE->hasExplicitTemplateArgs()) {
11724     ULE->copyTemplateArgumentsInto(TABuffer);
11725     ExplicitTemplateArgs = &TABuffer;
11726   }
11727 
11728   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11729                  Sema::LookupOrdinaryName);
11730   bool DoDiagnoseEmptyLookup = EmptyLookup;
11731   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11732                               OverloadCandidateSet::CSK_Normal,
11733                               ExplicitTemplateArgs, Args,
11734                               &DoDiagnoseEmptyLookup) &&
11735     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11736         S, SS, R,
11737         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11738                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11739         ExplicitTemplateArgs, Args)))
11740     return ExprError();
11741 
11742   assert(!R.empty() && "lookup results empty despite recovery");
11743 
11744   // If recovery created an ambiguity, just bail out.
11745   if (R.isAmbiguous()) {
11746     R.suppressDiagnostics();
11747     return ExprError();
11748   }
11749 
11750   // Build an implicit member call if appropriate.  Just drop the
11751   // casts and such from the call, we don't really care.
11752   ExprResult NewFn = ExprError();
11753   if ((*R.begin())->isCXXClassMember())
11754     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11755                                                     ExplicitTemplateArgs, S);
11756   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11757     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11758                                         ExplicitTemplateArgs);
11759   else
11760     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11761 
11762   if (NewFn.isInvalid())
11763     return ExprError();
11764 
11765   // This shouldn't cause an infinite loop because we're giving it
11766   // an expression with viable lookup results, which should never
11767   // end up here.
11768   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11769                                MultiExprArg(Args.data(), Args.size()),
11770                                RParenLoc);
11771 }
11772 
11773 /// \brief Constructs and populates an OverloadedCandidateSet from
11774 /// the given function.
11775 /// \returns true when an the ExprResult output parameter has been set.
11776 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11777                                   UnresolvedLookupExpr *ULE,
11778                                   MultiExprArg Args,
11779                                   SourceLocation RParenLoc,
11780                                   OverloadCandidateSet *CandidateSet,
11781                                   ExprResult *Result) {
11782 #ifndef NDEBUG
11783   if (ULE->requiresADL()) {
11784     // To do ADL, we must have found an unqualified name.
11785     assert(!ULE->getQualifier() && "qualified name with ADL");
11786 
11787     // We don't perform ADL for implicit declarations of builtins.
11788     // Verify that this was correctly set up.
11789     FunctionDecl *F;
11790     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11791         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11792         F->getBuiltinID() && F->isImplicit())
11793       llvm_unreachable("performing ADL for builtin");
11794 
11795     // We don't perform ADL in C.
11796     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11797   }
11798 #endif
11799 
11800   UnbridgedCastsSet UnbridgedCasts;
11801   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11802     *Result = ExprError();
11803     return true;
11804   }
11805 
11806   // Add the functions denoted by the callee to the set of candidate
11807   // functions, including those from argument-dependent lookup.
11808   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11809 
11810   if (getLangOpts().MSVCCompat &&
11811       CurContext->isDependentContext() && !isSFINAEContext() &&
11812       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11813 
11814     OverloadCandidateSet::iterator Best;
11815     if (CandidateSet->empty() ||
11816         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11817             OR_No_Viable_Function) {
11818       // In Microsoft mode, if we are inside a template class member function then
11819       // create a type dependent CallExpr. The goal is to postpone name lookup
11820       // to instantiation time to be able to search into type dependent base
11821       // classes.
11822       CallExpr *CE = new (Context) CallExpr(
11823           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11824       CE->setTypeDependent(true);
11825       CE->setValueDependent(true);
11826       CE->setInstantiationDependent(true);
11827       *Result = CE;
11828       return true;
11829     }
11830   }
11831 
11832   if (CandidateSet->empty())
11833     return false;
11834 
11835   UnbridgedCasts.restore();
11836   return false;
11837 }
11838 
11839 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11840 /// the completed call expression. If overload resolution fails, emits
11841 /// diagnostics and returns ExprError()
11842 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11843                                            UnresolvedLookupExpr *ULE,
11844                                            SourceLocation LParenLoc,
11845                                            MultiExprArg Args,
11846                                            SourceLocation RParenLoc,
11847                                            Expr *ExecConfig,
11848                                            OverloadCandidateSet *CandidateSet,
11849                                            OverloadCandidateSet::iterator *Best,
11850                                            OverloadingResult OverloadResult,
11851                                            bool AllowTypoCorrection) {
11852   if (CandidateSet->empty())
11853     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11854                                  RParenLoc, /*EmptyLookup=*/true,
11855                                  AllowTypoCorrection);
11856 
11857   switch (OverloadResult) {
11858   case OR_Success: {
11859     FunctionDecl *FDecl = (*Best)->Function;
11860     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11861     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11862       return ExprError();
11863     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11864     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11865                                          ExecConfig);
11866   }
11867 
11868   case OR_No_Viable_Function: {
11869     // Try to recover by looking for viable functions which the user might
11870     // have meant to call.
11871     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11872                                                 Args, RParenLoc,
11873                                                 /*EmptyLookup=*/false,
11874                                                 AllowTypoCorrection);
11875     if (!Recovery.isInvalid())
11876       return Recovery;
11877 
11878     // If the user passes in a function that we can't take the address of, we
11879     // generally end up emitting really bad error messages. Here, we attempt to
11880     // emit better ones.
11881     for (const Expr *Arg : Args) {
11882       if (!Arg->getType()->isFunctionType())
11883         continue;
11884       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11885         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11886         if (FD &&
11887             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11888                                                        Arg->getExprLoc()))
11889           return ExprError();
11890       }
11891     }
11892 
11893     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11894         << ULE->getName() << Fn->getSourceRange();
11895     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11896     break;
11897   }
11898 
11899   case OR_Ambiguous:
11900     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11901       << ULE->getName() << Fn->getSourceRange();
11902     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11903     break;
11904 
11905   case OR_Deleted: {
11906     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11907       << (*Best)->Function->isDeleted()
11908       << ULE->getName()
11909       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11910       << Fn->getSourceRange();
11911     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11912 
11913     // We emitted an error for the unvailable/deleted function call but keep
11914     // the call in the AST.
11915     FunctionDecl *FDecl = (*Best)->Function;
11916     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11917     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11918                                          ExecConfig);
11919   }
11920   }
11921 
11922   // Overload resolution failed.
11923   return ExprError();
11924 }
11925 
11926 static void markUnaddressableCandidatesUnviable(Sema &S,
11927                                                 OverloadCandidateSet &CS) {
11928   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11929     if (I->Viable &&
11930         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11931       I->Viable = false;
11932       I->FailureKind = ovl_fail_addr_not_available;
11933     }
11934   }
11935 }
11936 
11937 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11938 /// (which eventually refers to the declaration Func) and the call
11939 /// arguments Args/NumArgs, attempt to resolve the function call down
11940 /// to a specific function. If overload resolution succeeds, returns
11941 /// the call expression produced by overload resolution.
11942 /// Otherwise, emits diagnostics and returns ExprError.
11943 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11944                                          UnresolvedLookupExpr *ULE,
11945                                          SourceLocation LParenLoc,
11946                                          MultiExprArg Args,
11947                                          SourceLocation RParenLoc,
11948                                          Expr *ExecConfig,
11949                                          bool AllowTypoCorrection,
11950                                          bool CalleesAddressIsTaken) {
11951   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11952                                     OverloadCandidateSet::CSK_Normal);
11953   ExprResult result;
11954 
11955   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11956                              &result))
11957     return result;
11958 
11959   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11960   // functions that aren't addressible are considered unviable.
11961   if (CalleesAddressIsTaken)
11962     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11963 
11964   OverloadCandidateSet::iterator Best;
11965   OverloadingResult OverloadResult =
11966       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11967 
11968   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11969                                   RParenLoc, ExecConfig, &CandidateSet,
11970                                   &Best, OverloadResult,
11971                                   AllowTypoCorrection);
11972 }
11973 
11974 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11975   return Functions.size() > 1 ||
11976     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11977 }
11978 
11979 /// \brief Create a unary operation that may resolve to an overloaded
11980 /// operator.
11981 ///
11982 /// \param OpLoc The location of the operator itself (e.g., '*').
11983 ///
11984 /// \param Opc The UnaryOperatorKind that describes this operator.
11985 ///
11986 /// \param Fns The set of non-member functions that will be
11987 /// considered by overload resolution. The caller needs to build this
11988 /// set based on the context using, e.g.,
11989 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11990 /// set should not contain any member functions; those will be added
11991 /// by CreateOverloadedUnaryOp().
11992 ///
11993 /// \param Input The input argument.
11994 ExprResult
11995 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11996                               const UnresolvedSetImpl &Fns,
11997                               Expr *Input, bool PerformADL) {
11998   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11999   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12000   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12001   // TODO: provide better source location info.
12002   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12003 
12004   if (checkPlaceholderForOverload(*this, Input))
12005     return ExprError();
12006 
12007   Expr *Args[2] = { Input, nullptr };
12008   unsigned NumArgs = 1;
12009 
12010   // For post-increment and post-decrement, add the implicit '0' as
12011   // the second argument, so that we know this is a post-increment or
12012   // post-decrement.
12013   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12014     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12015     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12016                                      SourceLocation());
12017     NumArgs = 2;
12018   }
12019 
12020   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12021 
12022   if (Input->isTypeDependent()) {
12023     if (Fns.empty())
12024       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12025                                          VK_RValue, OK_Ordinary, OpLoc, false);
12026 
12027     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12028     UnresolvedLookupExpr *Fn
12029       = UnresolvedLookupExpr::Create(Context, NamingClass,
12030                                      NestedNameSpecifierLoc(), OpNameInfo,
12031                                      /*ADL*/ true, IsOverloaded(Fns),
12032                                      Fns.begin(), Fns.end());
12033     return new (Context)
12034         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12035                             VK_RValue, OpLoc, FPOptions());
12036   }
12037 
12038   // Build an empty overload set.
12039   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12040 
12041   // Add the candidates from the given function set.
12042   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12043 
12044   // Add operator candidates that are member functions.
12045   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12046 
12047   // Add candidates from ADL.
12048   if (PerformADL) {
12049     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12050                                          /*ExplicitTemplateArgs*/nullptr,
12051                                          CandidateSet);
12052   }
12053 
12054   // Add builtin operator candidates.
12055   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12056 
12057   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12058 
12059   // Perform overload resolution.
12060   OverloadCandidateSet::iterator Best;
12061   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12062   case OR_Success: {
12063     // We found a built-in operator or an overloaded operator.
12064     FunctionDecl *FnDecl = Best->Function;
12065 
12066     if (FnDecl) {
12067       Expr *Base = nullptr;
12068       // We matched an overloaded operator. Build a call to that
12069       // operator.
12070 
12071       // Convert the arguments.
12072       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12073         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12074 
12075         ExprResult InputRes =
12076           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12077                                               Best->FoundDecl, Method);
12078         if (InputRes.isInvalid())
12079           return ExprError();
12080         Base = Input = InputRes.get();
12081       } else {
12082         // Convert the arguments.
12083         ExprResult InputInit
12084           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12085                                                       Context,
12086                                                       FnDecl->getParamDecl(0)),
12087                                       SourceLocation(),
12088                                       Input);
12089         if (InputInit.isInvalid())
12090           return ExprError();
12091         Input = InputInit.get();
12092       }
12093 
12094       // Build the actual expression node.
12095       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12096                                                 Base, HadMultipleCandidates,
12097                                                 OpLoc);
12098       if (FnExpr.isInvalid())
12099         return ExprError();
12100 
12101       // Determine the result type.
12102       QualType ResultTy = FnDecl->getReturnType();
12103       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12104       ResultTy = ResultTy.getNonLValueExprType(Context);
12105 
12106       Args[0] = Input;
12107       CallExpr *TheCall =
12108         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12109                                           ResultTy, VK, OpLoc, FPOptions());
12110 
12111       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12112         return ExprError();
12113 
12114       if (CheckFunctionCall(FnDecl, TheCall,
12115                             FnDecl->getType()->castAs<FunctionProtoType>()))
12116         return ExprError();
12117 
12118       return MaybeBindToTemporary(TheCall);
12119     } else {
12120       // We matched a built-in operator. Convert the arguments, then
12121       // break out so that we will build the appropriate built-in
12122       // operator node.
12123       ExprResult InputRes = PerformImplicitConversion(
12124           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12125       if (InputRes.isInvalid())
12126         return ExprError();
12127       Input = InputRes.get();
12128       break;
12129     }
12130   }
12131 
12132   case OR_No_Viable_Function:
12133     // This is an erroneous use of an operator which can be overloaded by
12134     // a non-member function. Check for non-member operators which were
12135     // defined too late to be candidates.
12136     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12137       // FIXME: Recover by calling the found function.
12138       return ExprError();
12139 
12140     // No viable function; fall through to handling this as a
12141     // built-in operator, which will produce an error message for us.
12142     break;
12143 
12144   case OR_Ambiguous:
12145     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12146         << UnaryOperator::getOpcodeStr(Opc)
12147         << Input->getType()
12148         << Input->getSourceRange();
12149     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12150                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12151     return ExprError();
12152 
12153   case OR_Deleted:
12154     Diag(OpLoc, diag::err_ovl_deleted_oper)
12155       << Best->Function->isDeleted()
12156       << UnaryOperator::getOpcodeStr(Opc)
12157       << getDeletedOrUnavailableSuffix(Best->Function)
12158       << Input->getSourceRange();
12159     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12160                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12161     return ExprError();
12162   }
12163 
12164   // Either we found no viable overloaded operator or we matched a
12165   // built-in operator. In either case, fall through to trying to
12166   // build a built-in operation.
12167   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12168 }
12169 
12170 /// \brief Create a binary operation that may resolve to an overloaded
12171 /// operator.
12172 ///
12173 /// \param OpLoc The location of the operator itself (e.g., '+').
12174 ///
12175 /// \param Opc The BinaryOperatorKind that describes this operator.
12176 ///
12177 /// \param Fns The set of non-member functions that will be
12178 /// considered by overload resolution. The caller needs to build this
12179 /// set based on the context using, e.g.,
12180 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12181 /// set should not contain any member functions; those will be added
12182 /// by CreateOverloadedBinOp().
12183 ///
12184 /// \param LHS Left-hand argument.
12185 /// \param RHS Right-hand argument.
12186 ExprResult
12187 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12188                             BinaryOperatorKind Opc,
12189                             const UnresolvedSetImpl &Fns,
12190                             Expr *LHS, Expr *RHS, bool PerformADL) {
12191   Expr *Args[2] = { LHS, RHS };
12192   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12193 
12194   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12195   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12196 
12197   // If either side is type-dependent, create an appropriate dependent
12198   // expression.
12199   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12200     if (Fns.empty()) {
12201       // If there are no functions to store, just build a dependent
12202       // BinaryOperator or CompoundAssignment.
12203       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12204         return new (Context) BinaryOperator(
12205             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12206             OpLoc, FPFeatures);
12207 
12208       return new (Context) CompoundAssignOperator(
12209           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12210           Context.DependentTy, Context.DependentTy, OpLoc,
12211           FPFeatures);
12212     }
12213 
12214     // FIXME: save results of ADL from here?
12215     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12216     // TODO: provide better source location info in DNLoc component.
12217     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12218     UnresolvedLookupExpr *Fn
12219       = UnresolvedLookupExpr::Create(Context, NamingClass,
12220                                      NestedNameSpecifierLoc(), OpNameInfo,
12221                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12222                                      Fns.begin(), Fns.end());
12223     return new (Context)
12224         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12225                             VK_RValue, OpLoc, FPFeatures);
12226   }
12227 
12228   // Always do placeholder-like conversions on the RHS.
12229   if (checkPlaceholderForOverload(*this, Args[1]))
12230     return ExprError();
12231 
12232   // Do placeholder-like conversion on the LHS; note that we should
12233   // not get here with a PseudoObject LHS.
12234   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12235   if (checkPlaceholderForOverload(*this, Args[0]))
12236     return ExprError();
12237 
12238   // If this is the assignment operator, we only perform overload resolution
12239   // if the left-hand side is a class or enumeration type. This is actually
12240   // a hack. The standard requires that we do overload resolution between the
12241   // various built-in candidates, but as DR507 points out, this can lead to
12242   // problems. So we do it this way, which pretty much follows what GCC does.
12243   // Note that we go the traditional code path for compound assignment forms.
12244   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12245     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12246 
12247   // If this is the .* operator, which is not overloadable, just
12248   // create a built-in binary operator.
12249   if (Opc == BO_PtrMemD)
12250     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12251 
12252   // Build an empty overload set.
12253   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12254 
12255   // Add the candidates from the given function set.
12256   AddFunctionCandidates(Fns, Args, CandidateSet);
12257 
12258   // Add operator candidates that are member functions.
12259   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12260 
12261   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12262   // performed for an assignment operator (nor for operator[] nor operator->,
12263   // which don't get here).
12264   if (Opc != BO_Assign && PerformADL)
12265     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12266                                          /*ExplicitTemplateArgs*/ nullptr,
12267                                          CandidateSet);
12268 
12269   // Add builtin operator candidates.
12270   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12271 
12272   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12273 
12274   // Perform overload resolution.
12275   OverloadCandidateSet::iterator Best;
12276   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12277     case OR_Success: {
12278       // We found a built-in operator or an overloaded operator.
12279       FunctionDecl *FnDecl = Best->Function;
12280 
12281       if (FnDecl) {
12282         Expr *Base = nullptr;
12283         // We matched an overloaded operator. Build a call to that
12284         // operator.
12285 
12286         // Convert the arguments.
12287         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12288           // Best->Access is only meaningful for class members.
12289           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12290 
12291           ExprResult Arg1 =
12292             PerformCopyInitialization(
12293               InitializedEntity::InitializeParameter(Context,
12294                                                      FnDecl->getParamDecl(0)),
12295               SourceLocation(), Args[1]);
12296           if (Arg1.isInvalid())
12297             return ExprError();
12298 
12299           ExprResult Arg0 =
12300             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12301                                                 Best->FoundDecl, Method);
12302           if (Arg0.isInvalid())
12303             return ExprError();
12304           Base = Args[0] = Arg0.getAs<Expr>();
12305           Args[1] = RHS = Arg1.getAs<Expr>();
12306         } else {
12307           // Convert the arguments.
12308           ExprResult Arg0 = PerformCopyInitialization(
12309             InitializedEntity::InitializeParameter(Context,
12310                                                    FnDecl->getParamDecl(0)),
12311             SourceLocation(), Args[0]);
12312           if (Arg0.isInvalid())
12313             return ExprError();
12314 
12315           ExprResult Arg1 =
12316             PerformCopyInitialization(
12317               InitializedEntity::InitializeParameter(Context,
12318                                                      FnDecl->getParamDecl(1)),
12319               SourceLocation(), Args[1]);
12320           if (Arg1.isInvalid())
12321             return ExprError();
12322           Args[0] = LHS = Arg0.getAs<Expr>();
12323           Args[1] = RHS = Arg1.getAs<Expr>();
12324         }
12325 
12326         // Build the actual expression node.
12327         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12328                                                   Best->FoundDecl, Base,
12329                                                   HadMultipleCandidates, OpLoc);
12330         if (FnExpr.isInvalid())
12331           return ExprError();
12332 
12333         // Determine the result type.
12334         QualType ResultTy = FnDecl->getReturnType();
12335         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12336         ResultTy = ResultTy.getNonLValueExprType(Context);
12337 
12338         CXXOperatorCallExpr *TheCall =
12339           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12340                                             Args, ResultTy, VK, OpLoc,
12341                                             FPFeatures);
12342 
12343         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12344                                 FnDecl))
12345           return ExprError();
12346 
12347         ArrayRef<const Expr *> ArgsArray(Args, 2);
12348         const Expr *ImplicitThis = nullptr;
12349         // Cut off the implicit 'this'.
12350         if (isa<CXXMethodDecl>(FnDecl)) {
12351           ImplicitThis = ArgsArray[0];
12352           ArgsArray = ArgsArray.slice(1);
12353         }
12354 
12355         // Check for a self move.
12356         if (Op == OO_Equal)
12357           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12358 
12359         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12360                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12361                   VariadicDoesNotApply);
12362 
12363         return MaybeBindToTemporary(TheCall);
12364       } else {
12365         // We matched a built-in operator. Convert the arguments, then
12366         // break out so that we will build the appropriate built-in
12367         // operator node.
12368         ExprResult ArgsRes0 =
12369             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12370                                       Best->Conversions[0], AA_Passing);
12371         if (ArgsRes0.isInvalid())
12372           return ExprError();
12373         Args[0] = ArgsRes0.get();
12374 
12375         ExprResult ArgsRes1 =
12376             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12377                                       Best->Conversions[1], AA_Passing);
12378         if (ArgsRes1.isInvalid())
12379           return ExprError();
12380         Args[1] = ArgsRes1.get();
12381         break;
12382       }
12383     }
12384 
12385     case OR_No_Viable_Function: {
12386       // C++ [over.match.oper]p9:
12387       //   If the operator is the operator , [...] and there are no
12388       //   viable functions, then the operator is assumed to be the
12389       //   built-in operator and interpreted according to clause 5.
12390       if (Opc == BO_Comma)
12391         break;
12392 
12393       // For class as left operand for assignment or compound assigment
12394       // operator do not fall through to handling in built-in, but report that
12395       // no overloaded assignment operator found
12396       ExprResult Result = ExprError();
12397       if (Args[0]->getType()->isRecordType() &&
12398           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12399         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12400              << BinaryOperator::getOpcodeStr(Opc)
12401              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12402         if (Args[0]->getType()->isIncompleteType()) {
12403           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12404             << Args[0]->getType()
12405             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12406         }
12407       } else {
12408         // This is an erroneous use of an operator which can be overloaded by
12409         // a non-member function. Check for non-member operators which were
12410         // defined too late to be candidates.
12411         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12412           // FIXME: Recover by calling the found function.
12413           return ExprError();
12414 
12415         // No viable function; try to create a built-in operation, which will
12416         // produce an error. Then, show the non-viable candidates.
12417         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12418       }
12419       assert(Result.isInvalid() &&
12420              "C++ binary operator overloading is missing candidates!");
12421       if (Result.isInvalid())
12422         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12423                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12424       return Result;
12425     }
12426 
12427     case OR_Ambiguous:
12428       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12429           << BinaryOperator::getOpcodeStr(Opc)
12430           << Args[0]->getType() << Args[1]->getType()
12431           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12432       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12433                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12434       return ExprError();
12435 
12436     case OR_Deleted:
12437       if (isImplicitlyDeleted(Best->Function)) {
12438         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12439         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12440           << Context.getRecordType(Method->getParent())
12441           << getSpecialMember(Method);
12442 
12443         // The user probably meant to call this special member. Just
12444         // explain why it's deleted.
12445         NoteDeletedFunction(Method);
12446         return ExprError();
12447       } else {
12448         Diag(OpLoc, diag::err_ovl_deleted_oper)
12449           << Best->Function->isDeleted()
12450           << BinaryOperator::getOpcodeStr(Opc)
12451           << getDeletedOrUnavailableSuffix(Best->Function)
12452           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12453       }
12454       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12455                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12456       return ExprError();
12457   }
12458 
12459   // We matched a built-in operator; build it.
12460   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12461 }
12462 
12463 ExprResult
12464 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12465                                          SourceLocation RLoc,
12466                                          Expr *Base, Expr *Idx) {
12467   Expr *Args[2] = { Base, Idx };
12468   DeclarationName OpName =
12469       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12470 
12471   // If either side is type-dependent, create an appropriate dependent
12472   // expression.
12473   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12474 
12475     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12476     // CHECKME: no 'operator' keyword?
12477     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12478     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12479     UnresolvedLookupExpr *Fn
12480       = UnresolvedLookupExpr::Create(Context, NamingClass,
12481                                      NestedNameSpecifierLoc(), OpNameInfo,
12482                                      /*ADL*/ true, /*Overloaded*/ false,
12483                                      UnresolvedSetIterator(),
12484                                      UnresolvedSetIterator());
12485     // Can't add any actual overloads yet
12486 
12487     return new (Context)
12488         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12489                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12490   }
12491 
12492   // Handle placeholders on both operands.
12493   if (checkPlaceholderForOverload(*this, Args[0]))
12494     return ExprError();
12495   if (checkPlaceholderForOverload(*this, Args[1]))
12496     return ExprError();
12497 
12498   // Build an empty overload set.
12499   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12500 
12501   // Subscript can only be overloaded as a member function.
12502 
12503   // Add operator candidates that are member functions.
12504   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12505 
12506   // Add builtin operator candidates.
12507   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12508 
12509   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12510 
12511   // Perform overload resolution.
12512   OverloadCandidateSet::iterator Best;
12513   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12514     case OR_Success: {
12515       // We found a built-in operator or an overloaded operator.
12516       FunctionDecl *FnDecl = Best->Function;
12517 
12518       if (FnDecl) {
12519         // We matched an overloaded operator. Build a call to that
12520         // operator.
12521 
12522         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12523 
12524         // Convert the arguments.
12525         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12526         ExprResult Arg0 =
12527           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12528                                               Best->FoundDecl, Method);
12529         if (Arg0.isInvalid())
12530           return ExprError();
12531         Args[0] = Arg0.get();
12532 
12533         // Convert the arguments.
12534         ExprResult InputInit
12535           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12536                                                       Context,
12537                                                       FnDecl->getParamDecl(0)),
12538                                       SourceLocation(),
12539                                       Args[1]);
12540         if (InputInit.isInvalid())
12541           return ExprError();
12542 
12543         Args[1] = InputInit.getAs<Expr>();
12544 
12545         // Build the actual expression node.
12546         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12547         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12548         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12549                                                   Best->FoundDecl,
12550                                                   Base,
12551                                                   HadMultipleCandidates,
12552                                                   OpLocInfo.getLoc(),
12553                                                   OpLocInfo.getInfo());
12554         if (FnExpr.isInvalid())
12555           return ExprError();
12556 
12557         // Determine the result type
12558         QualType ResultTy = FnDecl->getReturnType();
12559         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12560         ResultTy = ResultTy.getNonLValueExprType(Context);
12561 
12562         CXXOperatorCallExpr *TheCall =
12563           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12564                                             FnExpr.get(), Args,
12565                                             ResultTy, VK, RLoc,
12566                                             FPOptions());
12567 
12568         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12569           return ExprError();
12570 
12571         if (CheckFunctionCall(Method, TheCall,
12572                               Method->getType()->castAs<FunctionProtoType>()))
12573           return ExprError();
12574 
12575         return MaybeBindToTemporary(TheCall);
12576       } else {
12577         // We matched a built-in operator. Convert the arguments, then
12578         // break out so that we will build the appropriate built-in
12579         // operator node.
12580         ExprResult ArgsRes0 =
12581             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12582                                       Best->Conversions[0], AA_Passing);
12583         if (ArgsRes0.isInvalid())
12584           return ExprError();
12585         Args[0] = ArgsRes0.get();
12586 
12587         ExprResult ArgsRes1 =
12588             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12589                                       Best->Conversions[1], AA_Passing);
12590         if (ArgsRes1.isInvalid())
12591           return ExprError();
12592         Args[1] = ArgsRes1.get();
12593 
12594         break;
12595       }
12596     }
12597 
12598     case OR_No_Viable_Function: {
12599       if (CandidateSet.empty())
12600         Diag(LLoc, diag::err_ovl_no_oper)
12601           << Args[0]->getType() << /*subscript*/ 0
12602           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12603       else
12604         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12605           << Args[0]->getType()
12606           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12607       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12608                                   "[]", LLoc);
12609       return ExprError();
12610     }
12611 
12612     case OR_Ambiguous:
12613       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12614           << "[]"
12615           << Args[0]->getType() << Args[1]->getType()
12616           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12617       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12618                                   "[]", LLoc);
12619       return ExprError();
12620 
12621     case OR_Deleted:
12622       Diag(LLoc, diag::err_ovl_deleted_oper)
12623         << Best->Function->isDeleted() << "[]"
12624         << getDeletedOrUnavailableSuffix(Best->Function)
12625         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12626       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12627                                   "[]", LLoc);
12628       return ExprError();
12629     }
12630 
12631   // We matched a built-in operator; build it.
12632   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12633 }
12634 
12635 /// BuildCallToMemberFunction - Build a call to a member
12636 /// function. MemExpr is the expression that refers to the member
12637 /// function (and includes the object parameter), Args/NumArgs are the
12638 /// arguments to the function call (not including the object
12639 /// parameter). The caller needs to validate that the member
12640 /// expression refers to a non-static member function or an overloaded
12641 /// member function.
12642 ExprResult
12643 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12644                                 SourceLocation LParenLoc,
12645                                 MultiExprArg Args,
12646                                 SourceLocation RParenLoc) {
12647   assert(MemExprE->getType() == Context.BoundMemberTy ||
12648          MemExprE->getType() == Context.OverloadTy);
12649 
12650   // Dig out the member expression. This holds both the object
12651   // argument and the member function we're referring to.
12652   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12653 
12654   // Determine whether this is a call to a pointer-to-member function.
12655   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12656     assert(op->getType() == Context.BoundMemberTy);
12657     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12658 
12659     QualType fnType =
12660       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12661 
12662     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12663     QualType resultType = proto->getCallResultType(Context);
12664     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12665 
12666     // Check that the object type isn't more qualified than the
12667     // member function we're calling.
12668     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12669 
12670     QualType objectType = op->getLHS()->getType();
12671     if (op->getOpcode() == BO_PtrMemI)
12672       objectType = objectType->castAs<PointerType>()->getPointeeType();
12673     Qualifiers objectQuals = objectType.getQualifiers();
12674 
12675     Qualifiers difference = objectQuals - funcQuals;
12676     difference.removeObjCGCAttr();
12677     difference.removeAddressSpace();
12678     if (difference) {
12679       std::string qualsString = difference.getAsString();
12680       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12681         << fnType.getUnqualifiedType()
12682         << qualsString
12683         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12684     }
12685 
12686     CXXMemberCallExpr *call
12687       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12688                                         resultType, valueKind, RParenLoc);
12689 
12690     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12691                             call, nullptr))
12692       return ExprError();
12693 
12694     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12695       return ExprError();
12696 
12697     if (CheckOtherCall(call, proto))
12698       return ExprError();
12699 
12700     return MaybeBindToTemporary(call);
12701   }
12702 
12703   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12704     return new (Context)
12705         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12706 
12707   UnbridgedCastsSet UnbridgedCasts;
12708   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12709     return ExprError();
12710 
12711   MemberExpr *MemExpr;
12712   CXXMethodDecl *Method = nullptr;
12713   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12714   NestedNameSpecifier *Qualifier = nullptr;
12715   if (isa<MemberExpr>(NakedMemExpr)) {
12716     MemExpr = cast<MemberExpr>(NakedMemExpr);
12717     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12718     FoundDecl = MemExpr->getFoundDecl();
12719     Qualifier = MemExpr->getQualifier();
12720     UnbridgedCasts.restore();
12721   } else {
12722     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12723     Qualifier = UnresExpr->getQualifier();
12724 
12725     QualType ObjectType = UnresExpr->getBaseType();
12726     Expr::Classification ObjectClassification
12727       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12728                             : UnresExpr->getBase()->Classify(Context);
12729 
12730     // Add overload candidates
12731     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12732                                       OverloadCandidateSet::CSK_Normal);
12733 
12734     // FIXME: avoid copy.
12735     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12736     if (UnresExpr->hasExplicitTemplateArgs()) {
12737       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12738       TemplateArgs = &TemplateArgsBuffer;
12739     }
12740 
12741     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12742            E = UnresExpr->decls_end(); I != E; ++I) {
12743 
12744       NamedDecl *Func = *I;
12745       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12746       if (isa<UsingShadowDecl>(Func))
12747         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12748 
12749 
12750       // Microsoft supports direct constructor calls.
12751       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12752         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12753                              Args, CandidateSet);
12754       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12755         // If explicit template arguments were provided, we can't call a
12756         // non-template member function.
12757         if (TemplateArgs)
12758           continue;
12759 
12760         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12761                            ObjectClassification, Args, CandidateSet,
12762                            /*SuppressUserConversions=*/false);
12763       } else {
12764         AddMethodTemplateCandidate(
12765             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12766             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12767             /*SuppressUsedConversions=*/false);
12768       }
12769     }
12770 
12771     DeclarationName DeclName = UnresExpr->getMemberName();
12772 
12773     UnbridgedCasts.restore();
12774 
12775     OverloadCandidateSet::iterator Best;
12776     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12777                                             Best)) {
12778     case OR_Success:
12779       Method = cast<CXXMethodDecl>(Best->Function);
12780       FoundDecl = Best->FoundDecl;
12781       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12782       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12783         return ExprError();
12784       // If FoundDecl is different from Method (such as if one is a template
12785       // and the other a specialization), make sure DiagnoseUseOfDecl is
12786       // called on both.
12787       // FIXME: This would be more comprehensively addressed by modifying
12788       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12789       // being used.
12790       if (Method != FoundDecl.getDecl() &&
12791                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12792         return ExprError();
12793       break;
12794 
12795     case OR_No_Viable_Function:
12796       Diag(UnresExpr->getMemberLoc(),
12797            diag::err_ovl_no_viable_member_function_in_call)
12798         << DeclName << MemExprE->getSourceRange();
12799       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12800       // FIXME: Leaking incoming expressions!
12801       return ExprError();
12802 
12803     case OR_Ambiguous:
12804       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12805         << DeclName << MemExprE->getSourceRange();
12806       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12807       // FIXME: Leaking incoming expressions!
12808       return ExprError();
12809 
12810     case OR_Deleted:
12811       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12812         << Best->Function->isDeleted()
12813         << DeclName
12814         << getDeletedOrUnavailableSuffix(Best->Function)
12815         << MemExprE->getSourceRange();
12816       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12817       // FIXME: Leaking incoming expressions!
12818       return ExprError();
12819     }
12820 
12821     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12822 
12823     // If overload resolution picked a static member, build a
12824     // non-member call based on that function.
12825     if (Method->isStatic()) {
12826       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12827                                    RParenLoc);
12828     }
12829 
12830     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12831   }
12832 
12833   QualType ResultType = Method->getReturnType();
12834   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12835   ResultType = ResultType.getNonLValueExprType(Context);
12836 
12837   assert(Method && "Member call to something that isn't a method?");
12838   CXXMemberCallExpr *TheCall =
12839     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12840                                     ResultType, VK, RParenLoc);
12841 
12842   // Check for a valid return type.
12843   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12844                           TheCall, Method))
12845     return ExprError();
12846 
12847   // Convert the object argument (for a non-static member function call).
12848   // We only need to do this if there was actually an overload; otherwise
12849   // it was done at lookup.
12850   if (!Method->isStatic()) {
12851     ExprResult ObjectArg =
12852       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12853                                           FoundDecl, Method);
12854     if (ObjectArg.isInvalid())
12855       return ExprError();
12856     MemExpr->setBase(ObjectArg.get());
12857   }
12858 
12859   // Convert the rest of the arguments
12860   const FunctionProtoType *Proto =
12861     Method->getType()->getAs<FunctionProtoType>();
12862   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12863                               RParenLoc))
12864     return ExprError();
12865 
12866   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12867 
12868   if (CheckFunctionCall(Method, TheCall, Proto))
12869     return ExprError();
12870 
12871   // In the case the method to call was not selected by the overloading
12872   // resolution process, we still need to handle the enable_if attribute. Do
12873   // that here, so it will not hide previous -- and more relevant -- errors.
12874   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12875     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12876       Diag(MemE->getMemberLoc(),
12877            diag::err_ovl_no_viable_member_function_in_call)
12878           << Method << Method->getSourceRange();
12879       Diag(Method->getLocation(),
12880            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12881           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12882       return ExprError();
12883     }
12884   }
12885 
12886   if ((isa<CXXConstructorDecl>(CurContext) ||
12887        isa<CXXDestructorDecl>(CurContext)) &&
12888       TheCall->getMethodDecl()->isPure()) {
12889     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12890 
12891     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12892         MemExpr->performsVirtualDispatch(getLangOpts())) {
12893       Diag(MemExpr->getLocStart(),
12894            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12895         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12896         << MD->getParent()->getDeclName();
12897 
12898       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12899       if (getLangOpts().AppleKext)
12900         Diag(MemExpr->getLocStart(),
12901              diag::note_pure_qualified_call_kext)
12902              << MD->getParent()->getDeclName()
12903              << MD->getDeclName();
12904     }
12905   }
12906 
12907   if (CXXDestructorDecl *DD =
12908           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12909     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12910     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12911     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12912                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12913                          MemExpr->getMemberLoc());
12914   }
12915 
12916   return MaybeBindToTemporary(TheCall);
12917 }
12918 
12919 /// BuildCallToObjectOfClassType - Build a call to an object of class
12920 /// type (C++ [over.call.object]), which can end up invoking an
12921 /// overloaded function call operator (@c operator()) or performing a
12922 /// user-defined conversion on the object argument.
12923 ExprResult
12924 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12925                                    SourceLocation LParenLoc,
12926                                    MultiExprArg Args,
12927                                    SourceLocation RParenLoc) {
12928   if (checkPlaceholderForOverload(*this, Obj))
12929     return ExprError();
12930   ExprResult Object = Obj;
12931 
12932   UnbridgedCastsSet UnbridgedCasts;
12933   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12934     return ExprError();
12935 
12936   assert(Object.get()->getType()->isRecordType() &&
12937          "Requires object type argument");
12938   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12939 
12940   // C++ [over.call.object]p1:
12941   //  If the primary-expression E in the function call syntax
12942   //  evaluates to a class object of type "cv T", then the set of
12943   //  candidate functions includes at least the function call
12944   //  operators of T. The function call operators of T are obtained by
12945   //  ordinary lookup of the name operator() in the context of
12946   //  (E).operator().
12947   OverloadCandidateSet CandidateSet(LParenLoc,
12948                                     OverloadCandidateSet::CSK_Operator);
12949   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12950 
12951   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12952                           diag::err_incomplete_object_call, Object.get()))
12953     return true;
12954 
12955   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12956   LookupQualifiedName(R, Record->getDecl());
12957   R.suppressDiagnostics();
12958 
12959   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12960        Oper != OperEnd; ++Oper) {
12961     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12962                        Object.get()->Classify(Context), Args, CandidateSet,
12963                        /*SuppressUserConversions=*/false);
12964   }
12965 
12966   // C++ [over.call.object]p2:
12967   //   In addition, for each (non-explicit in C++0x) conversion function
12968   //   declared in T of the form
12969   //
12970   //        operator conversion-type-id () cv-qualifier;
12971   //
12972   //   where cv-qualifier is the same cv-qualification as, or a
12973   //   greater cv-qualification than, cv, and where conversion-type-id
12974   //   denotes the type "pointer to function of (P1,...,Pn) returning
12975   //   R", or the type "reference to pointer to function of
12976   //   (P1,...,Pn) returning R", or the type "reference to function
12977   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12978   //   is also considered as a candidate function. Similarly,
12979   //   surrogate call functions are added to the set of candidate
12980   //   functions for each conversion function declared in an
12981   //   accessible base class provided the function is not hidden
12982   //   within T by another intervening declaration.
12983   const auto &Conversions =
12984       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12985   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12986     NamedDecl *D = *I;
12987     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12988     if (isa<UsingShadowDecl>(D))
12989       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12990 
12991     // Skip over templated conversion functions; they aren't
12992     // surrogates.
12993     if (isa<FunctionTemplateDecl>(D))
12994       continue;
12995 
12996     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12997     if (!Conv->isExplicit()) {
12998       // Strip the reference type (if any) and then the pointer type (if
12999       // any) to get down to what might be a function type.
13000       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13001       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13002         ConvType = ConvPtrType->getPointeeType();
13003 
13004       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13005       {
13006         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13007                               Object.get(), Args, CandidateSet);
13008       }
13009     }
13010   }
13011 
13012   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13013 
13014   // Perform overload resolution.
13015   OverloadCandidateSet::iterator Best;
13016   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13017                                           Best)) {
13018   case OR_Success:
13019     // Overload resolution succeeded; we'll build the appropriate call
13020     // below.
13021     break;
13022 
13023   case OR_No_Viable_Function:
13024     if (CandidateSet.empty())
13025       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13026         << Object.get()->getType() << /*call*/ 1
13027         << Object.get()->getSourceRange();
13028     else
13029       Diag(Object.get()->getLocStart(),
13030            diag::err_ovl_no_viable_object_call)
13031         << Object.get()->getType() << Object.get()->getSourceRange();
13032     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13033     break;
13034 
13035   case OR_Ambiguous:
13036     Diag(Object.get()->getLocStart(),
13037          diag::err_ovl_ambiguous_object_call)
13038       << Object.get()->getType() << Object.get()->getSourceRange();
13039     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13040     break;
13041 
13042   case OR_Deleted:
13043     Diag(Object.get()->getLocStart(),
13044          diag::err_ovl_deleted_object_call)
13045       << Best->Function->isDeleted()
13046       << Object.get()->getType()
13047       << getDeletedOrUnavailableSuffix(Best->Function)
13048       << Object.get()->getSourceRange();
13049     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13050     break;
13051   }
13052 
13053   if (Best == CandidateSet.end())
13054     return true;
13055 
13056   UnbridgedCasts.restore();
13057 
13058   if (Best->Function == nullptr) {
13059     // Since there is no function declaration, this is one of the
13060     // surrogate candidates. Dig out the conversion function.
13061     CXXConversionDecl *Conv
13062       = cast<CXXConversionDecl>(
13063                          Best->Conversions[0].UserDefined.ConversionFunction);
13064 
13065     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13066                               Best->FoundDecl);
13067     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13068       return ExprError();
13069     assert(Conv == Best->FoundDecl.getDecl() &&
13070              "Found Decl & conversion-to-functionptr should be same, right?!");
13071     // We selected one of the surrogate functions that converts the
13072     // object parameter to a function pointer. Perform the conversion
13073     // on the object argument, then let ActOnCallExpr finish the job.
13074 
13075     // Create an implicit member expr to refer to the conversion operator.
13076     // and then call it.
13077     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13078                                              Conv, HadMultipleCandidates);
13079     if (Call.isInvalid())
13080       return ExprError();
13081     // Record usage of conversion in an implicit cast.
13082     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13083                                     CK_UserDefinedConversion, Call.get(),
13084                                     nullptr, VK_RValue);
13085 
13086     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13087   }
13088 
13089   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13090 
13091   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13092   // that calls this method, using Object for the implicit object
13093   // parameter and passing along the remaining arguments.
13094   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13095 
13096   // An error diagnostic has already been printed when parsing the declaration.
13097   if (Method->isInvalidDecl())
13098     return ExprError();
13099 
13100   const FunctionProtoType *Proto =
13101     Method->getType()->getAs<FunctionProtoType>();
13102 
13103   unsigned NumParams = Proto->getNumParams();
13104 
13105   DeclarationNameInfo OpLocInfo(
13106                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13107   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13108   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13109                                            Obj, HadMultipleCandidates,
13110                                            OpLocInfo.getLoc(),
13111                                            OpLocInfo.getInfo());
13112   if (NewFn.isInvalid())
13113     return true;
13114 
13115   // Build the full argument list for the method call (the implicit object
13116   // parameter is placed at the beginning of the list).
13117   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13118   MethodArgs[0] = Object.get();
13119   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13120 
13121   // Once we've built TheCall, all of the expressions are properly
13122   // owned.
13123   QualType ResultTy = Method->getReturnType();
13124   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13125   ResultTy = ResultTy.getNonLValueExprType(Context);
13126 
13127   CXXOperatorCallExpr *TheCall = new (Context)
13128       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13129                           VK, RParenLoc, FPOptions());
13130 
13131   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13132     return true;
13133 
13134   // We may have default arguments. If so, we need to allocate more
13135   // slots in the call for them.
13136   if (Args.size() < NumParams)
13137     TheCall->setNumArgs(Context, NumParams + 1);
13138 
13139   bool IsError = false;
13140 
13141   // Initialize the implicit object parameter.
13142   ExprResult ObjRes =
13143     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13144                                         Best->FoundDecl, Method);
13145   if (ObjRes.isInvalid())
13146     IsError = true;
13147   else
13148     Object = ObjRes;
13149   TheCall->setArg(0, Object.get());
13150 
13151   // Check the argument types.
13152   for (unsigned i = 0; i != NumParams; i++) {
13153     Expr *Arg;
13154     if (i < Args.size()) {
13155       Arg = Args[i];
13156 
13157       // Pass the argument.
13158 
13159       ExprResult InputInit
13160         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13161                                                     Context,
13162                                                     Method->getParamDecl(i)),
13163                                     SourceLocation(), Arg);
13164 
13165       IsError |= InputInit.isInvalid();
13166       Arg = InputInit.getAs<Expr>();
13167     } else {
13168       ExprResult DefArg
13169         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13170       if (DefArg.isInvalid()) {
13171         IsError = true;
13172         break;
13173       }
13174 
13175       Arg = DefArg.getAs<Expr>();
13176     }
13177 
13178     TheCall->setArg(i + 1, Arg);
13179   }
13180 
13181   // If this is a variadic call, handle args passed through "...".
13182   if (Proto->isVariadic()) {
13183     // Promote the arguments (C99 6.5.2.2p7).
13184     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13185       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13186                                                         nullptr);
13187       IsError |= Arg.isInvalid();
13188       TheCall->setArg(i + 1, Arg.get());
13189     }
13190   }
13191 
13192   if (IsError) return true;
13193 
13194   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13195 
13196   if (CheckFunctionCall(Method, TheCall, Proto))
13197     return true;
13198 
13199   return MaybeBindToTemporary(TheCall);
13200 }
13201 
13202 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13203 ///  (if one exists), where @c Base is an expression of class type and
13204 /// @c Member is the name of the member we're trying to find.
13205 ExprResult
13206 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13207                                bool *NoArrowOperatorFound) {
13208   assert(Base->getType()->isRecordType() &&
13209          "left-hand side must have class type");
13210 
13211   if (checkPlaceholderForOverload(*this, Base))
13212     return ExprError();
13213 
13214   SourceLocation Loc = Base->getExprLoc();
13215 
13216   // C++ [over.ref]p1:
13217   //
13218   //   [...] An expression x->m is interpreted as (x.operator->())->m
13219   //   for a class object x of type T if T::operator->() exists and if
13220   //   the operator is selected as the best match function by the
13221   //   overload resolution mechanism (13.3).
13222   DeclarationName OpName =
13223     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13224   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13225   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13226 
13227   if (RequireCompleteType(Loc, Base->getType(),
13228                           diag::err_typecheck_incomplete_tag, Base))
13229     return ExprError();
13230 
13231   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13232   LookupQualifiedName(R, BaseRecord->getDecl());
13233   R.suppressDiagnostics();
13234 
13235   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13236        Oper != OperEnd; ++Oper) {
13237     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13238                        None, CandidateSet, /*SuppressUserConversions=*/false);
13239   }
13240 
13241   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13242 
13243   // Perform overload resolution.
13244   OverloadCandidateSet::iterator Best;
13245   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13246   case OR_Success:
13247     // Overload resolution succeeded; we'll build the call below.
13248     break;
13249 
13250   case OR_No_Viable_Function:
13251     if (CandidateSet.empty()) {
13252       QualType BaseType = Base->getType();
13253       if (NoArrowOperatorFound) {
13254         // Report this specific error to the caller instead of emitting a
13255         // diagnostic, as requested.
13256         *NoArrowOperatorFound = true;
13257         return ExprError();
13258       }
13259       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13260         << BaseType << Base->getSourceRange();
13261       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13262         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13263           << FixItHint::CreateReplacement(OpLoc, ".");
13264       }
13265     } else
13266       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13267         << "operator->" << Base->getSourceRange();
13268     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13269     return ExprError();
13270 
13271   case OR_Ambiguous:
13272     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13273       << "->" << Base->getType() << Base->getSourceRange();
13274     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13275     return ExprError();
13276 
13277   case OR_Deleted:
13278     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13279       << Best->Function->isDeleted()
13280       << "->"
13281       << getDeletedOrUnavailableSuffix(Best->Function)
13282       << Base->getSourceRange();
13283     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13284     return ExprError();
13285   }
13286 
13287   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13288 
13289   // Convert the object parameter.
13290   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13291   ExprResult BaseResult =
13292     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13293                                         Best->FoundDecl, Method);
13294   if (BaseResult.isInvalid())
13295     return ExprError();
13296   Base = BaseResult.get();
13297 
13298   // Build the operator call.
13299   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13300                                             Base, HadMultipleCandidates, OpLoc);
13301   if (FnExpr.isInvalid())
13302     return ExprError();
13303 
13304   QualType ResultTy = Method->getReturnType();
13305   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13306   ResultTy = ResultTy.getNonLValueExprType(Context);
13307   CXXOperatorCallExpr *TheCall =
13308     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13309                                       Base, ResultTy, VK, OpLoc, FPOptions());
13310 
13311   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13312     return ExprError();
13313 
13314   if (CheckFunctionCall(Method, TheCall,
13315                         Method->getType()->castAs<FunctionProtoType>()))
13316     return ExprError();
13317 
13318   return MaybeBindToTemporary(TheCall);
13319 }
13320 
13321 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13322 /// a literal operator described by the provided lookup results.
13323 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13324                                           DeclarationNameInfo &SuffixInfo,
13325                                           ArrayRef<Expr*> Args,
13326                                           SourceLocation LitEndLoc,
13327                                        TemplateArgumentListInfo *TemplateArgs) {
13328   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13329 
13330   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13331                                     OverloadCandidateSet::CSK_Normal);
13332   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13333                         /*SuppressUserConversions=*/true);
13334 
13335   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13336 
13337   // Perform overload resolution. This will usually be trivial, but might need
13338   // to perform substitutions for a literal operator template.
13339   OverloadCandidateSet::iterator Best;
13340   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13341   case OR_Success:
13342   case OR_Deleted:
13343     break;
13344 
13345   case OR_No_Viable_Function:
13346     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13347       << R.getLookupName();
13348     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13349     return ExprError();
13350 
13351   case OR_Ambiguous:
13352     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13353     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13354     return ExprError();
13355   }
13356 
13357   FunctionDecl *FD = Best->Function;
13358   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13359                                         nullptr, HadMultipleCandidates,
13360                                         SuffixInfo.getLoc(),
13361                                         SuffixInfo.getInfo());
13362   if (Fn.isInvalid())
13363     return true;
13364 
13365   // Check the argument types. This should almost always be a no-op, except
13366   // that array-to-pointer decay is applied to string literals.
13367   Expr *ConvArgs[2];
13368   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13369     ExprResult InputInit = PerformCopyInitialization(
13370       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13371       SourceLocation(), Args[ArgIdx]);
13372     if (InputInit.isInvalid())
13373       return true;
13374     ConvArgs[ArgIdx] = InputInit.get();
13375   }
13376 
13377   QualType ResultTy = FD->getReturnType();
13378   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13379   ResultTy = ResultTy.getNonLValueExprType(Context);
13380 
13381   UserDefinedLiteral *UDL =
13382     new (Context) UserDefinedLiteral(Context, Fn.get(),
13383                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13384                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13385 
13386   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13387     return ExprError();
13388 
13389   if (CheckFunctionCall(FD, UDL, nullptr))
13390     return ExprError();
13391 
13392   return MaybeBindToTemporary(UDL);
13393 }
13394 
13395 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13396 /// given LookupResult is non-empty, it is assumed to describe a member which
13397 /// will be invoked. Otherwise, the function will be found via argument
13398 /// dependent lookup.
13399 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13400 /// otherwise CallExpr is set to ExprError() and some non-success value
13401 /// is returned.
13402 Sema::ForRangeStatus
13403 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13404                                 SourceLocation RangeLoc,
13405                                 const DeclarationNameInfo &NameInfo,
13406                                 LookupResult &MemberLookup,
13407                                 OverloadCandidateSet *CandidateSet,
13408                                 Expr *Range, ExprResult *CallExpr) {
13409   Scope *S = nullptr;
13410 
13411   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13412   if (!MemberLookup.empty()) {
13413     ExprResult MemberRef =
13414         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13415                                  /*IsPtr=*/false, CXXScopeSpec(),
13416                                  /*TemplateKWLoc=*/SourceLocation(),
13417                                  /*FirstQualifierInScope=*/nullptr,
13418                                  MemberLookup,
13419                                  /*TemplateArgs=*/nullptr, S);
13420     if (MemberRef.isInvalid()) {
13421       *CallExpr = ExprError();
13422       return FRS_DiagnosticIssued;
13423     }
13424     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13425     if (CallExpr->isInvalid()) {
13426       *CallExpr = ExprError();
13427       return FRS_DiagnosticIssued;
13428     }
13429   } else {
13430     UnresolvedSet<0> FoundNames;
13431     UnresolvedLookupExpr *Fn =
13432       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13433                                    NestedNameSpecifierLoc(), NameInfo,
13434                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13435                                    FoundNames.begin(), FoundNames.end());
13436 
13437     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13438                                                     CandidateSet, CallExpr);
13439     if (CandidateSet->empty() || CandidateSetError) {
13440       *CallExpr = ExprError();
13441       return FRS_NoViableFunction;
13442     }
13443     OverloadCandidateSet::iterator Best;
13444     OverloadingResult OverloadResult =
13445         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13446 
13447     if (OverloadResult == OR_No_Viable_Function) {
13448       *CallExpr = ExprError();
13449       return FRS_NoViableFunction;
13450     }
13451     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13452                                          Loc, nullptr, CandidateSet, &Best,
13453                                          OverloadResult,
13454                                          /*AllowTypoCorrection=*/false);
13455     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13456       *CallExpr = ExprError();
13457       return FRS_DiagnosticIssued;
13458     }
13459   }
13460   return FRS_Success;
13461 }
13462 
13463 
13464 /// FixOverloadedFunctionReference - E is an expression that refers to
13465 /// a C++ overloaded function (possibly with some parentheses and
13466 /// perhaps a '&' around it). We have resolved the overloaded function
13467 /// to the function declaration Fn, so patch up the expression E to
13468 /// refer (possibly indirectly) to Fn. Returns the new expr.
13469 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13470                                            FunctionDecl *Fn) {
13471   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13472     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13473                                                    Found, Fn);
13474     if (SubExpr == PE->getSubExpr())
13475       return PE;
13476 
13477     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13478   }
13479 
13480   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13481     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13482                                                    Found, Fn);
13483     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13484                                SubExpr->getType()) &&
13485            "Implicit cast type cannot be determined from overload");
13486     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13487     if (SubExpr == ICE->getSubExpr())
13488       return ICE;
13489 
13490     return ImplicitCastExpr::Create(Context, ICE->getType(),
13491                                     ICE->getCastKind(),
13492                                     SubExpr, nullptr,
13493                                     ICE->getValueKind());
13494   }
13495 
13496   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13497     if (!GSE->isResultDependent()) {
13498       Expr *SubExpr =
13499           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13500       if (SubExpr == GSE->getResultExpr())
13501         return GSE;
13502 
13503       // Replace the resulting type information before rebuilding the generic
13504       // selection expression.
13505       ArrayRef<Expr *> A = GSE->getAssocExprs();
13506       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13507       unsigned ResultIdx = GSE->getResultIndex();
13508       AssocExprs[ResultIdx] = SubExpr;
13509 
13510       return new (Context) GenericSelectionExpr(
13511           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13512           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13513           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13514           ResultIdx);
13515     }
13516     // Rather than fall through to the unreachable, return the original generic
13517     // selection expression.
13518     return GSE;
13519   }
13520 
13521   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13522     assert(UnOp->getOpcode() == UO_AddrOf &&
13523            "Can only take the address of an overloaded function");
13524     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13525       if (Method->isStatic()) {
13526         // Do nothing: static member functions aren't any different
13527         // from non-member functions.
13528       } else {
13529         // Fix the subexpression, which really has to be an
13530         // UnresolvedLookupExpr holding an overloaded member function
13531         // or template.
13532         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13533                                                        Found, Fn);
13534         if (SubExpr == UnOp->getSubExpr())
13535           return UnOp;
13536 
13537         assert(isa<DeclRefExpr>(SubExpr)
13538                && "fixed to something other than a decl ref");
13539         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13540                && "fixed to a member ref with no nested name qualifier");
13541 
13542         // We have taken the address of a pointer to member
13543         // function. Perform the computation here so that we get the
13544         // appropriate pointer to member type.
13545         QualType ClassType
13546           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13547         QualType MemPtrType
13548           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13549         // Under the MS ABI, lock down the inheritance model now.
13550         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13551           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13552 
13553         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13554                                            VK_RValue, OK_Ordinary,
13555                                            UnOp->getOperatorLoc(), false);
13556       }
13557     }
13558     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13559                                                    Found, Fn);
13560     if (SubExpr == UnOp->getSubExpr())
13561       return UnOp;
13562 
13563     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13564                                      Context.getPointerType(SubExpr->getType()),
13565                                        VK_RValue, OK_Ordinary,
13566                                        UnOp->getOperatorLoc(), false);
13567   }
13568 
13569   // C++ [except.spec]p17:
13570   //   An exception-specification is considered to be needed when:
13571   //   - in an expression the function is the unique lookup result or the
13572   //     selected member of a set of overloaded functions
13573   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13574     ResolveExceptionSpec(E->getExprLoc(), FPT);
13575 
13576   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13577     // FIXME: avoid copy.
13578     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13579     if (ULE->hasExplicitTemplateArgs()) {
13580       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13581       TemplateArgs = &TemplateArgsBuffer;
13582     }
13583 
13584     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13585                                            ULE->getQualifierLoc(),
13586                                            ULE->getTemplateKeywordLoc(),
13587                                            Fn,
13588                                            /*enclosing*/ false, // FIXME?
13589                                            ULE->getNameLoc(),
13590                                            Fn->getType(),
13591                                            VK_LValue,
13592                                            Found.getDecl(),
13593                                            TemplateArgs);
13594     MarkDeclRefReferenced(DRE);
13595     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13596     return DRE;
13597   }
13598 
13599   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13600     // FIXME: avoid copy.
13601     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13602     if (MemExpr->hasExplicitTemplateArgs()) {
13603       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13604       TemplateArgs = &TemplateArgsBuffer;
13605     }
13606 
13607     Expr *Base;
13608 
13609     // If we're filling in a static method where we used to have an
13610     // implicit member access, rewrite to a simple decl ref.
13611     if (MemExpr->isImplicitAccess()) {
13612       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13613         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13614                                                MemExpr->getQualifierLoc(),
13615                                                MemExpr->getTemplateKeywordLoc(),
13616                                                Fn,
13617                                                /*enclosing*/ false,
13618                                                MemExpr->getMemberLoc(),
13619                                                Fn->getType(),
13620                                                VK_LValue,
13621                                                Found.getDecl(),
13622                                                TemplateArgs);
13623         MarkDeclRefReferenced(DRE);
13624         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13625         return DRE;
13626       } else {
13627         SourceLocation Loc = MemExpr->getMemberLoc();
13628         if (MemExpr->getQualifier())
13629           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13630         CheckCXXThisCapture(Loc);
13631         Base = new (Context) CXXThisExpr(Loc,
13632                                          MemExpr->getBaseType(),
13633                                          /*isImplicit=*/true);
13634       }
13635     } else
13636       Base = MemExpr->getBase();
13637 
13638     ExprValueKind valueKind;
13639     QualType type;
13640     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13641       valueKind = VK_LValue;
13642       type = Fn->getType();
13643     } else {
13644       valueKind = VK_RValue;
13645       type = Context.BoundMemberTy;
13646     }
13647 
13648     MemberExpr *ME = MemberExpr::Create(
13649         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13650         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13651         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13652         OK_Ordinary);
13653     ME->setHadMultipleCandidates(true);
13654     MarkMemberReferenced(ME);
13655     return ME;
13656   }
13657 
13658   llvm_unreachable("Invalid reference to overloaded function");
13659 }
13660 
13661 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13662                                                 DeclAccessPair Found,
13663                                                 FunctionDecl *Fn) {
13664   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13665 }
13666