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 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
292 ///        from floating point types to integral types should be ignored.
293 NarrowingKind StandardConversionSequence::getNarrowingKind(
294     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
295     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
296   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297 
298   // C++11 [dcl.init.list]p7:
299   //   A narrowing conversion is an implicit conversion ...
300   QualType FromType = getToType(0);
301   QualType ToType = getToType(1);
302 
303   // A conversion to an enumeration type is narrowing if the conversion to
304   // the underlying type is narrowing. This only arises for expressions of
305   // the form 'Enum{init}'.
306   if (auto *ET = ToType->getAs<EnumType>())
307     ToType = ET->getDecl()->getIntegerType();
308 
309   switch (Second) {
310   // 'bool' is an integral type; dispatch to the right place to handle it.
311   case ICK_Boolean_Conversion:
312     if (FromType->isRealFloatingType())
313       goto FloatingIntegralConversion;
314     if (FromType->isIntegralOrUnscopedEnumerationType())
315       goto IntegralConversion;
316     // Boolean conversions can be from pointers and pointers to members
317     // [conv.bool], and those aren't considered narrowing conversions.
318     return NK_Not_Narrowing;
319 
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327   FloatingIntegralConversion:
328     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329       return NK_Type_Narrowing;
330     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
331                ToType->isRealFloatingType()) {
332       if (IgnoreFloatToIntegralConversion)
333         return NK_Not_Narrowing;
334       llvm::APSInt IntConstantValue;
335       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
336       assert(Initializer && "Unknown conversion expression");
337 
338       // If it's value-dependent, we can't tell whether it's narrowing.
339       if (Initializer->isValueDependent())
340         return NK_Dependent_Narrowing;
341 
342       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
343         // Convert the integer to the floating type.
344         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
345         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
346                                 llvm::APFloat::rmNearestTiesToEven);
347         // And back.
348         llvm::APSInt ConvertedValue = IntConstantValue;
349         bool ignored;
350         Result.convertToInteger(ConvertedValue,
351                                 llvm::APFloat::rmTowardZero, &ignored);
352         // If the resulting value is different, this was a narrowing conversion.
353         if (IntConstantValue != ConvertedValue) {
354           ConstantValue = APValue(IntConstantValue);
355           ConstantType = Initializer->getType();
356           return NK_Constant_Narrowing;
357         }
358       } else {
359         // Variables are always narrowings.
360         return NK_Variable_Narrowing;
361       }
362     }
363     return NK_Not_Narrowing;
364 
365   // -- from long double to double or float, or from double to float, except
366   //    where the source is a constant expression and the actual value after
367   //    conversion is within the range of values that can be represented (even
368   //    if it cannot be represented exactly), or
369   case ICK_Floating_Conversion:
370     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
371         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
372       // FromType is larger than ToType.
373       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
374 
375       // If it's value-dependent, we can't tell whether it's narrowing.
376       if (Initializer->isValueDependent())
377         return NK_Dependent_Narrowing;
378 
379       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
380         // Constant!
381         assert(ConstantValue.isFloat());
382         llvm::APFloat FloatVal = ConstantValue.getFloat();
383         // Convert the source value into the target type.
384         bool ignored;
385         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
386           Ctx.getFloatTypeSemantics(ToType),
387           llvm::APFloat::rmNearestTiesToEven, &ignored);
388         // If there was no overflow, the source value is within the range of
389         // values that can be represented.
390         if (ConvertStatus & llvm::APFloat::opOverflow) {
391           ConstantType = Initializer->getType();
392           return NK_Constant_Narrowing;
393         }
394       } else {
395         return NK_Variable_Narrowing;
396       }
397     }
398     return NK_Not_Narrowing;
399 
400   // -- from an integer type or unscoped enumeration type to an integer type
401   //    that cannot represent all the values of the original type, except where
402   //    the source is a constant expression and the actual value after
403   //    conversion will fit into the target type and will produce the original
404   //    value when converted back to the original type.
405   case ICK_Integral_Conversion:
406   IntegralConversion: {
407     assert(FromType->isIntegralOrUnscopedEnumerationType());
408     assert(ToType->isIntegralOrUnscopedEnumerationType());
409     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
410     const unsigned FromWidth = Ctx.getIntWidth(FromType);
411     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
412     const unsigned ToWidth = Ctx.getIntWidth(ToType);
413 
414     if (FromWidth > ToWidth ||
415         (FromWidth == ToWidth && FromSigned != ToSigned) ||
416         (FromSigned && !ToSigned)) {
417       // Not all values of FromType can be represented in ToType.
418       llvm::APSInt InitializerValue;
419       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
420 
421       // If it's value-dependent, we can't tell whether it's narrowing.
422       if (Initializer->isValueDependent())
423         return NK_Dependent_Narrowing;
424 
425       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
426         // Such conversions on variables are always narrowing.
427         return NK_Variable_Narrowing;
428       }
429       bool Narrowing = false;
430       if (FromWidth < ToWidth) {
431         // Negative -> unsigned is narrowing. Otherwise, more bits is never
432         // narrowing.
433         if (InitializerValue.isSigned() && InitializerValue.isNegative())
434           Narrowing = true;
435       } else {
436         // Add a bit to the InitializerValue so we don't have to worry about
437         // signed vs. unsigned comparisons.
438         InitializerValue = InitializerValue.extend(
439           InitializerValue.getBitWidth() + 1);
440         // Convert the initializer to and from the target width and signed-ness.
441         llvm::APSInt ConvertedValue = InitializerValue;
442         ConvertedValue = ConvertedValue.trunc(ToWidth);
443         ConvertedValue.setIsSigned(ToSigned);
444         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
445         ConvertedValue.setIsSigned(InitializerValue.isSigned());
446         // If the result is different, this was a narrowing conversion.
447         if (ConvertedValue != InitializerValue)
448           Narrowing = true;
449       }
450       if (Narrowing) {
451         ConstantType = Initializer->getType();
452         ConstantValue = APValue(InitializerValue);
453         return NK_Constant_Narrowing;
454       }
455     }
456     return NK_Not_Narrowing;
457   }
458 
459   default:
460     // Other kinds of conversions are not narrowings.
461     return NK_Not_Narrowing;
462   }
463 }
464 
465 /// dump - Print this standard conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
468   raw_ostream &OS = llvm::errs();
469   bool PrintedSomething = false;
470   if (First != ICK_Identity) {
471     OS << GetImplicitConversionName(First);
472     PrintedSomething = true;
473   }
474 
475   if (Second != ICK_Identity) {
476     if (PrintedSomething) {
477       OS << " -> ";
478     }
479     OS << GetImplicitConversionName(Second);
480 
481     if (CopyConstructor) {
482       OS << " (by copy constructor)";
483     } else if (DirectBinding) {
484       OS << " (direct reference binding)";
485     } else if (ReferenceBinding) {
486       OS << " (reference binding)";
487     }
488     PrintedSomething = true;
489   }
490 
491   if (Third != ICK_Identity) {
492     if (PrintedSomething) {
493       OS << " -> ";
494     }
495     OS << GetImplicitConversionName(Third);
496     PrintedSomething = true;
497   }
498 
499   if (!PrintedSomething) {
500     OS << "No conversions required";
501   }
502 }
503 
504 /// dump - Print this user-defined conversion sequence to standard
505 /// error. Useful for debugging overloading issues.
506 void UserDefinedConversionSequence::dump() const {
507   raw_ostream &OS = llvm::errs();
508   if (Before.First || Before.Second || Before.Third) {
509     Before.dump();
510     OS << " -> ";
511   }
512   if (ConversionFunction)
513     OS << '\'' << *ConversionFunction << '\'';
514   else
515     OS << "aggregate initialization";
516   if (After.First || After.Second || After.Third) {
517     OS << " -> ";
518     After.dump();
519   }
520 }
521 
522 /// dump - Print this implicit conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void ImplicitConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (isStdInitializerListElement())
527     OS << "Worst std::initializer_list element conversion: ";
528   switch (ConversionKind) {
529   case StandardConversion:
530     OS << "Standard conversion: ";
531     Standard.dump();
532     break;
533   case UserDefinedConversion:
534     OS << "User-defined conversion: ";
535     UserDefined.dump();
536     break;
537   case EllipsisConversion:
538     OS << "Ellipsis conversion";
539     break;
540   case AmbiguousConversion:
541     OS << "Ambiguous conversion";
542     break;
543   case BadConversion:
544     OS << "Bad conversion";
545     break;
546   }
547 
548   OS << "\n";
549 }
550 
551 void AmbiguousConversionSequence::construct() {
552   new (&conversions()) ConversionSet();
553 }
554 
555 void AmbiguousConversionSequence::destruct() {
556   conversions().~ConversionSet();
557 }
558 
559 void
560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
561   FromTypePtr = O.FromTypePtr;
562   ToTypePtr = O.ToTypePtr;
563   new (&conversions()) ConversionSet(O.conversions());
564 }
565 
566 namespace {
567   // Structure used by DeductionFailureInfo to store
568   // template argument information.
569   struct DFIArguments {
570     TemplateArgument FirstArg;
571     TemplateArgument SecondArg;
572   };
573   // Structure used by DeductionFailureInfo to store
574   // template parameter and template argument information.
575   struct DFIParamWithArguments : DFIArguments {
576     TemplateParameter Param;
577   };
578   // Structure used by DeductionFailureInfo to store template argument
579   // information and the index of the problematic call argument.
580   struct DFIDeducedMismatchArgs : DFIArguments {
581     TemplateArgumentList *TemplateArgs;
582     unsigned CallArgIndex;
583   };
584 }
585 
586 /// Convert from Sema's representation of template deduction information
587 /// to the form used in overload-candidate information.
588 DeductionFailureInfo
589 clang::MakeDeductionFailureInfo(ASTContext &Context,
590                                 Sema::TemplateDeductionResult TDK,
591                                 TemplateDeductionInfo &Info) {
592   DeductionFailureInfo Result;
593   Result.Result = static_cast<unsigned>(TDK);
594   Result.HasDiagnostic = false;
595   switch (TDK) {
596   case Sema::TDK_Invalid:
597   case Sema::TDK_InstantiationDepth:
598   case Sema::TDK_TooManyArguments:
599   case Sema::TDK_TooFewArguments:
600   case Sema::TDK_MiscellaneousDeductionFailure:
601   case Sema::TDK_CUDATargetMismatch:
602     Result.Data = nullptr;
603     break;
604 
605   case Sema::TDK_Incomplete:
606   case Sema::TDK_InvalidExplicitArguments:
607     Result.Data = Info.Param.getOpaqueValue();
608     break;
609 
610   case Sema::TDK_DeducedMismatch:
611   case Sema::TDK_DeducedMismatchNested: {
612     // FIXME: Should allocate from normal heap so that we can free this later.
613     auto *Saved = new (Context) DFIDeducedMismatchArgs;
614     Saved->FirstArg = Info.FirstArg;
615     Saved->SecondArg = Info.SecondArg;
616     Saved->TemplateArgs = Info.take();
617     Saved->CallArgIndex = Info.CallArgIndex;
618     Result.Data = Saved;
619     break;
620   }
621 
622   case Sema::TDK_NonDeducedMismatch: {
623     // FIXME: Should allocate from normal heap so that we can free this later.
624     DFIArguments *Saved = new (Context) DFIArguments;
625     Saved->FirstArg = Info.FirstArg;
626     Saved->SecondArg = Info.SecondArg;
627     Result.Data = Saved;
628     break;
629   }
630 
631   case Sema::TDK_Inconsistent:
632   case Sema::TDK_Underqualified: {
633     // FIXME: Should allocate from normal heap so that we can free this later.
634     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
635     Saved->Param = Info.Param;
636     Saved->FirstArg = Info.FirstArg;
637     Saved->SecondArg = Info.SecondArg;
638     Result.Data = Saved;
639     break;
640   }
641 
642   case Sema::TDK_SubstitutionFailure:
643     Result.Data = Info.take();
644     if (Info.hasSFINAEDiagnostic()) {
645       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
646           SourceLocation(), PartialDiagnostic::NullDiagnostic());
647       Info.takeSFINAEDiagnostic(*Diag);
648       Result.HasDiagnostic = true;
649     }
650     break;
651 
652   case Sema::TDK_Success:
653   case Sema::TDK_NonDependentConversionFailure:
654     llvm_unreachable("not a deduction failure");
655   }
656 
657   return Result;
658 }
659 
660 void DeductionFailureInfo::Destroy() {
661   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
662   case Sema::TDK_Success:
663   case Sema::TDK_Invalid:
664   case Sema::TDK_InstantiationDepth:
665   case Sema::TDK_Incomplete:
666   case Sema::TDK_TooManyArguments:
667   case Sema::TDK_TooFewArguments:
668   case Sema::TDK_InvalidExplicitArguments:
669   case Sema::TDK_CUDATargetMismatch:
670   case Sema::TDK_NonDependentConversionFailure:
671     break;
672 
673   case Sema::TDK_Inconsistent:
674   case Sema::TDK_Underqualified:
675   case Sema::TDK_DeducedMismatch:
676   case Sema::TDK_DeducedMismatchNested:
677   case Sema::TDK_NonDeducedMismatch:
678     // FIXME: Destroy the data?
679     Data = nullptr;
680     break;
681 
682   case Sema::TDK_SubstitutionFailure:
683     // FIXME: Destroy the template argument list?
684     Data = nullptr;
685     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
686       Diag->~PartialDiagnosticAt();
687       HasDiagnostic = false;
688     }
689     break;
690 
691   // Unhandled
692   case Sema::TDK_MiscellaneousDeductionFailure:
693     break;
694   }
695 }
696 
697 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
698   if (HasDiagnostic)
699     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
700   return nullptr;
701 }
702 
703 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
704   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
705   case Sema::TDK_Success:
706   case Sema::TDK_Invalid:
707   case Sema::TDK_InstantiationDepth:
708   case Sema::TDK_TooManyArguments:
709   case Sema::TDK_TooFewArguments:
710   case Sema::TDK_SubstitutionFailure:
711   case Sema::TDK_DeducedMismatch:
712   case Sema::TDK_DeducedMismatchNested:
713   case Sema::TDK_NonDeducedMismatch:
714   case Sema::TDK_CUDATargetMismatch:
715   case Sema::TDK_NonDependentConversionFailure:
716     return TemplateParameter();
717 
718   case Sema::TDK_Incomplete:
719   case Sema::TDK_InvalidExplicitArguments:
720     return TemplateParameter::getFromOpaqueValue(Data);
721 
722   case Sema::TDK_Inconsistent:
723   case Sema::TDK_Underqualified:
724     return static_cast<DFIParamWithArguments*>(Data)->Param;
725 
726   // Unhandled
727   case Sema::TDK_MiscellaneousDeductionFailure:
728     break;
729   }
730 
731   return TemplateParameter();
732 }
733 
734 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
735   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
736   case Sema::TDK_Success:
737   case Sema::TDK_Invalid:
738   case Sema::TDK_InstantiationDepth:
739   case Sema::TDK_TooManyArguments:
740   case Sema::TDK_TooFewArguments:
741   case Sema::TDK_Incomplete:
742   case Sema::TDK_InvalidExplicitArguments:
743   case Sema::TDK_Inconsistent:
744   case Sema::TDK_Underqualified:
745   case Sema::TDK_NonDeducedMismatch:
746   case Sema::TDK_CUDATargetMismatch:
747   case Sema::TDK_NonDependentConversionFailure:
748     return nullptr;
749 
750   case Sema::TDK_DeducedMismatch:
751   case Sema::TDK_DeducedMismatchNested:
752     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
753 
754   case Sema::TDK_SubstitutionFailure:
755     return static_cast<TemplateArgumentList*>(Data);
756 
757   // Unhandled
758   case Sema::TDK_MiscellaneousDeductionFailure:
759     break;
760   }
761 
762   return nullptr;
763 }
764 
765 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
766   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
767   case Sema::TDK_Success:
768   case Sema::TDK_Invalid:
769   case Sema::TDK_InstantiationDepth:
770   case Sema::TDK_Incomplete:
771   case Sema::TDK_TooManyArguments:
772   case Sema::TDK_TooFewArguments:
773   case Sema::TDK_InvalidExplicitArguments:
774   case Sema::TDK_SubstitutionFailure:
775   case Sema::TDK_CUDATargetMismatch:
776   case Sema::TDK_NonDependentConversionFailure:
777     return nullptr;
778 
779   case Sema::TDK_Inconsistent:
780   case Sema::TDK_Underqualified:
781   case Sema::TDK_DeducedMismatch:
782   case Sema::TDK_DeducedMismatchNested:
783   case Sema::TDK_NonDeducedMismatch:
784     return &static_cast<DFIArguments*>(Data)->FirstArg;
785 
786   // Unhandled
787   case Sema::TDK_MiscellaneousDeductionFailure:
788     break;
789   }
790 
791   return nullptr;
792 }
793 
794 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
795   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
796   case Sema::TDK_Success:
797   case Sema::TDK_Invalid:
798   case Sema::TDK_InstantiationDepth:
799   case Sema::TDK_Incomplete:
800   case Sema::TDK_TooManyArguments:
801   case Sema::TDK_TooFewArguments:
802   case Sema::TDK_InvalidExplicitArguments:
803   case Sema::TDK_SubstitutionFailure:
804   case Sema::TDK_CUDATargetMismatch:
805   case Sema::TDK_NonDependentConversionFailure:
806     return nullptr;
807 
808   case Sema::TDK_Inconsistent:
809   case Sema::TDK_Underqualified:
810   case Sema::TDK_DeducedMismatch:
811   case Sema::TDK_DeducedMismatchNested:
812   case Sema::TDK_NonDeducedMismatch:
813     return &static_cast<DFIArguments*>(Data)->SecondArg;
814 
815   // Unhandled
816   case Sema::TDK_MiscellaneousDeductionFailure:
817     break;
818   }
819 
820   return nullptr;
821 }
822 
823 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
824   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
825   case Sema::TDK_DeducedMismatch:
826   case Sema::TDK_DeducedMismatchNested:
827     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
828 
829   default:
830     return llvm::None;
831   }
832 }
833 
834 void OverloadCandidateSet::destroyCandidates() {
835   for (iterator i = begin(), e = end(); i != e; ++i) {
836     for (auto &C : i->Conversions)
837       C.~ImplicitConversionSequence();
838     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
839       i->DeductionFailure.Destroy();
840   }
841 }
842 
843 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
844   destroyCandidates();
845   SlabAllocator.Reset();
846   NumInlineBytesUsed = 0;
847   Candidates.clear();
848   Functions.clear();
849   Kind = CSK;
850 }
851 
852 namespace {
853   class UnbridgedCastsSet {
854     struct Entry {
855       Expr **Addr;
856       Expr *Saved;
857     };
858     SmallVector<Entry, 2> Entries;
859 
860   public:
861     void save(Sema &S, Expr *&E) {
862       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
863       Entry entry = { &E, E };
864       Entries.push_back(entry);
865       E = S.stripARCUnbridgedCast(E);
866     }
867 
868     void restore() {
869       for (SmallVectorImpl<Entry>::iterator
870              i = Entries.begin(), e = Entries.end(); i != e; ++i)
871         *i->Addr = i->Saved;
872     }
873   };
874 }
875 
876 /// checkPlaceholderForOverload - Do any interesting placeholder-like
877 /// preprocessing on the given expression.
878 ///
879 /// \param unbridgedCasts a collection to which to add unbridged casts;
880 ///   without this, they will be immediately diagnosed as errors
881 ///
882 /// Return true on unrecoverable error.
883 static bool
884 checkPlaceholderForOverload(Sema &S, Expr *&E,
885                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
886   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
887     // We can't handle overloaded expressions here because overload
888     // resolution might reasonably tweak them.
889     if (placeholder->getKind() == BuiltinType::Overload) return false;
890 
891     // If the context potentially accepts unbridged ARC casts, strip
892     // the unbridged cast and add it to the collection for later restoration.
893     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
894         unbridgedCasts) {
895       unbridgedCasts->save(S, E);
896       return false;
897     }
898 
899     // Go ahead and check everything else.
900     ExprResult result = S.CheckPlaceholderExpr(E);
901     if (result.isInvalid())
902       return true;
903 
904     E = result.get();
905     return false;
906   }
907 
908   // Nothing to do.
909   return false;
910 }
911 
912 /// checkArgPlaceholdersForOverload - Check a set of call operands for
913 /// placeholders.
914 static bool checkArgPlaceholdersForOverload(Sema &S,
915                                             MultiExprArg Args,
916                                             UnbridgedCastsSet &unbridged) {
917   for (unsigned i = 0, e = Args.size(); i != e; ++i)
918     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
919       return true;
920 
921   return false;
922 }
923 
924 /// Determine whether the given New declaration is an overload of the
925 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
926 /// New and Old cannot be overloaded, e.g., if New has the same signature as
927 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
928 /// functions (or function templates) at all. When it does return Ovl_Match or
929 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
930 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
931 /// declaration.
932 ///
933 /// Example: Given the following input:
934 ///
935 ///   void f(int, float); // #1
936 ///   void f(int, int); // #2
937 ///   int f(int, int); // #3
938 ///
939 /// When we process #1, there is no previous declaration of "f", so IsOverload
940 /// will not be used.
941 ///
942 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
943 /// the parameter types, we see that #1 and #2 are overloaded (since they have
944 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
945 /// unchanged.
946 ///
947 /// When we process #3, Old is an overload set containing #1 and #2. We compare
948 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
949 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
950 /// functions are not part of the signature), IsOverload returns Ovl_Match and
951 /// MatchedDecl will be set to point to the FunctionDecl for #2.
952 ///
953 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
954 /// by a using declaration. The rules for whether to hide shadow declarations
955 /// ignore some properties which otherwise figure into a function template's
956 /// signature.
957 Sema::OverloadKind
958 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
959                     NamedDecl *&Match, bool NewIsUsingDecl) {
960   for (LookupResult::iterator I = Old.begin(), E = Old.end();
961          I != E; ++I) {
962     NamedDecl *OldD = *I;
963 
964     bool OldIsUsingDecl = false;
965     if (isa<UsingShadowDecl>(OldD)) {
966       OldIsUsingDecl = true;
967 
968       // We can always introduce two using declarations into the same
969       // context, even if they have identical signatures.
970       if (NewIsUsingDecl) continue;
971 
972       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
973     }
974 
975     // A using-declaration does not conflict with another declaration
976     // if one of them is hidden.
977     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
978       continue;
979 
980     // If either declaration was introduced by a using declaration,
981     // we'll need to use slightly different rules for matching.
982     // Essentially, these rules are the normal rules, except that
983     // function templates hide function templates with different
984     // return types or template parameter lists.
985     bool UseMemberUsingDeclRules =
986       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
987       !New->getFriendObjectKind();
988 
989     if (FunctionDecl *OldF = OldD->getAsFunction()) {
990       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
991         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
992           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
993           continue;
994         }
995 
996         if (!isa<FunctionTemplateDecl>(OldD) &&
997             !shouldLinkPossiblyHiddenDecl(*I, New))
998           continue;
999 
1000         Match = *I;
1001         return Ovl_Match;
1002       }
1003 
1004       // Builtins that have custom typechecking or have a reference should
1005       // not be overloadable or redeclarable.
1006       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1007         Match = *I;
1008         return Ovl_NonFunction;
1009       }
1010     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1011       // We can overload with these, which can show up when doing
1012       // redeclaration checks for UsingDecls.
1013       assert(Old.getLookupKind() == LookupUsingDeclName);
1014     } else if (isa<TagDecl>(OldD)) {
1015       // We can always overload with tags by hiding them.
1016     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1017       // Optimistically assume that an unresolved using decl will
1018       // overload; if it doesn't, we'll have to diagnose during
1019       // template instantiation.
1020       //
1021       // Exception: if the scope is dependent and this is not a class
1022       // member, the using declaration can only introduce an enumerator.
1023       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1024         Match = *I;
1025         return Ovl_NonFunction;
1026       }
1027     } else {
1028       // (C++ 13p1):
1029       //   Only function declarations can be overloaded; object and type
1030       //   declarations cannot be overloaded.
1031       Match = *I;
1032       return Ovl_NonFunction;
1033     }
1034   }
1035 
1036   return Ovl_Overload;
1037 }
1038 
1039 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1040                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1041   // C++ [basic.start.main]p2: This function shall not be overloaded.
1042   if (New->isMain())
1043     return false;
1044 
1045   // MSVCRT user defined entry points cannot be overloaded.
1046   if (New->isMSVCRTEntryPoint())
1047     return false;
1048 
1049   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1050   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1051 
1052   // C++ [temp.fct]p2:
1053   //   A function template can be overloaded with other function templates
1054   //   and with normal (non-template) functions.
1055   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1056     return true;
1057 
1058   // Is the function New an overload of the function Old?
1059   QualType OldQType = Context.getCanonicalType(Old->getType());
1060   QualType NewQType = Context.getCanonicalType(New->getType());
1061 
1062   // Compare the signatures (C++ 1.3.10) of the two functions to
1063   // determine whether they are overloads. If we find any mismatch
1064   // in the signature, they are overloads.
1065 
1066   // If either of these functions is a K&R-style function (no
1067   // prototype), then we consider them to have matching signatures.
1068   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1069       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1070     return false;
1071 
1072   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1073   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1074 
1075   // The signature of a function includes the types of its
1076   // parameters (C++ 1.3.10), which includes the presence or absence
1077   // of the ellipsis; see C++ DR 357).
1078   if (OldQType != NewQType &&
1079       (OldType->getNumParams() != NewType->getNumParams() ||
1080        OldType->isVariadic() != NewType->isVariadic() ||
1081        !FunctionParamTypesAreEqual(OldType, NewType)))
1082     return true;
1083 
1084   // C++ [temp.over.link]p4:
1085   //   The signature of a function template consists of its function
1086   //   signature, its return type and its template parameter list. The names
1087   //   of the template parameters are significant only for establishing the
1088   //   relationship between the template parameters and the rest of the
1089   //   signature.
1090   //
1091   // We check the return type and template parameter lists for function
1092   // templates first; the remaining checks follow.
1093   //
1094   // However, we don't consider either of these when deciding whether
1095   // a member introduced by a shadow declaration is hidden.
1096   if (!UseMemberUsingDeclRules && NewTemplate &&
1097       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1098                                        OldTemplate->getTemplateParameters(),
1099                                        false, TPL_TemplateMatch) ||
1100        OldType->getReturnType() != NewType->getReturnType()))
1101     return true;
1102 
1103   // If the function is a class member, its signature includes the
1104   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1105   //
1106   // As part of this, also check whether one of the member functions
1107   // is static, in which case they are not overloads (C++
1108   // 13.1p2). While not part of the definition of the signature,
1109   // this check is important to determine whether these functions
1110   // can be overloaded.
1111   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1112   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1113   if (OldMethod && NewMethod &&
1114       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1115     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1116       if (!UseMemberUsingDeclRules &&
1117           (OldMethod->getRefQualifier() == RQ_None ||
1118            NewMethod->getRefQualifier() == RQ_None)) {
1119         // C++0x [over.load]p2:
1120         //   - Member function declarations with the same name and the same
1121         //     parameter-type-list as well as member function template
1122         //     declarations with the same name, the same parameter-type-list, and
1123         //     the same template parameter lists cannot be overloaded if any of
1124         //     them, but not all, have a ref-qualifier (8.3.5).
1125         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1126           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1127         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1128       }
1129       return true;
1130     }
1131 
1132     // We may not have applied the implicit const for a constexpr member
1133     // function yet (because we haven't yet resolved whether this is a static
1134     // or non-static member function). Add it now, on the assumption that this
1135     // is a redeclaration of OldMethod.
1136     unsigned OldQuals = OldMethod->getTypeQualifiers();
1137     unsigned NewQuals = NewMethod->getTypeQualifiers();
1138     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1139         !isa<CXXConstructorDecl>(NewMethod))
1140       NewQuals |= Qualifiers::Const;
1141 
1142     // We do not allow overloading based off of '__restrict'.
1143     OldQuals &= ~Qualifiers::Restrict;
1144     NewQuals &= ~Qualifiers::Restrict;
1145     if (OldQuals != NewQuals)
1146       return true;
1147   }
1148 
1149   // Though pass_object_size is placed on parameters and takes an argument, we
1150   // consider it to be a function-level modifier for the sake of function
1151   // identity. Either the function has one or more parameters with
1152   // pass_object_size or it doesn't.
1153   if (functionHasPassObjectSizeParams(New) !=
1154       functionHasPassObjectSizeParams(Old))
1155     return true;
1156 
1157   // enable_if attributes are an order-sensitive part of the signature.
1158   for (specific_attr_iterator<EnableIfAttr>
1159          NewI = New->specific_attr_begin<EnableIfAttr>(),
1160          NewE = New->specific_attr_end<EnableIfAttr>(),
1161          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1162          OldE = Old->specific_attr_end<EnableIfAttr>();
1163        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1164     if (NewI == NewE || OldI == OldE)
1165       return true;
1166     llvm::FoldingSetNodeID NewID, OldID;
1167     NewI->getCond()->Profile(NewID, Context, true);
1168     OldI->getCond()->Profile(OldID, Context, true);
1169     if (NewID != OldID)
1170       return true;
1171   }
1172 
1173   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1174     // Don't allow overloading of destructors.  (In theory we could, but it
1175     // would be a giant change to clang.)
1176     if (isa<CXXDestructorDecl>(New))
1177       return false;
1178 
1179     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1180                        OldTarget = IdentifyCUDATarget(Old);
1181     if (NewTarget == CFT_InvalidTarget)
1182       return false;
1183 
1184     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1185 
1186     // Allow overloading of functions with same signature and different CUDA
1187     // target attributes.
1188     return NewTarget != OldTarget;
1189   }
1190 
1191   // The signatures match; this is not an overload.
1192   return false;
1193 }
1194 
1195 /// Checks availability of the function depending on the current
1196 /// function context. Inside an unavailable function, unavailability is ignored.
1197 ///
1198 /// \returns true if \arg FD is unavailable and current context is inside
1199 /// an available function, false otherwise.
1200 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1201   if (!FD->isUnavailable())
1202     return false;
1203 
1204   // Walk up the context of the caller.
1205   Decl *C = cast<Decl>(CurContext);
1206   do {
1207     if (C->isUnavailable())
1208       return false;
1209   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1210   return true;
1211 }
1212 
1213 /// Tries a user-defined conversion from From to ToType.
1214 ///
1215 /// Produces an implicit conversion sequence for when a standard conversion
1216 /// is not an option. See TryImplicitConversion for more information.
1217 static ImplicitConversionSequence
1218 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1219                          bool SuppressUserConversions,
1220                          bool AllowExplicit,
1221                          bool InOverloadResolution,
1222                          bool CStyle,
1223                          bool AllowObjCWritebackConversion,
1224                          bool AllowObjCConversionOnExplicit) {
1225   ImplicitConversionSequence ICS;
1226 
1227   if (SuppressUserConversions) {
1228     // We're not in the case above, so there is no conversion that
1229     // we can perform.
1230     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1231     return ICS;
1232   }
1233 
1234   // Attempt user-defined conversion.
1235   OverloadCandidateSet Conversions(From->getExprLoc(),
1236                                    OverloadCandidateSet::CSK_Normal);
1237   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1238                                   Conversions, AllowExplicit,
1239                                   AllowObjCConversionOnExplicit)) {
1240   case OR_Success:
1241   case OR_Deleted:
1242     ICS.setUserDefined();
1243     // C++ [over.ics.user]p4:
1244     //   A conversion of an expression of class type to the same class
1245     //   type is given Exact Match rank, and a conversion of an
1246     //   expression of class type to a base class of that type is
1247     //   given Conversion rank, in spite of the fact that a copy
1248     //   constructor (i.e., a user-defined conversion function) is
1249     //   called for those cases.
1250     if (CXXConstructorDecl *Constructor
1251           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1252       QualType FromCanon
1253         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1254       QualType ToCanon
1255         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1256       if (Constructor->isCopyConstructor() &&
1257           (FromCanon == ToCanon ||
1258            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1259         // Turn this into a "standard" conversion sequence, so that it
1260         // gets ranked with standard conversion sequences.
1261         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1262         ICS.setStandard();
1263         ICS.Standard.setAsIdentityConversion();
1264         ICS.Standard.setFromType(From->getType());
1265         ICS.Standard.setAllToTypes(ToType);
1266         ICS.Standard.CopyConstructor = Constructor;
1267         ICS.Standard.FoundCopyConstructor = Found;
1268         if (ToCanon != FromCanon)
1269           ICS.Standard.Second = ICK_Derived_To_Base;
1270       }
1271     }
1272     break;
1273 
1274   case OR_Ambiguous:
1275     ICS.setAmbiguous();
1276     ICS.Ambiguous.setFromType(From->getType());
1277     ICS.Ambiguous.setToType(ToType);
1278     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1279          Cand != Conversions.end(); ++Cand)
1280       if (Cand->Viable)
1281         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1282     break;
1283 
1284     // Fall through.
1285   case OR_No_Viable_Function:
1286     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1287     break;
1288   }
1289 
1290   return ICS;
1291 }
1292 
1293 /// TryImplicitConversion - Attempt to perform an implicit conversion
1294 /// from the given expression (Expr) to the given type (ToType). This
1295 /// function returns an implicit conversion sequence that can be used
1296 /// to perform the initialization. Given
1297 ///
1298 ///   void f(float f);
1299 ///   void g(int i) { f(i); }
1300 ///
1301 /// this routine would produce an implicit conversion sequence to
1302 /// describe the initialization of f from i, which will be a standard
1303 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1304 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1305 //
1306 /// Note that this routine only determines how the conversion can be
1307 /// performed; it does not actually perform the conversion. As such,
1308 /// it will not produce any diagnostics if no conversion is available,
1309 /// but will instead return an implicit conversion sequence of kind
1310 /// "BadConversion".
1311 ///
1312 /// If @p SuppressUserConversions, then user-defined conversions are
1313 /// not permitted.
1314 /// If @p AllowExplicit, then explicit user-defined conversions are
1315 /// permitted.
1316 ///
1317 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1318 /// writeback conversion, which allows __autoreleasing id* parameters to
1319 /// be initialized with __strong id* or __weak id* arguments.
1320 static ImplicitConversionSequence
1321 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1322                       bool SuppressUserConversions,
1323                       bool AllowExplicit,
1324                       bool InOverloadResolution,
1325                       bool CStyle,
1326                       bool AllowObjCWritebackConversion,
1327                       bool AllowObjCConversionOnExplicit) {
1328   ImplicitConversionSequence ICS;
1329   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1330                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1331     ICS.setStandard();
1332     return ICS;
1333   }
1334 
1335   if (!S.getLangOpts().CPlusPlus) {
1336     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1337     return ICS;
1338   }
1339 
1340   // C++ [over.ics.user]p4:
1341   //   A conversion of an expression of class type to the same class
1342   //   type is given Exact Match rank, and a conversion of an
1343   //   expression of class type to a base class of that type is
1344   //   given Conversion rank, in spite of the fact that a copy/move
1345   //   constructor (i.e., a user-defined conversion function) is
1346   //   called for those cases.
1347   QualType FromType = From->getType();
1348   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1349       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1350        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1351     ICS.setStandard();
1352     ICS.Standard.setAsIdentityConversion();
1353     ICS.Standard.setFromType(FromType);
1354     ICS.Standard.setAllToTypes(ToType);
1355 
1356     // We don't actually check at this point whether there is a valid
1357     // copy/move constructor, since overloading just assumes that it
1358     // exists. When we actually perform initialization, we'll find the
1359     // appropriate constructor to copy the returned object, if needed.
1360     ICS.Standard.CopyConstructor = nullptr;
1361 
1362     // Determine whether this is considered a derived-to-base conversion.
1363     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1364       ICS.Standard.Second = ICK_Derived_To_Base;
1365 
1366     return ICS;
1367   }
1368 
1369   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1370                                   AllowExplicit, InOverloadResolution, CStyle,
1371                                   AllowObjCWritebackConversion,
1372                                   AllowObjCConversionOnExplicit);
1373 }
1374 
1375 ImplicitConversionSequence
1376 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1377                             bool SuppressUserConversions,
1378                             bool AllowExplicit,
1379                             bool InOverloadResolution,
1380                             bool CStyle,
1381                             bool AllowObjCWritebackConversion) {
1382   return ::TryImplicitConversion(*this, From, ToType,
1383                                  SuppressUserConversions, AllowExplicit,
1384                                  InOverloadResolution, CStyle,
1385                                  AllowObjCWritebackConversion,
1386                                  /*AllowObjCConversionOnExplicit=*/false);
1387 }
1388 
1389 /// PerformImplicitConversion - Perform an implicit conversion of the
1390 /// expression From to the type ToType. Returns the
1391 /// converted expression. Flavor is the kind of conversion we're
1392 /// performing, used in the error message. If @p AllowExplicit,
1393 /// explicit user-defined conversions are permitted.
1394 ExprResult
1395 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1396                                 AssignmentAction Action, bool AllowExplicit) {
1397   ImplicitConversionSequence ICS;
1398   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1399 }
1400 
1401 ExprResult
1402 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1403                                 AssignmentAction Action, bool AllowExplicit,
1404                                 ImplicitConversionSequence& ICS) {
1405   if (checkPlaceholderForOverload(*this, From))
1406     return ExprError();
1407 
1408   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1409   bool AllowObjCWritebackConversion
1410     = getLangOpts().ObjCAutoRefCount &&
1411       (Action == AA_Passing || Action == AA_Sending);
1412   if (getLangOpts().ObjC1)
1413     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1414                                       ToType, From->getType(), From);
1415   ICS = ::TryImplicitConversion(*this, From, ToType,
1416                                 /*SuppressUserConversions=*/false,
1417                                 AllowExplicit,
1418                                 /*InOverloadResolution=*/false,
1419                                 /*CStyle=*/false,
1420                                 AllowObjCWritebackConversion,
1421                                 /*AllowObjCConversionOnExplicit=*/false);
1422   return PerformImplicitConversion(From, ToType, ICS, Action);
1423 }
1424 
1425 /// Determine whether the conversion from FromType to ToType is a valid
1426 /// conversion that strips "noexcept" or "noreturn" off the nested function
1427 /// type.
1428 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1429                                 QualType &ResultTy) {
1430   if (Context.hasSameUnqualifiedType(FromType, ToType))
1431     return false;
1432 
1433   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1434   //                    or F(t noexcept) -> F(t)
1435   // where F adds one of the following at most once:
1436   //   - a pointer
1437   //   - a member pointer
1438   //   - a block pointer
1439   // Changes here need matching changes in FindCompositePointerType.
1440   CanQualType CanTo = Context.getCanonicalType(ToType);
1441   CanQualType CanFrom = Context.getCanonicalType(FromType);
1442   Type::TypeClass TyClass = CanTo->getTypeClass();
1443   if (TyClass != CanFrom->getTypeClass()) return false;
1444   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1445     if (TyClass == Type::Pointer) {
1446       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1447       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1448     } else if (TyClass == Type::BlockPointer) {
1449       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1450       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1451     } else if (TyClass == Type::MemberPointer) {
1452       auto ToMPT = CanTo.getAs<MemberPointerType>();
1453       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1454       // A function pointer conversion cannot change the class of the function.
1455       if (ToMPT->getClass() != FromMPT->getClass())
1456         return false;
1457       CanTo = ToMPT->getPointeeType();
1458       CanFrom = FromMPT->getPointeeType();
1459     } else {
1460       return false;
1461     }
1462 
1463     TyClass = CanTo->getTypeClass();
1464     if (TyClass != CanFrom->getTypeClass()) return false;
1465     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1466       return false;
1467   }
1468 
1469   const auto *FromFn = cast<FunctionType>(CanFrom);
1470   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1471 
1472   const auto *ToFn = cast<FunctionType>(CanTo);
1473   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1474 
1475   bool Changed = false;
1476 
1477   // Drop 'noreturn' if not present in target type.
1478   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1479     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1480     Changed = true;
1481   }
1482 
1483   // Drop 'noexcept' if not present in target type.
1484   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1485     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1486     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1487       FromFn = cast<FunctionType>(
1488           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1489                                                    EST_None)
1490                  .getTypePtr());
1491       Changed = true;
1492     }
1493 
1494     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1495     // only if the ExtParameterInfo lists of the two function prototypes can be
1496     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1497     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1498     bool CanUseToFPT, CanUseFromFPT;
1499     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1500                                       CanUseFromFPT, NewParamInfos) &&
1501         CanUseToFPT && !CanUseFromFPT) {
1502       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1503       ExtInfo.ExtParameterInfos =
1504           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1505       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1506                                             FromFPT->getParamTypes(), ExtInfo);
1507       FromFn = QT->getAs<FunctionType>();
1508       Changed = true;
1509     }
1510   }
1511 
1512   if (!Changed)
1513     return false;
1514 
1515   assert(QualType(FromFn, 0).isCanonical());
1516   if (QualType(FromFn, 0) != CanTo) return false;
1517 
1518   ResultTy = ToType;
1519   return true;
1520 }
1521 
1522 /// Determine whether the conversion from FromType to ToType is a valid
1523 /// vector conversion.
1524 ///
1525 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1526 /// conversion.
1527 static bool IsVectorConversion(Sema &S, QualType FromType,
1528                                QualType ToType, ImplicitConversionKind &ICK) {
1529   // We need at least one of these types to be a vector type to have a vector
1530   // conversion.
1531   if (!ToType->isVectorType() && !FromType->isVectorType())
1532     return false;
1533 
1534   // Identical types require no conversions.
1535   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1536     return false;
1537 
1538   // There are no conversions between extended vector types, only identity.
1539   if (ToType->isExtVectorType()) {
1540     // There are no conversions between extended vector types other than the
1541     // identity conversion.
1542     if (FromType->isExtVectorType())
1543       return false;
1544 
1545     // Vector splat from any arithmetic type to a vector.
1546     if (FromType->isArithmeticType()) {
1547       ICK = ICK_Vector_Splat;
1548       return true;
1549     }
1550   }
1551 
1552   // We can perform the conversion between vector types in the following cases:
1553   // 1)vector types are equivalent AltiVec and GCC vector types
1554   // 2)lax vector conversions are permitted and the vector types are of the
1555   //   same size
1556   if (ToType->isVectorType() && FromType->isVectorType()) {
1557     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1558         S.isLaxVectorConversion(FromType, ToType)) {
1559       ICK = ICK_Vector_Conversion;
1560       return true;
1561     }
1562   }
1563 
1564   return false;
1565 }
1566 
1567 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1568                                 bool InOverloadResolution,
1569                                 StandardConversionSequence &SCS,
1570                                 bool CStyle);
1571 
1572 /// IsStandardConversion - Determines whether there is a standard
1573 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1574 /// expression From to the type ToType. Standard conversion sequences
1575 /// only consider non-class types; for conversions that involve class
1576 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1577 /// contain the standard conversion sequence required to perform this
1578 /// conversion and this routine will return true. Otherwise, this
1579 /// routine will return false and the value of SCS is unspecified.
1580 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1581                                  bool InOverloadResolution,
1582                                  StandardConversionSequence &SCS,
1583                                  bool CStyle,
1584                                  bool AllowObjCWritebackConversion) {
1585   QualType FromType = From->getType();
1586 
1587   // Standard conversions (C++ [conv])
1588   SCS.setAsIdentityConversion();
1589   SCS.IncompatibleObjC = false;
1590   SCS.setFromType(FromType);
1591   SCS.CopyConstructor = nullptr;
1592 
1593   // There are no standard conversions for class types in C++, so
1594   // abort early. When overloading in C, however, we do permit them.
1595   if (S.getLangOpts().CPlusPlus &&
1596       (FromType->isRecordType() || ToType->isRecordType()))
1597     return false;
1598 
1599   // The first conversion can be an lvalue-to-rvalue conversion,
1600   // array-to-pointer conversion, or function-to-pointer conversion
1601   // (C++ 4p1).
1602 
1603   if (FromType == S.Context.OverloadTy) {
1604     DeclAccessPair AccessPair;
1605     if (FunctionDecl *Fn
1606           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1607                                                  AccessPair)) {
1608       // We were able to resolve the address of the overloaded function,
1609       // so we can convert to the type of that function.
1610       FromType = Fn->getType();
1611       SCS.setFromType(FromType);
1612 
1613       // we can sometimes resolve &foo<int> regardless of ToType, so check
1614       // if the type matches (identity) or we are converting to bool
1615       if (!S.Context.hasSameUnqualifiedType(
1616                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1617         QualType resultTy;
1618         // if the function type matches except for [[noreturn]], it's ok
1619         if (!S.IsFunctionConversion(FromType,
1620               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1621           // otherwise, only a boolean conversion is standard
1622           if (!ToType->isBooleanType())
1623             return false;
1624       }
1625 
1626       // Check if the "from" expression is taking the address of an overloaded
1627       // function and recompute the FromType accordingly. Take advantage of the
1628       // fact that non-static member functions *must* have such an address-of
1629       // expression.
1630       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1631       if (Method && !Method->isStatic()) {
1632         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1633                "Non-unary operator on non-static member address");
1634         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1635                == UO_AddrOf &&
1636                "Non-address-of operator on non-static member address");
1637         const Type *ClassType
1638           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1639         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1640       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1641         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1642                UO_AddrOf &&
1643                "Non-address-of operator for overloaded function expression");
1644         FromType = S.Context.getPointerType(FromType);
1645       }
1646 
1647       // Check that we've computed the proper type after overload resolution.
1648       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1649       // be calling it from within an NDEBUG block.
1650       assert(S.Context.hasSameType(
1651         FromType,
1652         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1653     } else {
1654       return false;
1655     }
1656   }
1657   // Lvalue-to-rvalue conversion (C++11 4.1):
1658   //   A glvalue (3.10) of a non-function, non-array type T can
1659   //   be converted to a prvalue.
1660   bool argIsLValue = From->isGLValue();
1661   if (argIsLValue &&
1662       !FromType->isFunctionType() && !FromType->isArrayType() &&
1663       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1664     SCS.First = ICK_Lvalue_To_Rvalue;
1665 
1666     // C11 6.3.2.1p2:
1667     //   ... if the lvalue has atomic type, the value has the non-atomic version
1668     //   of the type of the lvalue ...
1669     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1670       FromType = Atomic->getValueType();
1671 
1672     // If T is a non-class type, the type of the rvalue is the
1673     // cv-unqualified version of T. Otherwise, the type of the rvalue
1674     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1675     // just strip the qualifiers because they don't matter.
1676     FromType = FromType.getUnqualifiedType();
1677   } else if (FromType->isArrayType()) {
1678     // Array-to-pointer conversion (C++ 4.2)
1679     SCS.First = ICK_Array_To_Pointer;
1680 
1681     // An lvalue or rvalue of type "array of N T" or "array of unknown
1682     // bound of T" can be converted to an rvalue of type "pointer to
1683     // T" (C++ 4.2p1).
1684     FromType = S.Context.getArrayDecayedType(FromType);
1685 
1686     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1687       // This conversion is deprecated in C++03 (D.4)
1688       SCS.DeprecatedStringLiteralToCharPtr = true;
1689 
1690       // For the purpose of ranking in overload resolution
1691       // (13.3.3.1.1), this conversion is considered an
1692       // array-to-pointer conversion followed by a qualification
1693       // conversion (4.4). (C++ 4.2p2)
1694       SCS.Second = ICK_Identity;
1695       SCS.Third = ICK_Qualification;
1696       SCS.QualificationIncludesObjCLifetime = false;
1697       SCS.setAllToTypes(FromType);
1698       return true;
1699     }
1700   } else if (FromType->isFunctionType() && argIsLValue) {
1701     // Function-to-pointer conversion (C++ 4.3).
1702     SCS.First = ICK_Function_To_Pointer;
1703 
1704     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1705       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1706         if (!S.checkAddressOfFunctionIsAvailable(FD))
1707           return false;
1708 
1709     // An lvalue of function type T can be converted to an rvalue of
1710     // type "pointer to T." The result is a pointer to the
1711     // function. (C++ 4.3p1).
1712     FromType = S.Context.getPointerType(FromType);
1713   } else {
1714     // We don't require any conversions for the first step.
1715     SCS.First = ICK_Identity;
1716   }
1717   SCS.setToType(0, FromType);
1718 
1719   // The second conversion can be an integral promotion, floating
1720   // point promotion, integral conversion, floating point conversion,
1721   // floating-integral conversion, pointer conversion,
1722   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1723   // For overloading in C, this can also be a "compatible-type"
1724   // conversion.
1725   bool IncompatibleObjC = false;
1726   ImplicitConversionKind SecondICK = ICK_Identity;
1727   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1728     // The unqualified versions of the types are the same: there's no
1729     // conversion to do.
1730     SCS.Second = ICK_Identity;
1731   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1732     // Integral promotion (C++ 4.5).
1733     SCS.Second = ICK_Integral_Promotion;
1734     FromType = ToType.getUnqualifiedType();
1735   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1736     // Floating point promotion (C++ 4.6).
1737     SCS.Second = ICK_Floating_Promotion;
1738     FromType = ToType.getUnqualifiedType();
1739   } else if (S.IsComplexPromotion(FromType, ToType)) {
1740     // Complex promotion (Clang extension)
1741     SCS.Second = ICK_Complex_Promotion;
1742     FromType = ToType.getUnqualifiedType();
1743   } else if (ToType->isBooleanType() &&
1744              (FromType->isArithmeticType() ||
1745               FromType->isAnyPointerType() ||
1746               FromType->isBlockPointerType() ||
1747               FromType->isMemberPointerType() ||
1748               FromType->isNullPtrType())) {
1749     // Boolean conversions (C++ 4.12).
1750     SCS.Second = ICK_Boolean_Conversion;
1751     FromType = S.Context.BoolTy;
1752   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1753              ToType->isIntegralType(S.Context)) {
1754     // Integral conversions (C++ 4.7).
1755     SCS.Second = ICK_Integral_Conversion;
1756     FromType = ToType.getUnqualifiedType();
1757   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1758     // Complex conversions (C99 6.3.1.6)
1759     SCS.Second = ICK_Complex_Conversion;
1760     FromType = ToType.getUnqualifiedType();
1761   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1762              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1763     // Complex-real conversions (C99 6.3.1.7)
1764     SCS.Second = ICK_Complex_Real;
1765     FromType = ToType.getUnqualifiedType();
1766   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1767     // FIXME: disable conversions between long double and __float128 if
1768     // their representation is different until there is back end support
1769     // We of course allow this conversion if long double is really double.
1770     if (&S.Context.getFloatTypeSemantics(FromType) !=
1771         &S.Context.getFloatTypeSemantics(ToType)) {
1772       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1773                                     ToType == S.Context.LongDoubleTy) ||
1774                                    (FromType == S.Context.LongDoubleTy &&
1775                                     ToType == S.Context.Float128Ty));
1776       if (Float128AndLongDouble &&
1777           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1778            &llvm::APFloat::PPCDoubleDouble()))
1779         return false;
1780     }
1781     // Floating point conversions (C++ 4.8).
1782     SCS.Second = ICK_Floating_Conversion;
1783     FromType = ToType.getUnqualifiedType();
1784   } else if ((FromType->isRealFloatingType() &&
1785               ToType->isIntegralType(S.Context)) ||
1786              (FromType->isIntegralOrUnscopedEnumerationType() &&
1787               ToType->isRealFloatingType())) {
1788     // Floating-integral conversions (C++ 4.9).
1789     SCS.Second = ICK_Floating_Integral;
1790     FromType = ToType.getUnqualifiedType();
1791   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1792     SCS.Second = ICK_Block_Pointer_Conversion;
1793   } else if (AllowObjCWritebackConversion &&
1794              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1795     SCS.Second = ICK_Writeback_Conversion;
1796   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1797                                    FromType, IncompatibleObjC)) {
1798     // Pointer conversions (C++ 4.10).
1799     SCS.Second = ICK_Pointer_Conversion;
1800     SCS.IncompatibleObjC = IncompatibleObjC;
1801     FromType = FromType.getUnqualifiedType();
1802   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1803                                          InOverloadResolution, FromType)) {
1804     // Pointer to member conversions (4.11).
1805     SCS.Second = ICK_Pointer_Member;
1806   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1807     SCS.Second = SecondICK;
1808     FromType = ToType.getUnqualifiedType();
1809   } else if (!S.getLangOpts().CPlusPlus &&
1810              S.Context.typesAreCompatible(ToType, FromType)) {
1811     // Compatible conversions (Clang extension for C function overloading)
1812     SCS.Second = ICK_Compatible_Conversion;
1813     FromType = ToType.getUnqualifiedType();
1814   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1815                                              InOverloadResolution,
1816                                              SCS, CStyle)) {
1817     SCS.Second = ICK_TransparentUnionConversion;
1818     FromType = ToType;
1819   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1820                                  CStyle)) {
1821     // tryAtomicConversion has updated the standard conversion sequence
1822     // appropriately.
1823     return true;
1824   } else if (ToType->isEventT() &&
1825              From->isIntegerConstantExpr(S.getASTContext()) &&
1826              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1827     SCS.Second = ICK_Zero_Event_Conversion;
1828     FromType = ToType;
1829   } else if (ToType->isQueueT() &&
1830              From->isIntegerConstantExpr(S.getASTContext()) &&
1831              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1832     SCS.Second = ICK_Zero_Queue_Conversion;
1833     FromType = ToType;
1834   } else {
1835     // No second conversion required.
1836     SCS.Second = ICK_Identity;
1837   }
1838   SCS.setToType(1, FromType);
1839 
1840   // The third conversion can be a function pointer conversion or a
1841   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1842   bool ObjCLifetimeConversion;
1843   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1844     // Function pointer conversions (removing 'noexcept') including removal of
1845     // 'noreturn' (Clang extension).
1846     SCS.Third = ICK_Function_Conversion;
1847   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1848                                          ObjCLifetimeConversion)) {
1849     SCS.Third = ICK_Qualification;
1850     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1851     FromType = ToType;
1852   } else {
1853     // No conversion required
1854     SCS.Third = ICK_Identity;
1855   }
1856 
1857   // C++ [over.best.ics]p6:
1858   //   [...] Any difference in top-level cv-qualification is
1859   //   subsumed by the initialization itself and does not constitute
1860   //   a conversion. [...]
1861   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1862   QualType CanonTo = S.Context.getCanonicalType(ToType);
1863   if (CanonFrom.getLocalUnqualifiedType()
1864                                      == CanonTo.getLocalUnqualifiedType() &&
1865       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1866     FromType = ToType;
1867     CanonFrom = CanonTo;
1868   }
1869 
1870   SCS.setToType(2, FromType);
1871 
1872   if (CanonFrom == CanonTo)
1873     return true;
1874 
1875   // If we have not converted the argument type to the parameter type,
1876   // this is a bad conversion sequence, unless we're resolving an overload in C.
1877   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1878     return false;
1879 
1880   ExprResult ER = ExprResult{From};
1881   Sema::AssignConvertType Conv =
1882       S.CheckSingleAssignmentConstraints(ToType, ER,
1883                                          /*Diagnose=*/false,
1884                                          /*DiagnoseCFAudited=*/false,
1885                                          /*ConvertRHS=*/false);
1886   ImplicitConversionKind SecondConv;
1887   switch (Conv) {
1888   case Sema::Compatible:
1889     SecondConv = ICK_C_Only_Conversion;
1890     break;
1891   // For our purposes, discarding qualifiers is just as bad as using an
1892   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1893   // qualifiers, as well.
1894   case Sema::CompatiblePointerDiscardsQualifiers:
1895   case Sema::IncompatiblePointer:
1896   case Sema::IncompatiblePointerSign:
1897     SecondConv = ICK_Incompatible_Pointer_Conversion;
1898     break;
1899   default:
1900     return false;
1901   }
1902 
1903   // First can only be an lvalue conversion, so we pretend that this was the
1904   // second conversion. First should already be valid from earlier in the
1905   // function.
1906   SCS.Second = SecondConv;
1907   SCS.setToType(1, ToType);
1908 
1909   // Third is Identity, because Second should rank us worse than any other
1910   // conversion. This could also be ICK_Qualification, but it's simpler to just
1911   // lump everything in with the second conversion, and we don't gain anything
1912   // from making this ICK_Qualification.
1913   SCS.Third = ICK_Identity;
1914   SCS.setToType(2, ToType);
1915   return true;
1916 }
1917 
1918 static bool
1919 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1920                                      QualType &ToType,
1921                                      bool InOverloadResolution,
1922                                      StandardConversionSequence &SCS,
1923                                      bool CStyle) {
1924 
1925   const RecordType *UT = ToType->getAsUnionType();
1926   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1927     return false;
1928   // The field to initialize within the transparent union.
1929   RecordDecl *UD = UT->getDecl();
1930   // It's compatible if the expression matches any of the fields.
1931   for (const auto *it : UD->fields()) {
1932     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1933                              CStyle, /*ObjCWritebackConversion=*/false)) {
1934       ToType = it->getType();
1935       return true;
1936     }
1937   }
1938   return false;
1939 }
1940 
1941 /// IsIntegralPromotion - Determines whether the conversion from the
1942 /// expression From (whose potentially-adjusted type is FromType) to
1943 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1944 /// sets PromotedType to the promoted type.
1945 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1946   const BuiltinType *To = ToType->getAs<BuiltinType>();
1947   // All integers are built-in.
1948   if (!To) {
1949     return false;
1950   }
1951 
1952   // An rvalue of type char, signed char, unsigned char, short int, or
1953   // unsigned short int can be converted to an rvalue of type int if
1954   // int can represent all the values of the source type; otherwise,
1955   // the source rvalue can be converted to an rvalue of type unsigned
1956   // int (C++ 4.5p1).
1957   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1958       !FromType->isEnumeralType()) {
1959     if (// We can promote any signed, promotable integer type to an int
1960         (FromType->isSignedIntegerType() ||
1961          // We can promote any unsigned integer type whose size is
1962          // less than int to an int.
1963          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1964       return To->getKind() == BuiltinType::Int;
1965     }
1966 
1967     return To->getKind() == BuiltinType::UInt;
1968   }
1969 
1970   // C++11 [conv.prom]p3:
1971   //   A prvalue of an unscoped enumeration type whose underlying type is not
1972   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1973   //   following types that can represent all the values of the enumeration
1974   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1975   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1976   //   long long int. If none of the types in that list can represent all the
1977   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1978   //   type can be converted to an rvalue a prvalue of the extended integer type
1979   //   with lowest integer conversion rank (4.13) greater than the rank of long
1980   //   long in which all the values of the enumeration can be represented. If
1981   //   there are two such extended types, the signed one is chosen.
1982   // C++11 [conv.prom]p4:
1983   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1984   //   can be converted to a prvalue of its underlying type. Moreover, if
1985   //   integral promotion can be applied to its underlying type, a prvalue of an
1986   //   unscoped enumeration type whose underlying type is fixed can also be
1987   //   converted to a prvalue of the promoted underlying type.
1988   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1989     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1990     // provided for a scoped enumeration.
1991     if (FromEnumType->getDecl()->isScoped())
1992       return false;
1993 
1994     // We can perform an integral promotion to the underlying type of the enum,
1995     // even if that's not the promoted type. Note that the check for promoting
1996     // the underlying type is based on the type alone, and does not consider
1997     // the bitfield-ness of the actual source expression.
1998     if (FromEnumType->getDecl()->isFixed()) {
1999       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2000       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2001              IsIntegralPromotion(nullptr, Underlying, ToType);
2002     }
2003 
2004     // We have already pre-calculated the promotion type, so this is trivial.
2005     if (ToType->isIntegerType() &&
2006         isCompleteType(From->getLocStart(), FromType))
2007       return Context.hasSameUnqualifiedType(
2008           ToType, FromEnumType->getDecl()->getPromotionType());
2009   }
2010 
2011   // C++0x [conv.prom]p2:
2012   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2013   //   to an rvalue a prvalue of the first of the following types that can
2014   //   represent all the values of its underlying type: int, unsigned int,
2015   //   long int, unsigned long int, long long int, or unsigned long long int.
2016   //   If none of the types in that list can represent all the values of its
2017   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2018   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2019   //   type.
2020   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2021       ToType->isIntegerType()) {
2022     // Determine whether the type we're converting from is signed or
2023     // unsigned.
2024     bool FromIsSigned = FromType->isSignedIntegerType();
2025     uint64_t FromSize = Context.getTypeSize(FromType);
2026 
2027     // The types we'll try to promote to, in the appropriate
2028     // order. Try each of these types.
2029     QualType PromoteTypes[6] = {
2030       Context.IntTy, Context.UnsignedIntTy,
2031       Context.LongTy, Context.UnsignedLongTy ,
2032       Context.LongLongTy, Context.UnsignedLongLongTy
2033     };
2034     for (int Idx = 0; Idx < 6; ++Idx) {
2035       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2036       if (FromSize < ToSize ||
2037           (FromSize == ToSize &&
2038            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2039         // We found the type that we can promote to. If this is the
2040         // type we wanted, we have a promotion. Otherwise, no
2041         // promotion.
2042         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2043       }
2044     }
2045   }
2046 
2047   // An rvalue for an integral bit-field (9.6) can be converted to an
2048   // rvalue of type int if int can represent all the values of the
2049   // bit-field; otherwise, it can be converted to unsigned int if
2050   // unsigned int can represent all the values of the bit-field. If
2051   // the bit-field is larger yet, no integral promotion applies to
2052   // it. If the bit-field has an enumerated type, it is treated as any
2053   // other value of that type for promotion purposes (C++ 4.5p3).
2054   // FIXME: We should delay checking of bit-fields until we actually perform the
2055   // conversion.
2056   if (From) {
2057     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2058       llvm::APSInt BitWidth;
2059       if (FromType->isIntegralType(Context) &&
2060           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2061         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2062         ToSize = Context.getTypeSize(ToType);
2063 
2064         // Are we promoting to an int from a bitfield that fits in an int?
2065         if (BitWidth < ToSize ||
2066             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2067           return To->getKind() == BuiltinType::Int;
2068         }
2069 
2070         // Are we promoting to an unsigned int from an unsigned bitfield
2071         // that fits into an unsigned int?
2072         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2073           return To->getKind() == BuiltinType::UInt;
2074         }
2075 
2076         return false;
2077       }
2078     }
2079   }
2080 
2081   // An rvalue of type bool can be converted to an rvalue of type int,
2082   // with false becoming zero and true becoming one (C++ 4.5p4).
2083   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2084     return true;
2085   }
2086 
2087   return false;
2088 }
2089 
2090 /// IsFloatingPointPromotion - Determines whether the conversion from
2091 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2092 /// returns true and sets PromotedType to the promoted type.
2093 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2094   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2095     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2096       /// An rvalue of type float can be converted to an rvalue of type
2097       /// double. (C++ 4.6p1).
2098       if (FromBuiltin->getKind() == BuiltinType::Float &&
2099           ToBuiltin->getKind() == BuiltinType::Double)
2100         return true;
2101 
2102       // C99 6.3.1.5p1:
2103       //   When a float is promoted to double or long double, or a
2104       //   double is promoted to long double [...].
2105       if (!getLangOpts().CPlusPlus &&
2106           (FromBuiltin->getKind() == BuiltinType::Float ||
2107            FromBuiltin->getKind() == BuiltinType::Double) &&
2108           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2109            ToBuiltin->getKind() == BuiltinType::Float128))
2110         return true;
2111 
2112       // Half can be promoted to float.
2113       if (!getLangOpts().NativeHalfType &&
2114            FromBuiltin->getKind() == BuiltinType::Half &&
2115           ToBuiltin->getKind() == BuiltinType::Float)
2116         return true;
2117     }
2118 
2119   return false;
2120 }
2121 
2122 /// Determine if a conversion is a complex promotion.
2123 ///
2124 /// A complex promotion is defined as a complex -> complex conversion
2125 /// where the conversion between the underlying real types is a
2126 /// floating-point or integral promotion.
2127 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2128   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2129   if (!FromComplex)
2130     return false;
2131 
2132   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2133   if (!ToComplex)
2134     return false;
2135 
2136   return IsFloatingPointPromotion(FromComplex->getElementType(),
2137                                   ToComplex->getElementType()) ||
2138     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2139                         ToComplex->getElementType());
2140 }
2141 
2142 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2143 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2144 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2145 /// if non-empty, will be a pointer to ToType that may or may not have
2146 /// the right set of qualifiers on its pointee.
2147 ///
2148 static QualType
2149 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2150                                    QualType ToPointee, QualType ToType,
2151                                    ASTContext &Context,
2152                                    bool StripObjCLifetime = false) {
2153   assert((FromPtr->getTypeClass() == Type::Pointer ||
2154           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2155          "Invalid similarly-qualified pointer type");
2156 
2157   /// Conversions to 'id' subsume cv-qualifier conversions.
2158   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2159     return ToType.getUnqualifiedType();
2160 
2161   QualType CanonFromPointee
2162     = Context.getCanonicalType(FromPtr->getPointeeType());
2163   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2164   Qualifiers Quals = CanonFromPointee.getQualifiers();
2165 
2166   if (StripObjCLifetime)
2167     Quals.removeObjCLifetime();
2168 
2169   // Exact qualifier match -> return the pointer type we're converting to.
2170   if (CanonToPointee.getLocalQualifiers() == Quals) {
2171     // ToType is exactly what we need. Return it.
2172     if (!ToType.isNull())
2173       return ToType.getUnqualifiedType();
2174 
2175     // Build a pointer to ToPointee. It has the right qualifiers
2176     // already.
2177     if (isa<ObjCObjectPointerType>(ToType))
2178       return Context.getObjCObjectPointerType(ToPointee);
2179     return Context.getPointerType(ToPointee);
2180   }
2181 
2182   // Just build a canonical type that has the right qualifiers.
2183   QualType QualifiedCanonToPointee
2184     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2185 
2186   if (isa<ObjCObjectPointerType>(ToType))
2187     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2188   return Context.getPointerType(QualifiedCanonToPointee);
2189 }
2190 
2191 static bool isNullPointerConstantForConversion(Expr *Expr,
2192                                                bool InOverloadResolution,
2193                                                ASTContext &Context) {
2194   // Handle value-dependent integral null pointer constants correctly.
2195   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2196   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2197       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2198     return !InOverloadResolution;
2199 
2200   return Expr->isNullPointerConstant(Context,
2201                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2202                                         : Expr::NPC_ValueDependentIsNull);
2203 }
2204 
2205 /// IsPointerConversion - Determines whether the conversion of the
2206 /// expression From, which has the (possibly adjusted) type FromType,
2207 /// can be converted to the type ToType via a pointer conversion (C++
2208 /// 4.10). If so, returns true and places the converted type (that
2209 /// might differ from ToType in its cv-qualifiers at some level) into
2210 /// ConvertedType.
2211 ///
2212 /// This routine also supports conversions to and from block pointers
2213 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2214 /// pointers to interfaces. FIXME: Once we've determined the
2215 /// appropriate overloading rules for Objective-C, we may want to
2216 /// split the Objective-C checks into a different routine; however,
2217 /// GCC seems to consider all of these conversions to be pointer
2218 /// conversions, so for now they live here. IncompatibleObjC will be
2219 /// set if the conversion is an allowed Objective-C conversion that
2220 /// should result in a warning.
2221 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2222                                bool InOverloadResolution,
2223                                QualType& ConvertedType,
2224                                bool &IncompatibleObjC) {
2225   IncompatibleObjC = false;
2226   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2227                               IncompatibleObjC))
2228     return true;
2229 
2230   // Conversion from a null pointer constant to any Objective-C pointer type.
2231   if (ToType->isObjCObjectPointerType() &&
2232       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2233     ConvertedType = ToType;
2234     return true;
2235   }
2236 
2237   // Blocks: Block pointers can be converted to void*.
2238   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2239       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2240     ConvertedType = ToType;
2241     return true;
2242   }
2243   // Blocks: A null pointer constant can be converted to a block
2244   // pointer type.
2245   if (ToType->isBlockPointerType() &&
2246       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2247     ConvertedType = ToType;
2248     return true;
2249   }
2250 
2251   // If the left-hand-side is nullptr_t, the right side can be a null
2252   // pointer constant.
2253   if (ToType->isNullPtrType() &&
2254       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2255     ConvertedType = ToType;
2256     return true;
2257   }
2258 
2259   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2260   if (!ToTypePtr)
2261     return false;
2262 
2263   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2264   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2265     ConvertedType = ToType;
2266     return true;
2267   }
2268 
2269   // Beyond this point, both types need to be pointers
2270   // , including objective-c pointers.
2271   QualType ToPointeeType = ToTypePtr->getPointeeType();
2272   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2273       !getLangOpts().ObjCAutoRefCount) {
2274     ConvertedType = BuildSimilarlyQualifiedPointerType(
2275                                       FromType->getAs<ObjCObjectPointerType>(),
2276                                                        ToPointeeType,
2277                                                        ToType, Context);
2278     return true;
2279   }
2280   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2281   if (!FromTypePtr)
2282     return false;
2283 
2284   QualType FromPointeeType = FromTypePtr->getPointeeType();
2285 
2286   // If the unqualified pointee types are the same, this can't be a
2287   // pointer conversion, so don't do all of the work below.
2288   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2289     return false;
2290 
2291   // An rvalue of type "pointer to cv T," where T is an object type,
2292   // can be converted to an rvalue of type "pointer to cv void" (C++
2293   // 4.10p2).
2294   if (FromPointeeType->isIncompleteOrObjectType() &&
2295       ToPointeeType->isVoidType()) {
2296     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2297                                                        ToPointeeType,
2298                                                        ToType, Context,
2299                                                    /*StripObjCLifetime=*/true);
2300     return true;
2301   }
2302 
2303   // MSVC allows implicit function to void* type conversion.
2304   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2305       ToPointeeType->isVoidType()) {
2306     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2307                                                        ToPointeeType,
2308                                                        ToType, Context);
2309     return true;
2310   }
2311 
2312   // When we're overloading in C, we allow a special kind of pointer
2313   // conversion for compatible-but-not-identical pointee types.
2314   if (!getLangOpts().CPlusPlus &&
2315       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2316     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2317                                                        ToPointeeType,
2318                                                        ToType, Context);
2319     return true;
2320   }
2321 
2322   // C++ [conv.ptr]p3:
2323   //
2324   //   An rvalue of type "pointer to cv D," where D is a class type,
2325   //   can be converted to an rvalue of type "pointer to cv B," where
2326   //   B is a base class (clause 10) of D. If B is an inaccessible
2327   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2328   //   necessitates this conversion is ill-formed. The result of the
2329   //   conversion is a pointer to the base class sub-object of the
2330   //   derived class object. The null pointer value is converted to
2331   //   the null pointer value of the destination type.
2332   //
2333   // Note that we do not check for ambiguity or inaccessibility
2334   // here. That is handled by CheckPointerConversion.
2335   if (getLangOpts().CPlusPlus &&
2336       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2337       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2338       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2339     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2340                                                        ToPointeeType,
2341                                                        ToType, Context);
2342     return true;
2343   }
2344 
2345   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2346       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2347     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2348                                                        ToPointeeType,
2349                                                        ToType, Context);
2350     return true;
2351   }
2352 
2353   return false;
2354 }
2355 
2356 /// Adopt the given qualifiers for the given type.
2357 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2358   Qualifiers TQs = T.getQualifiers();
2359 
2360   // Check whether qualifiers already match.
2361   if (TQs == Qs)
2362     return T;
2363 
2364   if (Qs.compatiblyIncludes(TQs))
2365     return Context.getQualifiedType(T, Qs);
2366 
2367   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2368 }
2369 
2370 /// isObjCPointerConversion - Determines whether this is an
2371 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2372 /// with the same arguments and return values.
2373 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2374                                    QualType& ConvertedType,
2375                                    bool &IncompatibleObjC) {
2376   if (!getLangOpts().ObjC1)
2377     return false;
2378 
2379   // The set of qualifiers on the type we're converting from.
2380   Qualifiers FromQualifiers = FromType.getQualifiers();
2381 
2382   // First, we handle all conversions on ObjC object pointer types.
2383   const ObjCObjectPointerType* ToObjCPtr =
2384     ToType->getAs<ObjCObjectPointerType>();
2385   const ObjCObjectPointerType *FromObjCPtr =
2386     FromType->getAs<ObjCObjectPointerType>();
2387 
2388   if (ToObjCPtr && FromObjCPtr) {
2389     // If the pointee types are the same (ignoring qualifications),
2390     // then this is not a pointer conversion.
2391     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2392                                        FromObjCPtr->getPointeeType()))
2393       return false;
2394 
2395     // Conversion between Objective-C pointers.
2396     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2397       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2398       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2399       if (getLangOpts().CPlusPlus && LHS && RHS &&
2400           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2401                                                 FromObjCPtr->getPointeeType()))
2402         return false;
2403       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2404                                                    ToObjCPtr->getPointeeType(),
2405                                                          ToType, Context);
2406       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2407       return true;
2408     }
2409 
2410     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2411       // Okay: this is some kind of implicit downcast of Objective-C
2412       // interfaces, which is permitted. However, we're going to
2413       // complain about it.
2414       IncompatibleObjC = true;
2415       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2416                                                    ToObjCPtr->getPointeeType(),
2417                                                          ToType, Context);
2418       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2419       return true;
2420     }
2421   }
2422   // Beyond this point, both types need to be C pointers or block pointers.
2423   QualType ToPointeeType;
2424   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2425     ToPointeeType = ToCPtr->getPointeeType();
2426   else if (const BlockPointerType *ToBlockPtr =
2427             ToType->getAs<BlockPointerType>()) {
2428     // Objective C++: We're able to convert from a pointer to any object
2429     // to a block pointer type.
2430     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2431       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2432       return true;
2433     }
2434     ToPointeeType = ToBlockPtr->getPointeeType();
2435   }
2436   else if (FromType->getAs<BlockPointerType>() &&
2437            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2438     // Objective C++: We're able to convert from a block pointer type to a
2439     // pointer to any object.
2440     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2441     return true;
2442   }
2443   else
2444     return false;
2445 
2446   QualType FromPointeeType;
2447   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2448     FromPointeeType = FromCPtr->getPointeeType();
2449   else if (const BlockPointerType *FromBlockPtr =
2450            FromType->getAs<BlockPointerType>())
2451     FromPointeeType = FromBlockPtr->getPointeeType();
2452   else
2453     return false;
2454 
2455   // If we have pointers to pointers, recursively check whether this
2456   // is an Objective-C conversion.
2457   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2458       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2459                               IncompatibleObjC)) {
2460     // We always complain about this conversion.
2461     IncompatibleObjC = true;
2462     ConvertedType = Context.getPointerType(ConvertedType);
2463     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2464     return true;
2465   }
2466   // Allow conversion of pointee being objective-c pointer to another one;
2467   // as in I* to id.
2468   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2469       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2470       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2471                               IncompatibleObjC)) {
2472 
2473     ConvertedType = Context.getPointerType(ConvertedType);
2474     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2475     return true;
2476   }
2477 
2478   // If we have pointers to functions or blocks, check whether the only
2479   // differences in the argument and result types are in Objective-C
2480   // pointer conversions. If so, we permit the conversion (but
2481   // complain about it).
2482   const FunctionProtoType *FromFunctionType
2483     = FromPointeeType->getAs<FunctionProtoType>();
2484   const FunctionProtoType *ToFunctionType
2485     = ToPointeeType->getAs<FunctionProtoType>();
2486   if (FromFunctionType && ToFunctionType) {
2487     // If the function types are exactly the same, this isn't an
2488     // Objective-C pointer conversion.
2489     if (Context.getCanonicalType(FromPointeeType)
2490           == Context.getCanonicalType(ToPointeeType))
2491       return false;
2492 
2493     // Perform the quick checks that will tell us whether these
2494     // function types are obviously different.
2495     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2496         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2497         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2498       return false;
2499 
2500     bool HasObjCConversion = false;
2501     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2502         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2503       // Okay, the types match exactly. Nothing to do.
2504     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2505                                        ToFunctionType->getReturnType(),
2506                                        ConvertedType, IncompatibleObjC)) {
2507       // Okay, we have an Objective-C pointer conversion.
2508       HasObjCConversion = true;
2509     } else {
2510       // Function types are too different. Abort.
2511       return false;
2512     }
2513 
2514     // Check argument types.
2515     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2516          ArgIdx != NumArgs; ++ArgIdx) {
2517       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2518       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2519       if (Context.getCanonicalType(FromArgType)
2520             == Context.getCanonicalType(ToArgType)) {
2521         // Okay, the types match exactly. Nothing to do.
2522       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2523                                          ConvertedType, IncompatibleObjC)) {
2524         // Okay, we have an Objective-C pointer conversion.
2525         HasObjCConversion = true;
2526       } else {
2527         // Argument types are too different. Abort.
2528         return false;
2529       }
2530     }
2531 
2532     if (HasObjCConversion) {
2533       // We had an Objective-C conversion. Allow this pointer
2534       // conversion, but complain about it.
2535       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2536       IncompatibleObjC = true;
2537       return true;
2538     }
2539   }
2540 
2541   return false;
2542 }
2543 
2544 /// Determine whether this is an Objective-C writeback conversion,
2545 /// used for parameter passing when performing automatic reference counting.
2546 ///
2547 /// \param FromType The type we're converting form.
2548 ///
2549 /// \param ToType The type we're converting to.
2550 ///
2551 /// \param ConvertedType The type that will be produced after applying
2552 /// this conversion.
2553 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2554                                      QualType &ConvertedType) {
2555   if (!getLangOpts().ObjCAutoRefCount ||
2556       Context.hasSameUnqualifiedType(FromType, ToType))
2557     return false;
2558 
2559   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2560   QualType ToPointee;
2561   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2562     ToPointee = ToPointer->getPointeeType();
2563   else
2564     return false;
2565 
2566   Qualifiers ToQuals = ToPointee.getQualifiers();
2567   if (!ToPointee->isObjCLifetimeType() ||
2568       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2569       !ToQuals.withoutObjCLifetime().empty())
2570     return false;
2571 
2572   // Argument must be a pointer to __strong to __weak.
2573   QualType FromPointee;
2574   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2575     FromPointee = FromPointer->getPointeeType();
2576   else
2577     return false;
2578 
2579   Qualifiers FromQuals = FromPointee.getQualifiers();
2580   if (!FromPointee->isObjCLifetimeType() ||
2581       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2582        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2583     return false;
2584 
2585   // Make sure that we have compatible qualifiers.
2586   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2587   if (!ToQuals.compatiblyIncludes(FromQuals))
2588     return false;
2589 
2590   // Remove qualifiers from the pointee type we're converting from; they
2591   // aren't used in the compatibility check belong, and we'll be adding back
2592   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2593   FromPointee = FromPointee.getUnqualifiedType();
2594 
2595   // The unqualified form of the pointee types must be compatible.
2596   ToPointee = ToPointee.getUnqualifiedType();
2597   bool IncompatibleObjC;
2598   if (Context.typesAreCompatible(FromPointee, ToPointee))
2599     FromPointee = ToPointee;
2600   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2601                                     IncompatibleObjC))
2602     return false;
2603 
2604   /// Construct the type we're converting to, which is a pointer to
2605   /// __autoreleasing pointee.
2606   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2607   ConvertedType = Context.getPointerType(FromPointee);
2608   return true;
2609 }
2610 
2611 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2612                                     QualType& ConvertedType) {
2613   QualType ToPointeeType;
2614   if (const BlockPointerType *ToBlockPtr =
2615         ToType->getAs<BlockPointerType>())
2616     ToPointeeType = ToBlockPtr->getPointeeType();
2617   else
2618     return false;
2619 
2620   QualType FromPointeeType;
2621   if (const BlockPointerType *FromBlockPtr =
2622       FromType->getAs<BlockPointerType>())
2623     FromPointeeType = FromBlockPtr->getPointeeType();
2624   else
2625     return false;
2626   // We have pointer to blocks, check whether the only
2627   // differences in the argument and result types are in Objective-C
2628   // pointer conversions. If so, we permit the conversion.
2629 
2630   const FunctionProtoType *FromFunctionType
2631     = FromPointeeType->getAs<FunctionProtoType>();
2632   const FunctionProtoType *ToFunctionType
2633     = ToPointeeType->getAs<FunctionProtoType>();
2634 
2635   if (!FromFunctionType || !ToFunctionType)
2636     return false;
2637 
2638   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2639     return true;
2640 
2641   // Perform the quick checks that will tell us whether these
2642   // function types are obviously different.
2643   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2644       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2645     return false;
2646 
2647   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2648   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2649   if (FromEInfo != ToEInfo)
2650     return false;
2651 
2652   bool IncompatibleObjC = false;
2653   if (Context.hasSameType(FromFunctionType->getReturnType(),
2654                           ToFunctionType->getReturnType())) {
2655     // Okay, the types match exactly. Nothing to do.
2656   } else {
2657     QualType RHS = FromFunctionType->getReturnType();
2658     QualType LHS = ToFunctionType->getReturnType();
2659     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2660         !RHS.hasQualifiers() && LHS.hasQualifiers())
2661        LHS = LHS.getUnqualifiedType();
2662 
2663      if (Context.hasSameType(RHS,LHS)) {
2664        // OK exact match.
2665      } else if (isObjCPointerConversion(RHS, LHS,
2666                                         ConvertedType, IncompatibleObjC)) {
2667      if (IncompatibleObjC)
2668        return false;
2669      // Okay, we have an Objective-C pointer conversion.
2670      }
2671      else
2672        return false;
2673    }
2674 
2675    // Check argument types.
2676    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2677         ArgIdx != NumArgs; ++ArgIdx) {
2678      IncompatibleObjC = false;
2679      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2680      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2681      if (Context.hasSameType(FromArgType, ToArgType)) {
2682        // Okay, the types match exactly. Nothing to do.
2683      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2684                                         ConvertedType, IncompatibleObjC)) {
2685        if (IncompatibleObjC)
2686          return false;
2687        // Okay, we have an Objective-C pointer conversion.
2688      } else
2689        // Argument types are too different. Abort.
2690        return false;
2691    }
2692 
2693    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2694    bool CanUseToFPT, CanUseFromFPT;
2695    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2696                                       CanUseToFPT, CanUseFromFPT,
2697                                       NewParamInfos))
2698      return false;
2699 
2700    ConvertedType = ToType;
2701    return true;
2702 }
2703 
2704 enum {
2705   ft_default,
2706   ft_different_class,
2707   ft_parameter_arity,
2708   ft_parameter_mismatch,
2709   ft_return_type,
2710   ft_qualifer_mismatch,
2711   ft_noexcept
2712 };
2713 
2714 /// Attempts to get the FunctionProtoType from a Type. Handles
2715 /// MemberFunctionPointers properly.
2716 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2717   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2718     return FPT;
2719 
2720   if (auto *MPT = FromType->getAs<MemberPointerType>())
2721     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2722 
2723   return nullptr;
2724 }
2725 
2726 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2727 /// function types.  Catches different number of parameter, mismatch in
2728 /// parameter types, and different return types.
2729 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2730                                       QualType FromType, QualType ToType) {
2731   // If either type is not valid, include no extra info.
2732   if (FromType.isNull() || ToType.isNull()) {
2733     PDiag << ft_default;
2734     return;
2735   }
2736 
2737   // Get the function type from the pointers.
2738   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2739     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2740                             *ToMember = ToType->getAs<MemberPointerType>();
2741     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2742       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2743             << QualType(FromMember->getClass(), 0);
2744       return;
2745     }
2746     FromType = FromMember->getPointeeType();
2747     ToType = ToMember->getPointeeType();
2748   }
2749 
2750   if (FromType->isPointerType())
2751     FromType = FromType->getPointeeType();
2752   if (ToType->isPointerType())
2753     ToType = ToType->getPointeeType();
2754 
2755   // Remove references.
2756   FromType = FromType.getNonReferenceType();
2757   ToType = ToType.getNonReferenceType();
2758 
2759   // Don't print extra info for non-specialized template functions.
2760   if (FromType->isInstantiationDependentType() &&
2761       !FromType->getAs<TemplateSpecializationType>()) {
2762     PDiag << ft_default;
2763     return;
2764   }
2765 
2766   // No extra info for same types.
2767   if (Context.hasSameType(FromType, ToType)) {
2768     PDiag << ft_default;
2769     return;
2770   }
2771 
2772   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2773                           *ToFunction = tryGetFunctionProtoType(ToType);
2774 
2775   // Both types need to be function types.
2776   if (!FromFunction || !ToFunction) {
2777     PDiag << ft_default;
2778     return;
2779   }
2780 
2781   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2782     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2783           << FromFunction->getNumParams();
2784     return;
2785   }
2786 
2787   // Handle different parameter types.
2788   unsigned ArgPos;
2789   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2790     PDiag << ft_parameter_mismatch << ArgPos + 1
2791           << ToFunction->getParamType(ArgPos)
2792           << FromFunction->getParamType(ArgPos);
2793     return;
2794   }
2795 
2796   // Handle different return type.
2797   if (!Context.hasSameType(FromFunction->getReturnType(),
2798                            ToFunction->getReturnType())) {
2799     PDiag << ft_return_type << ToFunction->getReturnType()
2800           << FromFunction->getReturnType();
2801     return;
2802   }
2803 
2804   unsigned FromQuals = FromFunction->getTypeQuals(),
2805            ToQuals = ToFunction->getTypeQuals();
2806   if (FromQuals != ToQuals) {
2807     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2808     return;
2809   }
2810 
2811   // Handle exception specification differences on canonical type (in C++17
2812   // onwards).
2813   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2814           ->isNothrow() !=
2815       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2816           ->isNothrow()) {
2817     PDiag << ft_noexcept;
2818     return;
2819   }
2820 
2821   // Unable to find a difference, so add no extra info.
2822   PDiag << ft_default;
2823 }
2824 
2825 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2826 /// for equality of their argument types. Caller has already checked that
2827 /// they have same number of arguments.  If the parameters are different,
2828 /// ArgPos will have the parameter index of the first different parameter.
2829 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2830                                       const FunctionProtoType *NewType,
2831                                       unsigned *ArgPos) {
2832   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2833                                               N = NewType->param_type_begin(),
2834                                               E = OldType->param_type_end();
2835        O && (O != E); ++O, ++N) {
2836     if (!Context.hasSameType(O->getUnqualifiedType(),
2837                              N->getUnqualifiedType())) {
2838       if (ArgPos)
2839         *ArgPos = O - OldType->param_type_begin();
2840       return false;
2841     }
2842   }
2843   return true;
2844 }
2845 
2846 /// CheckPointerConversion - Check the pointer conversion from the
2847 /// expression From to the type ToType. This routine checks for
2848 /// ambiguous or inaccessible derived-to-base pointer
2849 /// conversions for which IsPointerConversion has already returned
2850 /// true. It returns true and produces a diagnostic if there was an
2851 /// error, or returns false otherwise.
2852 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2853                                   CastKind &Kind,
2854                                   CXXCastPath& BasePath,
2855                                   bool IgnoreBaseAccess,
2856                                   bool Diagnose) {
2857   QualType FromType = From->getType();
2858   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2859 
2860   Kind = CK_BitCast;
2861 
2862   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2863       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2864           Expr::NPCK_ZeroExpression) {
2865     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2866       DiagRuntimeBehavior(From->getExprLoc(), From,
2867                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2868                             << ToType << From->getSourceRange());
2869     else if (!isUnevaluatedContext())
2870       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2871         << ToType << From->getSourceRange();
2872   }
2873   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2874     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2875       QualType FromPointeeType = FromPtrType->getPointeeType(),
2876                ToPointeeType   = ToPtrType->getPointeeType();
2877 
2878       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2879           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2880         // We must have a derived-to-base conversion. Check an
2881         // ambiguous or inaccessible conversion.
2882         unsigned InaccessibleID = 0;
2883         unsigned AmbigiousID = 0;
2884         if (Diagnose) {
2885           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2886           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2887         }
2888         if (CheckDerivedToBaseConversion(
2889                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2890                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2891                 &BasePath, IgnoreBaseAccess))
2892           return true;
2893 
2894         // The conversion was successful.
2895         Kind = CK_DerivedToBase;
2896       }
2897 
2898       if (Diagnose && !IsCStyleOrFunctionalCast &&
2899           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2900         assert(getLangOpts().MSVCCompat &&
2901                "this should only be possible with MSVCCompat!");
2902         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2903             << From->getSourceRange();
2904       }
2905     }
2906   } else if (const ObjCObjectPointerType *ToPtrType =
2907                ToType->getAs<ObjCObjectPointerType>()) {
2908     if (const ObjCObjectPointerType *FromPtrType =
2909           FromType->getAs<ObjCObjectPointerType>()) {
2910       // Objective-C++ conversions are always okay.
2911       // FIXME: We should have a different class of conversions for the
2912       // Objective-C++ implicit conversions.
2913       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2914         return false;
2915     } else if (FromType->isBlockPointerType()) {
2916       Kind = CK_BlockPointerToObjCPointerCast;
2917     } else {
2918       Kind = CK_CPointerToObjCPointerCast;
2919     }
2920   } else if (ToType->isBlockPointerType()) {
2921     if (!FromType->isBlockPointerType())
2922       Kind = CK_AnyPointerToBlockPointerCast;
2923   }
2924 
2925   // We shouldn't fall into this case unless it's valid for other
2926   // reasons.
2927   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2928     Kind = CK_NullToPointer;
2929 
2930   return false;
2931 }
2932 
2933 /// IsMemberPointerConversion - Determines whether the conversion of the
2934 /// expression From, which has the (possibly adjusted) type FromType, can be
2935 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2936 /// If so, returns true and places the converted type (that might differ from
2937 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2938 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2939                                      QualType ToType,
2940                                      bool InOverloadResolution,
2941                                      QualType &ConvertedType) {
2942   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2943   if (!ToTypePtr)
2944     return false;
2945 
2946   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2947   if (From->isNullPointerConstant(Context,
2948                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2949                                         : Expr::NPC_ValueDependentIsNull)) {
2950     ConvertedType = ToType;
2951     return true;
2952   }
2953 
2954   // Otherwise, both types have to be member pointers.
2955   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2956   if (!FromTypePtr)
2957     return false;
2958 
2959   // A pointer to member of B can be converted to a pointer to member of D,
2960   // where D is derived from B (C++ 4.11p2).
2961   QualType FromClass(FromTypePtr->getClass(), 0);
2962   QualType ToClass(ToTypePtr->getClass(), 0);
2963 
2964   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2965       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2966     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2967                                                  ToClass.getTypePtr());
2968     return true;
2969   }
2970 
2971   return false;
2972 }
2973 
2974 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2975 /// expression From to the type ToType. This routine checks for ambiguous or
2976 /// virtual or inaccessible base-to-derived member pointer conversions
2977 /// for which IsMemberPointerConversion has already returned true. It returns
2978 /// true and produces a diagnostic if there was an error, or returns false
2979 /// otherwise.
2980 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2981                                         CastKind &Kind,
2982                                         CXXCastPath &BasePath,
2983                                         bool IgnoreBaseAccess) {
2984   QualType FromType = From->getType();
2985   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2986   if (!FromPtrType) {
2987     // This must be a null pointer to member pointer conversion
2988     assert(From->isNullPointerConstant(Context,
2989                                        Expr::NPC_ValueDependentIsNull) &&
2990            "Expr must be null pointer constant!");
2991     Kind = CK_NullToMemberPointer;
2992     return false;
2993   }
2994 
2995   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2996   assert(ToPtrType && "No member pointer cast has a target type "
2997                       "that is not a member pointer.");
2998 
2999   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3000   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3001 
3002   // FIXME: What about dependent types?
3003   assert(FromClass->isRecordType() && "Pointer into non-class.");
3004   assert(ToClass->isRecordType() && "Pointer into non-class.");
3005 
3006   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3007                      /*DetectVirtual=*/true);
3008   bool DerivationOkay =
3009       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3010   assert(DerivationOkay &&
3011          "Should not have been called if derivation isn't OK.");
3012   (void)DerivationOkay;
3013 
3014   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3015                                   getUnqualifiedType())) {
3016     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3017     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3018       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3019     return true;
3020   }
3021 
3022   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3023     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3024       << FromClass << ToClass << QualType(VBase, 0)
3025       << From->getSourceRange();
3026     return true;
3027   }
3028 
3029   if (!IgnoreBaseAccess)
3030     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3031                          Paths.front(),
3032                          diag::err_downcast_from_inaccessible_base);
3033 
3034   // Must be a base to derived member conversion.
3035   BuildBasePathArray(Paths, BasePath);
3036   Kind = CK_BaseToDerivedMemberPointer;
3037   return false;
3038 }
3039 
3040 /// Determine whether the lifetime conversion between the two given
3041 /// qualifiers sets is nontrivial.
3042 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3043                                                Qualifiers ToQuals) {
3044   // Converting anything to const __unsafe_unretained is trivial.
3045   if (ToQuals.hasConst() &&
3046       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3047     return false;
3048 
3049   return true;
3050 }
3051 
3052 /// IsQualificationConversion - Determines whether the conversion from
3053 /// an rvalue of type FromType to ToType is a qualification conversion
3054 /// (C++ 4.4).
3055 ///
3056 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3057 /// when the qualification conversion involves a change in the Objective-C
3058 /// object lifetime.
3059 bool
3060 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3061                                 bool CStyle, bool &ObjCLifetimeConversion) {
3062   FromType = Context.getCanonicalType(FromType);
3063   ToType = Context.getCanonicalType(ToType);
3064   ObjCLifetimeConversion = false;
3065 
3066   // If FromType and ToType are the same type, this is not a
3067   // qualification conversion.
3068   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3069     return false;
3070 
3071   // (C++ 4.4p4):
3072   //   A conversion can add cv-qualifiers at levels other than the first
3073   //   in multi-level pointers, subject to the following rules: [...]
3074   bool PreviousToQualsIncludeConst = true;
3075   bool UnwrappedAnyPointer = false;
3076   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3077     // Within each iteration of the loop, we check the qualifiers to
3078     // determine if this still looks like a qualification
3079     // conversion. Then, if all is well, we unwrap one more level of
3080     // pointers or pointers-to-members and do it all again
3081     // until there are no more pointers or pointers-to-members left to
3082     // unwrap.
3083     UnwrappedAnyPointer = true;
3084 
3085     Qualifiers FromQuals = FromType.getQualifiers();
3086     Qualifiers ToQuals = ToType.getQualifiers();
3087 
3088     // Ignore __unaligned qualifier if this type is void.
3089     if (ToType.getUnqualifiedType()->isVoidType())
3090       FromQuals.removeUnaligned();
3091 
3092     // Objective-C ARC:
3093     //   Check Objective-C lifetime conversions.
3094     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3095         UnwrappedAnyPointer) {
3096       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3097         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3098           ObjCLifetimeConversion = true;
3099         FromQuals.removeObjCLifetime();
3100         ToQuals.removeObjCLifetime();
3101       } else {
3102         // Qualification conversions cannot cast between different
3103         // Objective-C lifetime qualifiers.
3104         return false;
3105       }
3106     }
3107 
3108     // Allow addition/removal of GC attributes but not changing GC attributes.
3109     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3110         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3111       FromQuals.removeObjCGCAttr();
3112       ToQuals.removeObjCGCAttr();
3113     }
3114 
3115     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3116     //      2,j, and similarly for volatile.
3117     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3118       return false;
3119 
3120     //   -- if the cv 1,j and cv 2,j are different, then const is in
3121     //      every cv for 0 < k < j.
3122     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3123         && !PreviousToQualsIncludeConst)
3124       return false;
3125 
3126     // Keep track of whether all prior cv-qualifiers in the "to" type
3127     // include const.
3128     PreviousToQualsIncludeConst
3129       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3130   }
3131 
3132   // We are left with FromType and ToType being the pointee types
3133   // after unwrapping the original FromType and ToType the same number
3134   // of types. If we unwrapped any pointers, and if FromType and
3135   // ToType have the same unqualified type (since we checked
3136   // qualifiers above), then this is a qualification conversion.
3137   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3138 }
3139 
3140 /// - Determine whether this is a conversion from a scalar type to an
3141 /// atomic type.
3142 ///
3143 /// If successful, updates \c SCS's second and third steps in the conversion
3144 /// sequence to finish the conversion.
3145 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3146                                 bool InOverloadResolution,
3147                                 StandardConversionSequence &SCS,
3148                                 bool CStyle) {
3149   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3150   if (!ToAtomic)
3151     return false;
3152 
3153   StandardConversionSequence InnerSCS;
3154   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3155                             InOverloadResolution, InnerSCS,
3156                             CStyle, /*AllowObjCWritebackConversion=*/false))
3157     return false;
3158 
3159   SCS.Second = InnerSCS.Second;
3160   SCS.setToType(1, InnerSCS.getToType(1));
3161   SCS.Third = InnerSCS.Third;
3162   SCS.QualificationIncludesObjCLifetime
3163     = InnerSCS.QualificationIncludesObjCLifetime;
3164   SCS.setToType(2, InnerSCS.getToType(2));
3165   return true;
3166 }
3167 
3168 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3169                                               CXXConstructorDecl *Constructor,
3170                                               QualType Type) {
3171   const FunctionProtoType *CtorType =
3172       Constructor->getType()->getAs<FunctionProtoType>();
3173   if (CtorType->getNumParams() > 0) {
3174     QualType FirstArg = CtorType->getParamType(0);
3175     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3176       return true;
3177   }
3178   return false;
3179 }
3180 
3181 static OverloadingResult
3182 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3183                                        CXXRecordDecl *To,
3184                                        UserDefinedConversionSequence &User,
3185                                        OverloadCandidateSet &CandidateSet,
3186                                        bool AllowExplicit) {
3187   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3188   for (auto *D : S.LookupConstructors(To)) {
3189     auto Info = getConstructorInfo(D);
3190     if (!Info)
3191       continue;
3192 
3193     bool Usable = !Info.Constructor->isInvalidDecl() &&
3194                   S.isInitListConstructor(Info.Constructor) &&
3195                   (AllowExplicit || !Info.Constructor->isExplicit());
3196     if (Usable) {
3197       // If the first argument is (a reference to) the target type,
3198       // suppress conversions.
3199       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3200           S.Context, Info.Constructor, ToType);
3201       if (Info.ConstructorTmpl)
3202         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3203                                        /*ExplicitArgs*/ nullptr, From,
3204                                        CandidateSet, SuppressUserConversions);
3205       else
3206         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3207                                CandidateSet, SuppressUserConversions);
3208     }
3209   }
3210 
3211   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3212 
3213   OverloadCandidateSet::iterator Best;
3214   switch (auto Result =
3215             CandidateSet.BestViableFunction(S, From->getLocStart(),
3216                                             Best)) {
3217   case OR_Deleted:
3218   case OR_Success: {
3219     // Record the standard conversion we used and the conversion function.
3220     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3221     QualType ThisType = Constructor->getThisType(S.Context);
3222     // Initializer lists don't have conversions as such.
3223     User.Before.setAsIdentityConversion();
3224     User.HadMultipleCandidates = HadMultipleCandidates;
3225     User.ConversionFunction = Constructor;
3226     User.FoundConversionFunction = Best->FoundDecl;
3227     User.After.setAsIdentityConversion();
3228     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3229     User.After.setAllToTypes(ToType);
3230     return Result;
3231   }
3232 
3233   case OR_No_Viable_Function:
3234     return OR_No_Viable_Function;
3235   case OR_Ambiguous:
3236     return OR_Ambiguous;
3237   }
3238 
3239   llvm_unreachable("Invalid OverloadResult!");
3240 }
3241 
3242 /// Determines whether there is a user-defined conversion sequence
3243 /// (C++ [over.ics.user]) that converts expression From to the type
3244 /// ToType. If such a conversion exists, User will contain the
3245 /// user-defined conversion sequence that performs such a conversion
3246 /// and this routine will return true. Otherwise, this routine returns
3247 /// false and User is unspecified.
3248 ///
3249 /// \param AllowExplicit  true if the conversion should consider C++0x
3250 /// "explicit" conversion functions as well as non-explicit conversion
3251 /// functions (C++0x [class.conv.fct]p2).
3252 ///
3253 /// \param AllowObjCConversionOnExplicit true if the conversion should
3254 /// allow an extra Objective-C pointer conversion on uses of explicit
3255 /// constructors. Requires \c AllowExplicit to also be set.
3256 static OverloadingResult
3257 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3258                         UserDefinedConversionSequence &User,
3259                         OverloadCandidateSet &CandidateSet,
3260                         bool AllowExplicit,
3261                         bool AllowObjCConversionOnExplicit) {
3262   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3263   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3264 
3265   // Whether we will only visit constructors.
3266   bool ConstructorsOnly = false;
3267 
3268   // If the type we are conversion to is a class type, enumerate its
3269   // constructors.
3270   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3271     // C++ [over.match.ctor]p1:
3272     //   When objects of class type are direct-initialized (8.5), or
3273     //   copy-initialized from an expression of the same or a
3274     //   derived class type (8.5), overload resolution selects the
3275     //   constructor. [...] For copy-initialization, the candidate
3276     //   functions are all the converting constructors (12.3.1) of
3277     //   that class. The argument list is the expression-list within
3278     //   the parentheses of the initializer.
3279     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3280         (From->getType()->getAs<RecordType>() &&
3281          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3282       ConstructorsOnly = true;
3283 
3284     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3285       // We're not going to find any constructors.
3286     } else if (CXXRecordDecl *ToRecordDecl
3287                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3288 
3289       Expr **Args = &From;
3290       unsigned NumArgs = 1;
3291       bool ListInitializing = false;
3292       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3293         // But first, see if there is an init-list-constructor that will work.
3294         OverloadingResult Result = IsInitializerListConstructorConversion(
3295             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3296         if (Result != OR_No_Viable_Function)
3297           return Result;
3298         // Never mind.
3299         CandidateSet.clear(
3300             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3301 
3302         // If we're list-initializing, we pass the individual elements as
3303         // arguments, not the entire list.
3304         Args = InitList->getInits();
3305         NumArgs = InitList->getNumInits();
3306         ListInitializing = true;
3307       }
3308 
3309       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3310         auto Info = getConstructorInfo(D);
3311         if (!Info)
3312           continue;
3313 
3314         bool Usable = !Info.Constructor->isInvalidDecl();
3315         if (ListInitializing)
3316           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3317         else
3318           Usable = Usable &&
3319                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3320         if (Usable) {
3321           bool SuppressUserConversions = !ConstructorsOnly;
3322           if (SuppressUserConversions && ListInitializing) {
3323             SuppressUserConversions = false;
3324             if (NumArgs == 1) {
3325               // If the first argument is (a reference to) the target type,
3326               // suppress conversions.
3327               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3328                   S.Context, Info.Constructor, ToType);
3329             }
3330           }
3331           if (Info.ConstructorTmpl)
3332             S.AddTemplateOverloadCandidate(
3333                 Info.ConstructorTmpl, Info.FoundDecl,
3334                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3335                 CandidateSet, SuppressUserConversions);
3336           else
3337             // Allow one user-defined conversion when user specifies a
3338             // From->ToType conversion via an static cast (c-style, etc).
3339             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3340                                    llvm::makeArrayRef(Args, NumArgs),
3341                                    CandidateSet, SuppressUserConversions);
3342         }
3343       }
3344     }
3345   }
3346 
3347   // Enumerate conversion functions, if we're allowed to.
3348   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3349   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3350     // No conversion functions from incomplete types.
3351   } else if (const RecordType *FromRecordType
3352                                    = From->getType()->getAs<RecordType>()) {
3353     if (CXXRecordDecl *FromRecordDecl
3354          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3355       // Add all of the conversion functions as candidates.
3356       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3357       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3358         DeclAccessPair FoundDecl = I.getPair();
3359         NamedDecl *D = FoundDecl.getDecl();
3360         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3361         if (isa<UsingShadowDecl>(D))
3362           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3363 
3364         CXXConversionDecl *Conv;
3365         FunctionTemplateDecl *ConvTemplate;
3366         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3367           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3368         else
3369           Conv = cast<CXXConversionDecl>(D);
3370 
3371         if (AllowExplicit || !Conv->isExplicit()) {
3372           if (ConvTemplate)
3373             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3374                                              ActingContext, From, ToType,
3375                                              CandidateSet,
3376                                              AllowObjCConversionOnExplicit);
3377           else
3378             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3379                                      From, ToType, CandidateSet,
3380                                      AllowObjCConversionOnExplicit);
3381         }
3382       }
3383     }
3384   }
3385 
3386   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3387 
3388   OverloadCandidateSet::iterator Best;
3389   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3390                                                         Best)) {
3391   case OR_Success:
3392   case OR_Deleted:
3393     // Record the standard conversion we used and the conversion function.
3394     if (CXXConstructorDecl *Constructor
3395           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3396       // C++ [over.ics.user]p1:
3397       //   If the user-defined conversion is specified by a
3398       //   constructor (12.3.1), the initial standard conversion
3399       //   sequence converts the source type to the type required by
3400       //   the argument of the constructor.
3401       //
3402       QualType ThisType = Constructor->getThisType(S.Context);
3403       if (isa<InitListExpr>(From)) {
3404         // Initializer lists don't have conversions as such.
3405         User.Before.setAsIdentityConversion();
3406       } else {
3407         if (Best->Conversions[0].isEllipsis())
3408           User.EllipsisConversion = true;
3409         else {
3410           User.Before = Best->Conversions[0].Standard;
3411           User.EllipsisConversion = false;
3412         }
3413       }
3414       User.HadMultipleCandidates = HadMultipleCandidates;
3415       User.ConversionFunction = Constructor;
3416       User.FoundConversionFunction = Best->FoundDecl;
3417       User.After.setAsIdentityConversion();
3418       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3419       User.After.setAllToTypes(ToType);
3420       return Result;
3421     }
3422     if (CXXConversionDecl *Conversion
3423                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3424       // C++ [over.ics.user]p1:
3425       //
3426       //   [...] If the user-defined conversion is specified by a
3427       //   conversion function (12.3.2), the initial standard
3428       //   conversion sequence converts the source type to the
3429       //   implicit object parameter of the conversion function.
3430       User.Before = Best->Conversions[0].Standard;
3431       User.HadMultipleCandidates = HadMultipleCandidates;
3432       User.ConversionFunction = Conversion;
3433       User.FoundConversionFunction = Best->FoundDecl;
3434       User.EllipsisConversion = false;
3435 
3436       // C++ [over.ics.user]p2:
3437       //   The second standard conversion sequence converts the
3438       //   result of the user-defined conversion to the target type
3439       //   for the sequence. Since an implicit conversion sequence
3440       //   is an initialization, the special rules for
3441       //   initialization by user-defined conversion apply when
3442       //   selecting the best user-defined conversion for a
3443       //   user-defined conversion sequence (see 13.3.3 and
3444       //   13.3.3.1).
3445       User.After = Best->FinalConversion;
3446       return Result;
3447     }
3448     llvm_unreachable("Not a constructor or conversion function?");
3449 
3450   case OR_No_Viable_Function:
3451     return OR_No_Viable_Function;
3452 
3453   case OR_Ambiguous:
3454     return OR_Ambiguous;
3455   }
3456 
3457   llvm_unreachable("Invalid OverloadResult!");
3458 }
3459 
3460 bool
3461 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3462   ImplicitConversionSequence ICS;
3463   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3464                                     OverloadCandidateSet::CSK_Normal);
3465   OverloadingResult OvResult =
3466     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3467                             CandidateSet, false, false);
3468   if (OvResult == OR_Ambiguous)
3469     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3470         << From->getType() << ToType << From->getSourceRange();
3471   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3472     if (!RequireCompleteType(From->getLocStart(), ToType,
3473                              diag::err_typecheck_nonviable_condition_incomplete,
3474                              From->getType(), From->getSourceRange()))
3475       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3476           << false << From->getType() << From->getSourceRange() << ToType;
3477   } else
3478     return false;
3479   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3480   return true;
3481 }
3482 
3483 /// Compare the user-defined conversion functions or constructors
3484 /// of two user-defined conversion sequences to determine whether any ordering
3485 /// is possible.
3486 static ImplicitConversionSequence::CompareKind
3487 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3488                            FunctionDecl *Function2) {
3489   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3490     return ImplicitConversionSequence::Indistinguishable;
3491 
3492   // Objective-C++:
3493   //   If both conversion functions are implicitly-declared conversions from
3494   //   a lambda closure type to a function pointer and a block pointer,
3495   //   respectively, always prefer the conversion to a function pointer,
3496   //   because the function pointer is more lightweight and is more likely
3497   //   to keep code working.
3498   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3499   if (!Conv1)
3500     return ImplicitConversionSequence::Indistinguishable;
3501 
3502   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3503   if (!Conv2)
3504     return ImplicitConversionSequence::Indistinguishable;
3505 
3506   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3507     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3508     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3509     if (Block1 != Block2)
3510       return Block1 ? ImplicitConversionSequence::Worse
3511                     : ImplicitConversionSequence::Better;
3512   }
3513 
3514   return ImplicitConversionSequence::Indistinguishable;
3515 }
3516 
3517 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3518     const ImplicitConversionSequence &ICS) {
3519   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3520          (ICS.isUserDefined() &&
3521           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3522 }
3523 
3524 /// CompareImplicitConversionSequences - Compare two implicit
3525 /// conversion sequences to determine whether one is better than the
3526 /// other or if they are indistinguishable (C++ 13.3.3.2).
3527 static ImplicitConversionSequence::CompareKind
3528 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3529                                    const ImplicitConversionSequence& ICS1,
3530                                    const ImplicitConversionSequence& ICS2)
3531 {
3532   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3533   // conversion sequences (as defined in 13.3.3.1)
3534   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3535   //      conversion sequence than a user-defined conversion sequence or
3536   //      an ellipsis conversion sequence, and
3537   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3538   //      conversion sequence than an ellipsis conversion sequence
3539   //      (13.3.3.1.3).
3540   //
3541   // C++0x [over.best.ics]p10:
3542   //   For the purpose of ranking implicit conversion sequences as
3543   //   described in 13.3.3.2, the ambiguous conversion sequence is
3544   //   treated as a user-defined sequence that is indistinguishable
3545   //   from any other user-defined conversion sequence.
3546 
3547   // String literal to 'char *' conversion has been deprecated in C++03. It has
3548   // been removed from C++11. We still accept this conversion, if it happens at
3549   // the best viable function. Otherwise, this conversion is considered worse
3550   // than ellipsis conversion. Consider this as an extension; this is not in the
3551   // standard. For example:
3552   //
3553   // int &f(...);    // #1
3554   // void f(char*);  // #2
3555   // void g() { int &r = f("foo"); }
3556   //
3557   // In C++03, we pick #2 as the best viable function.
3558   // In C++11, we pick #1 as the best viable function, because ellipsis
3559   // conversion is better than string-literal to char* conversion (since there
3560   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3561   // convert arguments, #2 would be the best viable function in C++11.
3562   // If the best viable function has this conversion, a warning will be issued
3563   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3564 
3565   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3566       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3567       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3568     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3569                ? ImplicitConversionSequence::Worse
3570                : ImplicitConversionSequence::Better;
3571 
3572   if (ICS1.getKindRank() < ICS2.getKindRank())
3573     return ImplicitConversionSequence::Better;
3574   if (ICS2.getKindRank() < ICS1.getKindRank())
3575     return ImplicitConversionSequence::Worse;
3576 
3577   // The following checks require both conversion sequences to be of
3578   // the same kind.
3579   if (ICS1.getKind() != ICS2.getKind())
3580     return ImplicitConversionSequence::Indistinguishable;
3581 
3582   ImplicitConversionSequence::CompareKind Result =
3583       ImplicitConversionSequence::Indistinguishable;
3584 
3585   // Two implicit conversion sequences of the same form are
3586   // indistinguishable conversion sequences unless one of the
3587   // following rules apply: (C++ 13.3.3.2p3):
3588 
3589   // List-initialization sequence L1 is a better conversion sequence than
3590   // list-initialization sequence L2 if:
3591   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3592   //   if not that,
3593   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3594   //   and N1 is smaller than N2.,
3595   // even if one of the other rules in this paragraph would otherwise apply.
3596   if (!ICS1.isBad()) {
3597     if (ICS1.isStdInitializerListElement() &&
3598         !ICS2.isStdInitializerListElement())
3599       return ImplicitConversionSequence::Better;
3600     if (!ICS1.isStdInitializerListElement() &&
3601         ICS2.isStdInitializerListElement())
3602       return ImplicitConversionSequence::Worse;
3603   }
3604 
3605   if (ICS1.isStandard())
3606     // Standard conversion sequence S1 is a better conversion sequence than
3607     // standard conversion sequence S2 if [...]
3608     Result = CompareStandardConversionSequences(S, Loc,
3609                                                 ICS1.Standard, ICS2.Standard);
3610   else if (ICS1.isUserDefined()) {
3611     // User-defined conversion sequence U1 is a better conversion
3612     // sequence than another user-defined conversion sequence U2 if
3613     // they contain the same user-defined conversion function or
3614     // constructor and if the second standard conversion sequence of
3615     // U1 is better than the second standard conversion sequence of
3616     // U2 (C++ 13.3.3.2p3).
3617     if (ICS1.UserDefined.ConversionFunction ==
3618           ICS2.UserDefined.ConversionFunction)
3619       Result = CompareStandardConversionSequences(S, Loc,
3620                                                   ICS1.UserDefined.After,
3621                                                   ICS2.UserDefined.After);
3622     else
3623       Result = compareConversionFunctions(S,
3624                                           ICS1.UserDefined.ConversionFunction,
3625                                           ICS2.UserDefined.ConversionFunction);
3626   }
3627 
3628   return Result;
3629 }
3630 
3631 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3632   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3633     Qualifiers Quals;
3634     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3635     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3636   }
3637 
3638   return Context.hasSameUnqualifiedType(T1, T2);
3639 }
3640 
3641 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3642 // determine if one is a proper subset of the other.
3643 static ImplicitConversionSequence::CompareKind
3644 compareStandardConversionSubsets(ASTContext &Context,
3645                                  const StandardConversionSequence& SCS1,
3646                                  const StandardConversionSequence& SCS2) {
3647   ImplicitConversionSequence::CompareKind Result
3648     = ImplicitConversionSequence::Indistinguishable;
3649 
3650   // the identity conversion sequence is considered to be a subsequence of
3651   // any non-identity conversion sequence
3652   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3653     return ImplicitConversionSequence::Better;
3654   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3655     return ImplicitConversionSequence::Worse;
3656 
3657   if (SCS1.Second != SCS2.Second) {
3658     if (SCS1.Second == ICK_Identity)
3659       Result = ImplicitConversionSequence::Better;
3660     else if (SCS2.Second == ICK_Identity)
3661       Result = ImplicitConversionSequence::Worse;
3662     else
3663       return ImplicitConversionSequence::Indistinguishable;
3664   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3665     return ImplicitConversionSequence::Indistinguishable;
3666 
3667   if (SCS1.Third == SCS2.Third) {
3668     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3669                              : ImplicitConversionSequence::Indistinguishable;
3670   }
3671 
3672   if (SCS1.Third == ICK_Identity)
3673     return Result == ImplicitConversionSequence::Worse
3674              ? ImplicitConversionSequence::Indistinguishable
3675              : ImplicitConversionSequence::Better;
3676 
3677   if (SCS2.Third == ICK_Identity)
3678     return Result == ImplicitConversionSequence::Better
3679              ? ImplicitConversionSequence::Indistinguishable
3680              : ImplicitConversionSequence::Worse;
3681 
3682   return ImplicitConversionSequence::Indistinguishable;
3683 }
3684 
3685 /// Determine whether one of the given reference bindings is better
3686 /// than the other based on what kind of bindings they are.
3687 static bool
3688 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3689                              const StandardConversionSequence &SCS2) {
3690   // C++0x [over.ics.rank]p3b4:
3691   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3692   //      implicit object parameter of a non-static member function declared
3693   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3694   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3695   //      lvalue reference to a function lvalue and S2 binds an rvalue
3696   //      reference*.
3697   //
3698   // FIXME: Rvalue references. We're going rogue with the above edits,
3699   // because the semantics in the current C++0x working paper (N3225 at the
3700   // time of this writing) break the standard definition of std::forward
3701   // and std::reference_wrapper when dealing with references to functions.
3702   // Proposed wording changes submitted to CWG for consideration.
3703   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3704       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3705     return false;
3706 
3707   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3708           SCS2.IsLvalueReference) ||
3709          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3710           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3711 }
3712 
3713 /// CompareStandardConversionSequences - Compare two standard
3714 /// conversion sequences to determine whether one is better than the
3715 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3716 static ImplicitConversionSequence::CompareKind
3717 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3718                                    const StandardConversionSequence& SCS1,
3719                                    const StandardConversionSequence& SCS2)
3720 {
3721   // Standard conversion sequence S1 is a better conversion sequence
3722   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3723 
3724   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3725   //     sequences in the canonical form defined by 13.3.3.1.1,
3726   //     excluding any Lvalue Transformation; the identity conversion
3727   //     sequence is considered to be a subsequence of any
3728   //     non-identity conversion sequence) or, if not that,
3729   if (ImplicitConversionSequence::CompareKind CK
3730         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3731     return CK;
3732 
3733   //  -- the rank of S1 is better than the rank of S2 (by the rules
3734   //     defined below), or, if not that,
3735   ImplicitConversionRank Rank1 = SCS1.getRank();
3736   ImplicitConversionRank Rank2 = SCS2.getRank();
3737   if (Rank1 < Rank2)
3738     return ImplicitConversionSequence::Better;
3739   else if (Rank2 < Rank1)
3740     return ImplicitConversionSequence::Worse;
3741 
3742   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3743   // are indistinguishable unless one of the following rules
3744   // applies:
3745 
3746   //   A conversion that is not a conversion of a pointer, or
3747   //   pointer to member, to bool is better than another conversion
3748   //   that is such a conversion.
3749   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3750     return SCS2.isPointerConversionToBool()
3751              ? ImplicitConversionSequence::Better
3752              : ImplicitConversionSequence::Worse;
3753 
3754   // C++ [over.ics.rank]p4b2:
3755   //
3756   //   If class B is derived directly or indirectly from class A,
3757   //   conversion of B* to A* is better than conversion of B* to
3758   //   void*, and conversion of A* to void* is better than conversion
3759   //   of B* to void*.
3760   bool SCS1ConvertsToVoid
3761     = SCS1.isPointerConversionToVoidPointer(S.Context);
3762   bool SCS2ConvertsToVoid
3763     = SCS2.isPointerConversionToVoidPointer(S.Context);
3764   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3765     // Exactly one of the conversion sequences is a conversion to
3766     // a void pointer; it's the worse conversion.
3767     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3768                               : ImplicitConversionSequence::Worse;
3769   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3770     // Neither conversion sequence converts to a void pointer; compare
3771     // their derived-to-base conversions.
3772     if (ImplicitConversionSequence::CompareKind DerivedCK
3773           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3774       return DerivedCK;
3775   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3776              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3777     // Both conversion sequences are conversions to void
3778     // pointers. Compare the source types to determine if there's an
3779     // inheritance relationship in their sources.
3780     QualType FromType1 = SCS1.getFromType();
3781     QualType FromType2 = SCS2.getFromType();
3782 
3783     // Adjust the types we're converting from via the array-to-pointer
3784     // conversion, if we need to.
3785     if (SCS1.First == ICK_Array_To_Pointer)
3786       FromType1 = S.Context.getArrayDecayedType(FromType1);
3787     if (SCS2.First == ICK_Array_To_Pointer)
3788       FromType2 = S.Context.getArrayDecayedType(FromType2);
3789 
3790     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3791     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3792 
3793     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3794       return ImplicitConversionSequence::Better;
3795     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3796       return ImplicitConversionSequence::Worse;
3797 
3798     // Objective-C++: If one interface is more specific than the
3799     // other, it is the better one.
3800     const ObjCObjectPointerType* FromObjCPtr1
3801       = FromType1->getAs<ObjCObjectPointerType>();
3802     const ObjCObjectPointerType* FromObjCPtr2
3803       = FromType2->getAs<ObjCObjectPointerType>();
3804     if (FromObjCPtr1 && FromObjCPtr2) {
3805       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3806                                                           FromObjCPtr2);
3807       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3808                                                            FromObjCPtr1);
3809       if (AssignLeft != AssignRight) {
3810         return AssignLeft? ImplicitConversionSequence::Better
3811                          : ImplicitConversionSequence::Worse;
3812       }
3813     }
3814   }
3815 
3816   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3817   // bullet 3).
3818   if (ImplicitConversionSequence::CompareKind QualCK
3819         = CompareQualificationConversions(S, SCS1, SCS2))
3820     return QualCK;
3821 
3822   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3823     // Check for a better reference binding based on the kind of bindings.
3824     if (isBetterReferenceBindingKind(SCS1, SCS2))
3825       return ImplicitConversionSequence::Better;
3826     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3827       return ImplicitConversionSequence::Worse;
3828 
3829     // C++ [over.ics.rank]p3b4:
3830     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3831     //      which the references refer are the same type except for
3832     //      top-level cv-qualifiers, and the type to which the reference
3833     //      initialized by S2 refers is more cv-qualified than the type
3834     //      to which the reference initialized by S1 refers.
3835     QualType T1 = SCS1.getToType(2);
3836     QualType T2 = SCS2.getToType(2);
3837     T1 = S.Context.getCanonicalType(T1);
3838     T2 = S.Context.getCanonicalType(T2);
3839     Qualifiers T1Quals, T2Quals;
3840     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3841     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3842     if (UnqualT1 == UnqualT2) {
3843       // Objective-C++ ARC: If the references refer to objects with different
3844       // lifetimes, prefer bindings that don't change lifetime.
3845       if (SCS1.ObjCLifetimeConversionBinding !=
3846                                           SCS2.ObjCLifetimeConversionBinding) {
3847         return SCS1.ObjCLifetimeConversionBinding
3848                                            ? ImplicitConversionSequence::Worse
3849                                            : ImplicitConversionSequence::Better;
3850       }
3851 
3852       // If the type is an array type, promote the element qualifiers to the
3853       // type for comparison.
3854       if (isa<ArrayType>(T1) && T1Quals)
3855         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3856       if (isa<ArrayType>(T2) && T2Quals)
3857         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3858       if (T2.isMoreQualifiedThan(T1))
3859         return ImplicitConversionSequence::Better;
3860       else if (T1.isMoreQualifiedThan(T2))
3861         return ImplicitConversionSequence::Worse;
3862     }
3863   }
3864 
3865   // In Microsoft mode, prefer an integral conversion to a
3866   // floating-to-integral conversion if the integral conversion
3867   // is between types of the same size.
3868   // For example:
3869   // void f(float);
3870   // void f(int);
3871   // int main {
3872   //    long a;
3873   //    f(a);
3874   // }
3875   // Here, MSVC will call f(int) instead of generating a compile error
3876   // as clang will do in standard mode.
3877   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3878       SCS2.Second == ICK_Floating_Integral &&
3879       S.Context.getTypeSize(SCS1.getFromType()) ==
3880           S.Context.getTypeSize(SCS1.getToType(2)))
3881     return ImplicitConversionSequence::Better;
3882 
3883   return ImplicitConversionSequence::Indistinguishable;
3884 }
3885 
3886 /// CompareQualificationConversions - Compares two standard conversion
3887 /// sequences to determine whether they can be ranked based on their
3888 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3889 static ImplicitConversionSequence::CompareKind
3890 CompareQualificationConversions(Sema &S,
3891                                 const StandardConversionSequence& SCS1,
3892                                 const StandardConversionSequence& SCS2) {
3893   // C++ 13.3.3.2p3:
3894   //  -- S1 and S2 differ only in their qualification conversion and
3895   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3896   //     cv-qualification signature of type T1 is a proper subset of
3897   //     the cv-qualification signature of type T2, and S1 is not the
3898   //     deprecated string literal array-to-pointer conversion (4.2).
3899   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3900       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3901     return ImplicitConversionSequence::Indistinguishable;
3902 
3903   // FIXME: the example in the standard doesn't use a qualification
3904   // conversion (!)
3905   QualType T1 = SCS1.getToType(2);
3906   QualType T2 = SCS2.getToType(2);
3907   T1 = S.Context.getCanonicalType(T1);
3908   T2 = S.Context.getCanonicalType(T2);
3909   Qualifiers T1Quals, T2Quals;
3910   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3911   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3912 
3913   // If the types are the same, we won't learn anything by unwrapped
3914   // them.
3915   if (UnqualT1 == UnqualT2)
3916     return ImplicitConversionSequence::Indistinguishable;
3917 
3918   // If the type is an array type, promote the element qualifiers to the type
3919   // for comparison.
3920   if (isa<ArrayType>(T1) && T1Quals)
3921     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3922   if (isa<ArrayType>(T2) && T2Quals)
3923     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3924 
3925   ImplicitConversionSequence::CompareKind Result
3926     = ImplicitConversionSequence::Indistinguishable;
3927 
3928   // Objective-C++ ARC:
3929   //   Prefer qualification conversions not involving a change in lifetime
3930   //   to qualification conversions that do not change lifetime.
3931   if (SCS1.QualificationIncludesObjCLifetime !=
3932                                       SCS2.QualificationIncludesObjCLifetime) {
3933     Result = SCS1.QualificationIncludesObjCLifetime
3934                ? ImplicitConversionSequence::Worse
3935                : ImplicitConversionSequence::Better;
3936   }
3937 
3938   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3939     // Within each iteration of the loop, we check the qualifiers to
3940     // determine if this still looks like a qualification
3941     // conversion. Then, if all is well, we unwrap one more level of
3942     // pointers or pointers-to-members and do it all again
3943     // until there are no more pointers or pointers-to-members left
3944     // to unwrap. This essentially mimics what
3945     // IsQualificationConversion does, but here we're checking for a
3946     // strict subset of qualifiers.
3947     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3948       // The qualifiers are the same, so this doesn't tell us anything
3949       // about how the sequences rank.
3950       ;
3951     else if (T2.isMoreQualifiedThan(T1)) {
3952       // T1 has fewer qualifiers, so it could be the better sequence.
3953       if (Result == ImplicitConversionSequence::Worse)
3954         // Neither has qualifiers that are a subset of the other's
3955         // qualifiers.
3956         return ImplicitConversionSequence::Indistinguishable;
3957 
3958       Result = ImplicitConversionSequence::Better;
3959     } else if (T1.isMoreQualifiedThan(T2)) {
3960       // T2 has fewer qualifiers, so it could be the better sequence.
3961       if (Result == ImplicitConversionSequence::Better)
3962         // Neither has qualifiers that are a subset of the other's
3963         // qualifiers.
3964         return ImplicitConversionSequence::Indistinguishable;
3965 
3966       Result = ImplicitConversionSequence::Worse;
3967     } else {
3968       // Qualifiers are disjoint.
3969       return ImplicitConversionSequence::Indistinguishable;
3970     }
3971 
3972     // If the types after this point are equivalent, we're done.
3973     if (S.Context.hasSameUnqualifiedType(T1, T2))
3974       break;
3975   }
3976 
3977   // Check that the winning standard conversion sequence isn't using
3978   // the deprecated string literal array to pointer conversion.
3979   switch (Result) {
3980   case ImplicitConversionSequence::Better:
3981     if (SCS1.DeprecatedStringLiteralToCharPtr)
3982       Result = ImplicitConversionSequence::Indistinguishable;
3983     break;
3984 
3985   case ImplicitConversionSequence::Indistinguishable:
3986     break;
3987 
3988   case ImplicitConversionSequence::Worse:
3989     if (SCS2.DeprecatedStringLiteralToCharPtr)
3990       Result = ImplicitConversionSequence::Indistinguishable;
3991     break;
3992   }
3993 
3994   return Result;
3995 }
3996 
3997 /// CompareDerivedToBaseConversions - Compares two standard conversion
3998 /// sequences to determine whether they can be ranked based on their
3999 /// various kinds of derived-to-base conversions (C++
4000 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4001 /// conversions between Objective-C interface types.
4002 static ImplicitConversionSequence::CompareKind
4003 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4004                                 const StandardConversionSequence& SCS1,
4005                                 const StandardConversionSequence& SCS2) {
4006   QualType FromType1 = SCS1.getFromType();
4007   QualType ToType1 = SCS1.getToType(1);
4008   QualType FromType2 = SCS2.getFromType();
4009   QualType ToType2 = SCS2.getToType(1);
4010 
4011   // Adjust the types we're converting from via the array-to-pointer
4012   // conversion, if we need to.
4013   if (SCS1.First == ICK_Array_To_Pointer)
4014     FromType1 = S.Context.getArrayDecayedType(FromType1);
4015   if (SCS2.First == ICK_Array_To_Pointer)
4016     FromType2 = S.Context.getArrayDecayedType(FromType2);
4017 
4018   // Canonicalize all of the types.
4019   FromType1 = S.Context.getCanonicalType(FromType1);
4020   ToType1 = S.Context.getCanonicalType(ToType1);
4021   FromType2 = S.Context.getCanonicalType(FromType2);
4022   ToType2 = S.Context.getCanonicalType(ToType2);
4023 
4024   // C++ [over.ics.rank]p4b3:
4025   //
4026   //   If class B is derived directly or indirectly from class A and
4027   //   class C is derived directly or indirectly from B,
4028   //
4029   // Compare based on pointer conversions.
4030   if (SCS1.Second == ICK_Pointer_Conversion &&
4031       SCS2.Second == ICK_Pointer_Conversion &&
4032       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4033       FromType1->isPointerType() && FromType2->isPointerType() &&
4034       ToType1->isPointerType() && ToType2->isPointerType()) {
4035     QualType FromPointee1
4036       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4037     QualType ToPointee1
4038       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4039     QualType FromPointee2
4040       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4041     QualType ToPointee2
4042       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4043 
4044     //   -- conversion of C* to B* is better than conversion of C* to A*,
4045     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4046       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4047         return ImplicitConversionSequence::Better;
4048       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4049         return ImplicitConversionSequence::Worse;
4050     }
4051 
4052     //   -- conversion of B* to A* is better than conversion of C* to A*,
4053     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4054       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4055         return ImplicitConversionSequence::Better;
4056       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4057         return ImplicitConversionSequence::Worse;
4058     }
4059   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4060              SCS2.Second == ICK_Pointer_Conversion) {
4061     const ObjCObjectPointerType *FromPtr1
4062       = FromType1->getAs<ObjCObjectPointerType>();
4063     const ObjCObjectPointerType *FromPtr2
4064       = FromType2->getAs<ObjCObjectPointerType>();
4065     const ObjCObjectPointerType *ToPtr1
4066       = ToType1->getAs<ObjCObjectPointerType>();
4067     const ObjCObjectPointerType *ToPtr2
4068       = ToType2->getAs<ObjCObjectPointerType>();
4069 
4070     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4071       // Apply the same conversion ranking rules for Objective-C pointer types
4072       // that we do for C++ pointers to class types. However, we employ the
4073       // Objective-C pseudo-subtyping relationship used for assignment of
4074       // Objective-C pointer types.
4075       bool FromAssignLeft
4076         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4077       bool FromAssignRight
4078         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4079       bool ToAssignLeft
4080         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4081       bool ToAssignRight
4082         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4083 
4084       // A conversion to an a non-id object pointer type or qualified 'id'
4085       // type is better than a conversion to 'id'.
4086       if (ToPtr1->isObjCIdType() &&
4087           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4088         return ImplicitConversionSequence::Worse;
4089       if (ToPtr2->isObjCIdType() &&
4090           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4091         return ImplicitConversionSequence::Better;
4092 
4093       // A conversion to a non-id object pointer type is better than a
4094       // conversion to a qualified 'id' type
4095       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4096         return ImplicitConversionSequence::Worse;
4097       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4098         return ImplicitConversionSequence::Better;
4099 
4100       // A conversion to an a non-Class object pointer type or qualified 'Class'
4101       // type is better than a conversion to 'Class'.
4102       if (ToPtr1->isObjCClassType() &&
4103           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4104         return ImplicitConversionSequence::Worse;
4105       if (ToPtr2->isObjCClassType() &&
4106           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4107         return ImplicitConversionSequence::Better;
4108 
4109       // A conversion to a non-Class object pointer type is better than a
4110       // conversion to a qualified 'Class' type.
4111       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4112         return ImplicitConversionSequence::Worse;
4113       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4114         return ImplicitConversionSequence::Better;
4115 
4116       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4117       if (S.Context.hasSameType(FromType1, FromType2) &&
4118           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4119           (ToAssignLeft != ToAssignRight)) {
4120         if (FromPtr1->isSpecialized()) {
4121           // "conversion of B<A> * to B * is better than conversion of B * to
4122           // C *.
4123           bool IsFirstSame =
4124               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4125           bool IsSecondSame =
4126               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4127           if (IsFirstSame) {
4128             if (!IsSecondSame)
4129               return ImplicitConversionSequence::Better;
4130           } else if (IsSecondSame)
4131             return ImplicitConversionSequence::Worse;
4132         }
4133         return ToAssignLeft? ImplicitConversionSequence::Worse
4134                            : ImplicitConversionSequence::Better;
4135       }
4136 
4137       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4138       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4139           (FromAssignLeft != FromAssignRight))
4140         return FromAssignLeft? ImplicitConversionSequence::Better
4141         : ImplicitConversionSequence::Worse;
4142     }
4143   }
4144 
4145   // Ranking of member-pointer types.
4146   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4147       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4148       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4149     const MemberPointerType * FromMemPointer1 =
4150                                         FromType1->getAs<MemberPointerType>();
4151     const MemberPointerType * ToMemPointer1 =
4152                                           ToType1->getAs<MemberPointerType>();
4153     const MemberPointerType * FromMemPointer2 =
4154                                           FromType2->getAs<MemberPointerType>();
4155     const MemberPointerType * ToMemPointer2 =
4156                                           ToType2->getAs<MemberPointerType>();
4157     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4158     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4159     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4160     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4161     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4162     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4163     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4164     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4165     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4166     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4167       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4168         return ImplicitConversionSequence::Worse;
4169       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4170         return ImplicitConversionSequence::Better;
4171     }
4172     // conversion of B::* to C::* is better than conversion of A::* to C::*
4173     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4174       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4175         return ImplicitConversionSequence::Better;
4176       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4177         return ImplicitConversionSequence::Worse;
4178     }
4179   }
4180 
4181   if (SCS1.Second == ICK_Derived_To_Base) {
4182     //   -- conversion of C to B is better than conversion of C to A,
4183     //   -- binding of an expression of type C to a reference of type
4184     //      B& is better than binding an expression of type C to a
4185     //      reference of type A&,
4186     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4187         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4188       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4189         return ImplicitConversionSequence::Better;
4190       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4191         return ImplicitConversionSequence::Worse;
4192     }
4193 
4194     //   -- conversion of B to A is better than conversion of C to A.
4195     //   -- binding of an expression of type B to a reference of type
4196     //      A& is better than binding an expression of type C to a
4197     //      reference of type A&,
4198     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4199         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4200       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4201         return ImplicitConversionSequence::Better;
4202       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4203         return ImplicitConversionSequence::Worse;
4204     }
4205   }
4206 
4207   return ImplicitConversionSequence::Indistinguishable;
4208 }
4209 
4210 /// Determine whether the given type is valid, e.g., it is not an invalid
4211 /// C++ class.
4212 static bool isTypeValid(QualType T) {
4213   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4214     return !Record->isInvalidDecl();
4215 
4216   return true;
4217 }
4218 
4219 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4220 /// determine whether they are reference-related,
4221 /// reference-compatible, reference-compatible with added
4222 /// qualification, or incompatible, for use in C++ initialization by
4223 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4224 /// type, and the first type (T1) is the pointee type of the reference
4225 /// type being initialized.
4226 Sema::ReferenceCompareResult
4227 Sema::CompareReferenceRelationship(SourceLocation Loc,
4228                                    QualType OrigT1, QualType OrigT2,
4229                                    bool &DerivedToBase,
4230                                    bool &ObjCConversion,
4231                                    bool &ObjCLifetimeConversion) {
4232   assert(!OrigT1->isReferenceType() &&
4233     "T1 must be the pointee type of the reference type");
4234   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4235 
4236   QualType T1 = Context.getCanonicalType(OrigT1);
4237   QualType T2 = Context.getCanonicalType(OrigT2);
4238   Qualifiers T1Quals, T2Quals;
4239   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4240   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4241 
4242   // C++ [dcl.init.ref]p4:
4243   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4244   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4245   //   T1 is a base class of T2.
4246   DerivedToBase = false;
4247   ObjCConversion = false;
4248   ObjCLifetimeConversion = false;
4249   QualType ConvertedT2;
4250   if (UnqualT1 == UnqualT2) {
4251     // Nothing to do.
4252   } else if (isCompleteType(Loc, OrigT2) &&
4253              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4254              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4255     DerivedToBase = true;
4256   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4257            UnqualT2->isObjCObjectOrInterfaceType() &&
4258            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4259     ObjCConversion = true;
4260   else if (UnqualT2->isFunctionType() &&
4261            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4262     // C++1z [dcl.init.ref]p4:
4263     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4264     //   function" and T1 is "function"
4265     //
4266     // We extend this to also apply to 'noreturn', so allow any function
4267     // conversion between function types.
4268     return Ref_Compatible;
4269   else
4270     return Ref_Incompatible;
4271 
4272   // At this point, we know that T1 and T2 are reference-related (at
4273   // least).
4274 
4275   // If the type is an array type, promote the element qualifiers to the type
4276   // for comparison.
4277   if (isa<ArrayType>(T1) && T1Quals)
4278     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4279   if (isa<ArrayType>(T2) && T2Quals)
4280     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4281 
4282   // C++ [dcl.init.ref]p4:
4283   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4284   //   reference-related to T2 and cv1 is the same cv-qualification
4285   //   as, or greater cv-qualification than, cv2. For purposes of
4286   //   overload resolution, cases for which cv1 is greater
4287   //   cv-qualification than cv2 are identified as
4288   //   reference-compatible with added qualification (see 13.3.3.2).
4289   //
4290   // Note that we also require equivalence of Objective-C GC and address-space
4291   // qualifiers when performing these computations, so that e.g., an int in
4292   // address space 1 is not reference-compatible with an int in address
4293   // space 2.
4294   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4295       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4296     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4297       ObjCLifetimeConversion = true;
4298 
4299     T1Quals.removeObjCLifetime();
4300     T2Quals.removeObjCLifetime();
4301   }
4302 
4303   // MS compiler ignores __unaligned qualifier for references; do the same.
4304   T1Quals.removeUnaligned();
4305   T2Quals.removeUnaligned();
4306 
4307   if (T1Quals.compatiblyIncludes(T2Quals))
4308     return Ref_Compatible;
4309   else
4310     return Ref_Related;
4311 }
4312 
4313 /// Look for a user-defined conversion to a value reference-compatible
4314 ///        with DeclType. Return true if something definite is found.
4315 static bool
4316 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4317                          QualType DeclType, SourceLocation DeclLoc,
4318                          Expr *Init, QualType T2, bool AllowRvalues,
4319                          bool AllowExplicit) {
4320   assert(T2->isRecordType() && "Can only find conversions of record types.");
4321   CXXRecordDecl *T2RecordDecl
4322     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4323 
4324   OverloadCandidateSet CandidateSet(
4325       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4326   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4327   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4328     NamedDecl *D = *I;
4329     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4330     if (isa<UsingShadowDecl>(D))
4331       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4332 
4333     FunctionTemplateDecl *ConvTemplate
4334       = dyn_cast<FunctionTemplateDecl>(D);
4335     CXXConversionDecl *Conv;
4336     if (ConvTemplate)
4337       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4338     else
4339       Conv = cast<CXXConversionDecl>(D);
4340 
4341     // If this is an explicit conversion, and we're not allowed to consider
4342     // explicit conversions, skip it.
4343     if (!AllowExplicit && Conv->isExplicit())
4344       continue;
4345 
4346     if (AllowRvalues) {
4347       bool DerivedToBase = false;
4348       bool ObjCConversion = false;
4349       bool ObjCLifetimeConversion = false;
4350 
4351       // If we are initializing an rvalue reference, don't permit conversion
4352       // functions that return lvalues.
4353       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4354         const ReferenceType *RefType
4355           = Conv->getConversionType()->getAs<LValueReferenceType>();
4356         if (RefType && !RefType->getPointeeType()->isFunctionType())
4357           continue;
4358       }
4359 
4360       if (!ConvTemplate &&
4361           S.CompareReferenceRelationship(
4362             DeclLoc,
4363             Conv->getConversionType().getNonReferenceType()
4364               .getUnqualifiedType(),
4365             DeclType.getNonReferenceType().getUnqualifiedType(),
4366             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4367           Sema::Ref_Incompatible)
4368         continue;
4369     } else {
4370       // If the conversion function doesn't return a reference type,
4371       // it can't be considered for this conversion. An rvalue reference
4372       // is only acceptable if its referencee is a function type.
4373 
4374       const ReferenceType *RefType =
4375         Conv->getConversionType()->getAs<ReferenceType>();
4376       if (!RefType ||
4377           (!RefType->isLValueReferenceType() &&
4378            !RefType->getPointeeType()->isFunctionType()))
4379         continue;
4380     }
4381 
4382     if (ConvTemplate)
4383       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4384                                        Init, DeclType, CandidateSet,
4385                                        /*AllowObjCConversionOnExplicit=*/false);
4386     else
4387       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4388                                DeclType, CandidateSet,
4389                                /*AllowObjCConversionOnExplicit=*/false);
4390   }
4391 
4392   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4393 
4394   OverloadCandidateSet::iterator Best;
4395   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4396   case OR_Success:
4397     // C++ [over.ics.ref]p1:
4398     //
4399     //   [...] If the parameter binds directly to the result of
4400     //   applying a conversion function to the argument
4401     //   expression, the implicit conversion sequence is a
4402     //   user-defined conversion sequence (13.3.3.1.2), with the
4403     //   second standard conversion sequence either an identity
4404     //   conversion or, if the conversion function returns an
4405     //   entity of a type that is a derived class of the parameter
4406     //   type, a derived-to-base Conversion.
4407     if (!Best->FinalConversion.DirectBinding)
4408       return false;
4409 
4410     ICS.setUserDefined();
4411     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4412     ICS.UserDefined.After = Best->FinalConversion;
4413     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4414     ICS.UserDefined.ConversionFunction = Best->Function;
4415     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4416     ICS.UserDefined.EllipsisConversion = false;
4417     assert(ICS.UserDefined.After.ReferenceBinding &&
4418            ICS.UserDefined.After.DirectBinding &&
4419            "Expected a direct reference binding!");
4420     return true;
4421 
4422   case OR_Ambiguous:
4423     ICS.setAmbiguous();
4424     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4425          Cand != CandidateSet.end(); ++Cand)
4426       if (Cand->Viable)
4427         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4428     return true;
4429 
4430   case OR_No_Viable_Function:
4431   case OR_Deleted:
4432     // There was no suitable conversion, or we found a deleted
4433     // conversion; continue with other checks.
4434     return false;
4435   }
4436 
4437   llvm_unreachable("Invalid OverloadResult!");
4438 }
4439 
4440 /// Compute an implicit conversion sequence for reference
4441 /// initialization.
4442 static ImplicitConversionSequence
4443 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4444                  SourceLocation DeclLoc,
4445                  bool SuppressUserConversions,
4446                  bool AllowExplicit) {
4447   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4448 
4449   // Most paths end in a failed conversion.
4450   ImplicitConversionSequence ICS;
4451   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4452 
4453   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4454   QualType T2 = Init->getType();
4455 
4456   // If the initializer is the address of an overloaded function, try
4457   // to resolve the overloaded function. If all goes well, T2 is the
4458   // type of the resulting function.
4459   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4460     DeclAccessPair Found;
4461     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4462                                                                 false, Found))
4463       T2 = Fn->getType();
4464   }
4465 
4466   // Compute some basic properties of the types and the initializer.
4467   bool isRValRef = DeclType->isRValueReferenceType();
4468   bool DerivedToBase = false;
4469   bool ObjCConversion = false;
4470   bool ObjCLifetimeConversion = false;
4471   Expr::Classification InitCategory = Init->Classify(S.Context);
4472   Sema::ReferenceCompareResult RefRelationship
4473     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4474                                      ObjCConversion, ObjCLifetimeConversion);
4475 
4476 
4477   // C++0x [dcl.init.ref]p5:
4478   //   A reference to type "cv1 T1" is initialized by an expression
4479   //   of type "cv2 T2" as follows:
4480 
4481   //     -- If reference is an lvalue reference and the initializer expression
4482   if (!isRValRef) {
4483     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4484     //        reference-compatible with "cv2 T2," or
4485     //
4486     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4487     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4488       // C++ [over.ics.ref]p1:
4489       //   When a parameter of reference type binds directly (8.5.3)
4490       //   to an argument expression, the implicit conversion sequence
4491       //   is the identity conversion, unless the argument expression
4492       //   has a type that is a derived class of the parameter type,
4493       //   in which case the implicit conversion sequence is a
4494       //   derived-to-base Conversion (13.3.3.1).
4495       ICS.setStandard();
4496       ICS.Standard.First = ICK_Identity;
4497       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4498                          : ObjCConversion? ICK_Compatible_Conversion
4499                          : ICK_Identity;
4500       ICS.Standard.Third = ICK_Identity;
4501       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4502       ICS.Standard.setToType(0, T2);
4503       ICS.Standard.setToType(1, T1);
4504       ICS.Standard.setToType(2, T1);
4505       ICS.Standard.ReferenceBinding = true;
4506       ICS.Standard.DirectBinding = true;
4507       ICS.Standard.IsLvalueReference = !isRValRef;
4508       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4509       ICS.Standard.BindsToRvalue = false;
4510       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4511       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4512       ICS.Standard.CopyConstructor = nullptr;
4513       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4514 
4515       // Nothing more to do: the inaccessibility/ambiguity check for
4516       // derived-to-base conversions is suppressed when we're
4517       // computing the implicit conversion sequence (C++
4518       // [over.best.ics]p2).
4519       return ICS;
4520     }
4521 
4522     //       -- has a class type (i.e., T2 is a class type), where T1 is
4523     //          not reference-related to T2, and can be implicitly
4524     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4525     //          is reference-compatible with "cv3 T3" 92) (this
4526     //          conversion is selected by enumerating the applicable
4527     //          conversion functions (13.3.1.6) and choosing the best
4528     //          one through overload resolution (13.3)),
4529     if (!SuppressUserConversions && T2->isRecordType() &&
4530         S.isCompleteType(DeclLoc, T2) &&
4531         RefRelationship == Sema::Ref_Incompatible) {
4532       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4533                                    Init, T2, /*AllowRvalues=*/false,
4534                                    AllowExplicit))
4535         return ICS;
4536     }
4537   }
4538 
4539   //     -- Otherwise, the reference shall be an lvalue reference to a
4540   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4541   //        shall be an rvalue reference.
4542   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4543     return ICS;
4544 
4545   //       -- If the initializer expression
4546   //
4547   //            -- is an xvalue, class prvalue, array prvalue or function
4548   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4549   if (RefRelationship == Sema::Ref_Compatible &&
4550       (InitCategory.isXValue() ||
4551        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4552        (InitCategory.isLValue() && T2->isFunctionType()))) {
4553     ICS.setStandard();
4554     ICS.Standard.First = ICK_Identity;
4555     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4556                       : ObjCConversion? ICK_Compatible_Conversion
4557                       : ICK_Identity;
4558     ICS.Standard.Third = ICK_Identity;
4559     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4560     ICS.Standard.setToType(0, T2);
4561     ICS.Standard.setToType(1, T1);
4562     ICS.Standard.setToType(2, T1);
4563     ICS.Standard.ReferenceBinding = true;
4564     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4565     // binding unless we're binding to a class prvalue.
4566     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4567     // allow the use of rvalue references in C++98/03 for the benefit of
4568     // standard library implementors; therefore, we need the xvalue check here.
4569     ICS.Standard.DirectBinding =
4570       S.getLangOpts().CPlusPlus11 ||
4571       !(InitCategory.isPRValue() || T2->isRecordType());
4572     ICS.Standard.IsLvalueReference = !isRValRef;
4573     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4574     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4575     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4576     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4577     ICS.Standard.CopyConstructor = nullptr;
4578     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4579     return ICS;
4580   }
4581 
4582   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4583   //               reference-related to T2, and can be implicitly converted to
4584   //               an xvalue, class prvalue, or function lvalue of type
4585   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4586   //               "cv3 T3",
4587   //
4588   //          then the reference is bound to the value of the initializer
4589   //          expression in the first case and to the result of the conversion
4590   //          in the second case (or, in either case, to an appropriate base
4591   //          class subobject).
4592   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4593       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4594       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4595                                Init, T2, /*AllowRvalues=*/true,
4596                                AllowExplicit)) {
4597     // In the second case, if the reference is an rvalue reference
4598     // and the second standard conversion sequence of the
4599     // user-defined conversion sequence includes an lvalue-to-rvalue
4600     // conversion, the program is ill-formed.
4601     if (ICS.isUserDefined() && isRValRef &&
4602         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4603       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4604 
4605     return ICS;
4606   }
4607 
4608   // A temporary of function type cannot be created; don't even try.
4609   if (T1->isFunctionType())
4610     return ICS;
4611 
4612   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4613   //          initialized from the initializer expression using the
4614   //          rules for a non-reference copy initialization (8.5). The
4615   //          reference is then bound to the temporary. If T1 is
4616   //          reference-related to T2, cv1 must be the same
4617   //          cv-qualification as, or greater cv-qualification than,
4618   //          cv2; otherwise, the program is ill-formed.
4619   if (RefRelationship == Sema::Ref_Related) {
4620     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4621     // we would be reference-compatible or reference-compatible with
4622     // added qualification. But that wasn't the case, so the reference
4623     // initialization fails.
4624     //
4625     // Note that we only want to check address spaces and cvr-qualifiers here.
4626     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4627     Qualifiers T1Quals = T1.getQualifiers();
4628     Qualifiers T2Quals = T2.getQualifiers();
4629     T1Quals.removeObjCGCAttr();
4630     T1Quals.removeObjCLifetime();
4631     T2Quals.removeObjCGCAttr();
4632     T2Quals.removeObjCLifetime();
4633     // MS compiler ignores __unaligned qualifier for references; do the same.
4634     T1Quals.removeUnaligned();
4635     T2Quals.removeUnaligned();
4636     if (!T1Quals.compatiblyIncludes(T2Quals))
4637       return ICS;
4638   }
4639 
4640   // If at least one of the types is a class type, the types are not
4641   // related, and we aren't allowed any user conversions, the
4642   // reference binding fails. This case is important for breaking
4643   // recursion, since TryImplicitConversion below will attempt to
4644   // create a temporary through the use of a copy constructor.
4645   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4646       (T1->isRecordType() || T2->isRecordType()))
4647     return ICS;
4648 
4649   // If T1 is reference-related to T2 and the reference is an rvalue
4650   // reference, the initializer expression shall not be an lvalue.
4651   if (RefRelationship >= Sema::Ref_Related &&
4652       isRValRef && Init->Classify(S.Context).isLValue())
4653     return ICS;
4654 
4655   // C++ [over.ics.ref]p2:
4656   //   When a parameter of reference type is not bound directly to
4657   //   an argument expression, the conversion sequence is the one
4658   //   required to convert the argument expression to the
4659   //   underlying type of the reference according to
4660   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4661   //   to copy-initializing a temporary of the underlying type with
4662   //   the argument expression. Any difference in top-level
4663   //   cv-qualification is subsumed by the initialization itself
4664   //   and does not constitute a conversion.
4665   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4666                               /*AllowExplicit=*/false,
4667                               /*InOverloadResolution=*/false,
4668                               /*CStyle=*/false,
4669                               /*AllowObjCWritebackConversion=*/false,
4670                               /*AllowObjCConversionOnExplicit=*/false);
4671 
4672   // Of course, that's still a reference binding.
4673   if (ICS.isStandard()) {
4674     ICS.Standard.ReferenceBinding = true;
4675     ICS.Standard.IsLvalueReference = !isRValRef;
4676     ICS.Standard.BindsToFunctionLvalue = false;
4677     ICS.Standard.BindsToRvalue = true;
4678     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4679     ICS.Standard.ObjCLifetimeConversionBinding = false;
4680   } else if (ICS.isUserDefined()) {
4681     const ReferenceType *LValRefType =
4682         ICS.UserDefined.ConversionFunction->getReturnType()
4683             ->getAs<LValueReferenceType>();
4684 
4685     // C++ [over.ics.ref]p3:
4686     //   Except for an implicit object parameter, for which see 13.3.1, a
4687     //   standard conversion sequence cannot be formed if it requires [...]
4688     //   binding an rvalue reference to an lvalue other than a function
4689     //   lvalue.
4690     // Note that the function case is not possible here.
4691     if (DeclType->isRValueReferenceType() && LValRefType) {
4692       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4693       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4694       // reference to an rvalue!
4695       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4696       return ICS;
4697     }
4698 
4699     ICS.UserDefined.After.ReferenceBinding = true;
4700     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4701     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4702     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4703     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4704     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4705   }
4706 
4707   return ICS;
4708 }
4709 
4710 static ImplicitConversionSequence
4711 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4712                       bool SuppressUserConversions,
4713                       bool InOverloadResolution,
4714                       bool AllowObjCWritebackConversion,
4715                       bool AllowExplicit = false);
4716 
4717 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4718 /// initializer list From.
4719 static ImplicitConversionSequence
4720 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4721                   bool SuppressUserConversions,
4722                   bool InOverloadResolution,
4723                   bool AllowObjCWritebackConversion) {
4724   // C++11 [over.ics.list]p1:
4725   //   When an argument is an initializer list, it is not an expression and
4726   //   special rules apply for converting it to a parameter type.
4727 
4728   ImplicitConversionSequence Result;
4729   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4730 
4731   // We need a complete type for what follows. Incomplete types can never be
4732   // initialized from init lists.
4733   if (!S.isCompleteType(From->getLocStart(), ToType))
4734     return Result;
4735 
4736   // Per DR1467:
4737   //   If the parameter type is a class X and the initializer list has a single
4738   //   element of type cv U, where U is X or a class derived from X, the
4739   //   implicit conversion sequence is the one required to convert the element
4740   //   to the parameter type.
4741   //
4742   //   Otherwise, if the parameter type is a character array [... ]
4743   //   and the initializer list has a single element that is an
4744   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4745   //   implicit conversion sequence is the identity conversion.
4746   if (From->getNumInits() == 1) {
4747     if (ToType->isRecordType()) {
4748       QualType InitType = From->getInit(0)->getType();
4749       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4750           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4751         return TryCopyInitialization(S, From->getInit(0), ToType,
4752                                      SuppressUserConversions,
4753                                      InOverloadResolution,
4754                                      AllowObjCWritebackConversion);
4755     }
4756     // FIXME: Check the other conditions here: array of character type,
4757     // initializer is a string literal.
4758     if (ToType->isArrayType()) {
4759       InitializedEntity Entity =
4760         InitializedEntity::InitializeParameter(S.Context, ToType,
4761                                                /*Consumed=*/false);
4762       if (S.CanPerformCopyInitialization(Entity, From)) {
4763         Result.setStandard();
4764         Result.Standard.setAsIdentityConversion();
4765         Result.Standard.setFromType(ToType);
4766         Result.Standard.setAllToTypes(ToType);
4767         return Result;
4768       }
4769     }
4770   }
4771 
4772   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4773   // C++11 [over.ics.list]p2:
4774   //   If the parameter type is std::initializer_list<X> or "array of X" and
4775   //   all the elements can be implicitly converted to X, the implicit
4776   //   conversion sequence is the worst conversion necessary to convert an
4777   //   element of the list to X.
4778   //
4779   // C++14 [over.ics.list]p3:
4780   //   Otherwise, if the parameter type is "array of N X", if the initializer
4781   //   list has exactly N elements or if it has fewer than N elements and X is
4782   //   default-constructible, and if all the elements of the initializer list
4783   //   can be implicitly converted to X, the implicit conversion sequence is
4784   //   the worst conversion necessary to convert an element of the list to X.
4785   //
4786   // FIXME: We're missing a lot of these checks.
4787   bool toStdInitializerList = false;
4788   QualType X;
4789   if (ToType->isArrayType())
4790     X = S.Context.getAsArrayType(ToType)->getElementType();
4791   else
4792     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4793   if (!X.isNull()) {
4794     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4795       Expr *Init = From->getInit(i);
4796       ImplicitConversionSequence ICS =
4797           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4798                                 InOverloadResolution,
4799                                 AllowObjCWritebackConversion);
4800       // If a single element isn't convertible, fail.
4801       if (ICS.isBad()) {
4802         Result = ICS;
4803         break;
4804       }
4805       // Otherwise, look for the worst conversion.
4806       if (Result.isBad() ||
4807           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4808                                              Result) ==
4809               ImplicitConversionSequence::Worse)
4810         Result = ICS;
4811     }
4812 
4813     // For an empty list, we won't have computed any conversion sequence.
4814     // Introduce the identity conversion sequence.
4815     if (From->getNumInits() == 0) {
4816       Result.setStandard();
4817       Result.Standard.setAsIdentityConversion();
4818       Result.Standard.setFromType(ToType);
4819       Result.Standard.setAllToTypes(ToType);
4820     }
4821 
4822     Result.setStdInitializerListElement(toStdInitializerList);
4823     return Result;
4824   }
4825 
4826   // C++14 [over.ics.list]p4:
4827   // C++11 [over.ics.list]p3:
4828   //   Otherwise, if the parameter is a non-aggregate class X and overload
4829   //   resolution chooses a single best constructor [...] the implicit
4830   //   conversion sequence is a user-defined conversion sequence. If multiple
4831   //   constructors are viable but none is better than the others, the
4832   //   implicit conversion sequence is a user-defined conversion sequence.
4833   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4834     // This function can deal with initializer lists.
4835     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4836                                     /*AllowExplicit=*/false,
4837                                     InOverloadResolution, /*CStyle=*/false,
4838                                     AllowObjCWritebackConversion,
4839                                     /*AllowObjCConversionOnExplicit=*/false);
4840   }
4841 
4842   // C++14 [over.ics.list]p5:
4843   // C++11 [over.ics.list]p4:
4844   //   Otherwise, if the parameter has an aggregate type which can be
4845   //   initialized from the initializer list [...] the implicit conversion
4846   //   sequence is a user-defined conversion sequence.
4847   if (ToType->isAggregateType()) {
4848     // Type is an aggregate, argument is an init list. At this point it comes
4849     // down to checking whether the initialization works.
4850     // FIXME: Find out whether this parameter is consumed or not.
4851     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4852     // need to call into the initialization code here; overload resolution
4853     // should not be doing that.
4854     InitializedEntity Entity =
4855         InitializedEntity::InitializeParameter(S.Context, ToType,
4856                                                /*Consumed=*/false);
4857     if (S.CanPerformCopyInitialization(Entity, From)) {
4858       Result.setUserDefined();
4859       Result.UserDefined.Before.setAsIdentityConversion();
4860       // Initializer lists don't have a type.
4861       Result.UserDefined.Before.setFromType(QualType());
4862       Result.UserDefined.Before.setAllToTypes(QualType());
4863 
4864       Result.UserDefined.After.setAsIdentityConversion();
4865       Result.UserDefined.After.setFromType(ToType);
4866       Result.UserDefined.After.setAllToTypes(ToType);
4867       Result.UserDefined.ConversionFunction = nullptr;
4868     }
4869     return Result;
4870   }
4871 
4872   // C++14 [over.ics.list]p6:
4873   // C++11 [over.ics.list]p5:
4874   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4875   if (ToType->isReferenceType()) {
4876     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4877     // mention initializer lists in any way. So we go by what list-
4878     // initialization would do and try to extrapolate from that.
4879 
4880     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4881 
4882     // If the initializer list has a single element that is reference-related
4883     // to the parameter type, we initialize the reference from that.
4884     if (From->getNumInits() == 1) {
4885       Expr *Init = From->getInit(0);
4886 
4887       QualType T2 = Init->getType();
4888 
4889       // If the initializer is the address of an overloaded function, try
4890       // to resolve the overloaded function. If all goes well, T2 is the
4891       // type of the resulting function.
4892       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4893         DeclAccessPair Found;
4894         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4895                                    Init, ToType, false, Found))
4896           T2 = Fn->getType();
4897       }
4898 
4899       // Compute some basic properties of the types and the initializer.
4900       bool dummy1 = false;
4901       bool dummy2 = false;
4902       bool dummy3 = false;
4903       Sema::ReferenceCompareResult RefRelationship
4904         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4905                                          dummy2, dummy3);
4906 
4907       if (RefRelationship >= Sema::Ref_Related) {
4908         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4909                                 SuppressUserConversions,
4910                                 /*AllowExplicit=*/false);
4911       }
4912     }
4913 
4914     // Otherwise, we bind the reference to a temporary created from the
4915     // initializer list.
4916     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4917                                InOverloadResolution,
4918                                AllowObjCWritebackConversion);
4919     if (Result.isFailure())
4920       return Result;
4921     assert(!Result.isEllipsis() &&
4922            "Sub-initialization cannot result in ellipsis conversion.");
4923 
4924     // Can we even bind to a temporary?
4925     if (ToType->isRValueReferenceType() ||
4926         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4927       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4928                                             Result.UserDefined.After;
4929       SCS.ReferenceBinding = true;
4930       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4931       SCS.BindsToRvalue = true;
4932       SCS.BindsToFunctionLvalue = false;
4933       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4934       SCS.ObjCLifetimeConversionBinding = false;
4935     } else
4936       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4937                     From, ToType);
4938     return Result;
4939   }
4940 
4941   // C++14 [over.ics.list]p7:
4942   // C++11 [over.ics.list]p6:
4943   //   Otherwise, if the parameter type is not a class:
4944   if (!ToType->isRecordType()) {
4945     //    - if the initializer list has one element that is not itself an
4946     //      initializer list, the implicit conversion sequence is the one
4947     //      required to convert the element to the parameter type.
4948     unsigned NumInits = From->getNumInits();
4949     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4950       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4951                                      SuppressUserConversions,
4952                                      InOverloadResolution,
4953                                      AllowObjCWritebackConversion);
4954     //    - if the initializer list has no elements, the implicit conversion
4955     //      sequence is the identity conversion.
4956     else if (NumInits == 0) {
4957       Result.setStandard();
4958       Result.Standard.setAsIdentityConversion();
4959       Result.Standard.setFromType(ToType);
4960       Result.Standard.setAllToTypes(ToType);
4961     }
4962     return Result;
4963   }
4964 
4965   // C++14 [over.ics.list]p8:
4966   // C++11 [over.ics.list]p7:
4967   //   In all cases other than those enumerated above, no conversion is possible
4968   return Result;
4969 }
4970 
4971 /// TryCopyInitialization - Try to copy-initialize a value of type
4972 /// ToType from the expression From. Return the implicit conversion
4973 /// sequence required to pass this argument, which may be a bad
4974 /// conversion sequence (meaning that the argument cannot be passed to
4975 /// a parameter of this type). If @p SuppressUserConversions, then we
4976 /// do not permit any user-defined conversion sequences.
4977 static ImplicitConversionSequence
4978 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4979                       bool SuppressUserConversions,
4980                       bool InOverloadResolution,
4981                       bool AllowObjCWritebackConversion,
4982                       bool AllowExplicit) {
4983   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4984     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4985                              InOverloadResolution,AllowObjCWritebackConversion);
4986 
4987   if (ToType->isReferenceType())
4988     return TryReferenceInit(S, From, ToType,
4989                             /*FIXME:*/From->getLocStart(),
4990                             SuppressUserConversions,
4991                             AllowExplicit);
4992 
4993   return TryImplicitConversion(S, From, ToType,
4994                                SuppressUserConversions,
4995                                /*AllowExplicit=*/false,
4996                                InOverloadResolution,
4997                                /*CStyle=*/false,
4998                                AllowObjCWritebackConversion,
4999                                /*AllowObjCConversionOnExplicit=*/false);
5000 }
5001 
5002 static bool TryCopyInitialization(const CanQualType FromQTy,
5003                                   const CanQualType ToQTy,
5004                                   Sema &S,
5005                                   SourceLocation Loc,
5006                                   ExprValueKind FromVK) {
5007   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5008   ImplicitConversionSequence ICS =
5009     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5010 
5011   return !ICS.isBad();
5012 }
5013 
5014 /// TryObjectArgumentInitialization - Try to initialize the object
5015 /// parameter of the given member function (@c Method) from the
5016 /// expression @p From.
5017 static ImplicitConversionSequence
5018 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5019                                 Expr::Classification FromClassification,
5020                                 CXXMethodDecl *Method,
5021                                 CXXRecordDecl *ActingContext) {
5022   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5023   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5024   //                 const volatile object.
5025   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5026     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5027   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
5028 
5029   // Set up the conversion sequence as a "bad" conversion, to allow us
5030   // to exit early.
5031   ImplicitConversionSequence ICS;
5032 
5033   // We need to have an object of class type.
5034   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5035     FromType = PT->getPointeeType();
5036 
5037     // When we had a pointer, it's implicitly dereferenced, so we
5038     // better have an lvalue.
5039     assert(FromClassification.isLValue());
5040   }
5041 
5042   assert(FromType->isRecordType());
5043 
5044   // C++0x [over.match.funcs]p4:
5045   //   For non-static member functions, the type of the implicit object
5046   //   parameter is
5047   //
5048   //     - "lvalue reference to cv X" for functions declared without a
5049   //        ref-qualifier or with the & ref-qualifier
5050   //     - "rvalue reference to cv X" for functions declared with the &&
5051   //        ref-qualifier
5052   //
5053   // where X is the class of which the function is a member and cv is the
5054   // cv-qualification on the member function declaration.
5055   //
5056   // However, when finding an implicit conversion sequence for the argument, we
5057   // are not allowed to perform user-defined conversions
5058   // (C++ [over.match.funcs]p5). We perform a simplified version of
5059   // reference binding here, that allows class rvalues to bind to
5060   // non-constant references.
5061 
5062   // First check the qualifiers.
5063   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5064   if (ImplicitParamType.getCVRQualifiers()
5065                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5066       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5067     ICS.setBad(BadConversionSequence::bad_qualifiers,
5068                FromType, ImplicitParamType);
5069     return ICS;
5070   }
5071 
5072   // Check that we have either the same type or a derived type. It
5073   // affects the conversion rank.
5074   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5075   ImplicitConversionKind SecondKind;
5076   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5077     SecondKind = ICK_Identity;
5078   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5079     SecondKind = ICK_Derived_To_Base;
5080   else {
5081     ICS.setBad(BadConversionSequence::unrelated_class,
5082                FromType, ImplicitParamType);
5083     return ICS;
5084   }
5085 
5086   // Check the ref-qualifier.
5087   switch (Method->getRefQualifier()) {
5088   case RQ_None:
5089     // Do nothing; we don't care about lvalueness or rvalueness.
5090     break;
5091 
5092   case RQ_LValue:
5093     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5094       // non-const lvalue reference cannot bind to an rvalue
5095       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5096                  ImplicitParamType);
5097       return ICS;
5098     }
5099     break;
5100 
5101   case RQ_RValue:
5102     if (!FromClassification.isRValue()) {
5103       // rvalue reference cannot bind to an lvalue
5104       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5105                  ImplicitParamType);
5106       return ICS;
5107     }
5108     break;
5109   }
5110 
5111   // Success. Mark this as a reference binding.
5112   ICS.setStandard();
5113   ICS.Standard.setAsIdentityConversion();
5114   ICS.Standard.Second = SecondKind;
5115   ICS.Standard.setFromType(FromType);
5116   ICS.Standard.setAllToTypes(ImplicitParamType);
5117   ICS.Standard.ReferenceBinding = true;
5118   ICS.Standard.DirectBinding = true;
5119   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5120   ICS.Standard.BindsToFunctionLvalue = false;
5121   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5122   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5123     = (Method->getRefQualifier() == RQ_None);
5124   return ICS;
5125 }
5126 
5127 /// PerformObjectArgumentInitialization - Perform initialization of
5128 /// the implicit object parameter for the given Method with the given
5129 /// expression.
5130 ExprResult
5131 Sema::PerformObjectArgumentInitialization(Expr *From,
5132                                           NestedNameSpecifier *Qualifier,
5133                                           NamedDecl *FoundDecl,
5134                                           CXXMethodDecl *Method) {
5135   QualType FromRecordType, DestType;
5136   QualType ImplicitParamRecordType  =
5137     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5138 
5139   Expr::Classification FromClassification;
5140   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5141     FromRecordType = PT->getPointeeType();
5142     DestType = Method->getThisType(Context);
5143     FromClassification = Expr::Classification::makeSimpleLValue();
5144   } else {
5145     FromRecordType = From->getType();
5146     DestType = ImplicitParamRecordType;
5147     FromClassification = From->Classify(Context);
5148   }
5149 
5150   // Note that we always use the true parent context when performing
5151   // the actual argument initialization.
5152   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5153       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5154       Method->getParent());
5155   if (ICS.isBad()) {
5156     switch (ICS.Bad.Kind) {
5157     case BadConversionSequence::bad_qualifiers: {
5158       Qualifiers FromQs = FromRecordType.getQualifiers();
5159       Qualifiers ToQs = DestType.getQualifiers();
5160       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5161       if (CVR) {
5162         Diag(From->getLocStart(),
5163              diag::err_member_function_call_bad_cvr)
5164           << Method->getDeclName() << FromRecordType << (CVR - 1)
5165           << From->getSourceRange();
5166         Diag(Method->getLocation(), diag::note_previous_decl)
5167           << Method->getDeclName();
5168         return ExprError();
5169       }
5170       break;
5171     }
5172 
5173     case BadConversionSequence::lvalue_ref_to_rvalue:
5174     case BadConversionSequence::rvalue_ref_to_lvalue: {
5175       bool IsRValueQualified =
5176         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5177       Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5178         << Method->getDeclName() << FromClassification.isRValue()
5179         << IsRValueQualified;
5180       Diag(Method->getLocation(), diag::note_previous_decl)
5181         << Method->getDeclName();
5182       return ExprError();
5183     }
5184 
5185     case BadConversionSequence::no_conversion:
5186     case BadConversionSequence::unrelated_class:
5187       break;
5188     }
5189 
5190     return Diag(From->getLocStart(),
5191                 diag::err_member_function_call_bad_type)
5192        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5193   }
5194 
5195   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5196     ExprResult FromRes =
5197       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5198     if (FromRes.isInvalid())
5199       return ExprError();
5200     From = FromRes.get();
5201   }
5202 
5203   if (!Context.hasSameType(From->getType(), DestType))
5204     From = ImpCastExprToType(From, DestType, CK_NoOp,
5205                              From->getValueKind()).get();
5206   return From;
5207 }
5208 
5209 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5210 /// expression From to bool (C++0x [conv]p3).
5211 static ImplicitConversionSequence
5212 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5213   return TryImplicitConversion(S, From, S.Context.BoolTy,
5214                                /*SuppressUserConversions=*/false,
5215                                /*AllowExplicit=*/true,
5216                                /*InOverloadResolution=*/false,
5217                                /*CStyle=*/false,
5218                                /*AllowObjCWritebackConversion=*/false,
5219                                /*AllowObjCConversionOnExplicit=*/false);
5220 }
5221 
5222 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5223 /// of the expression From to bool (C++0x [conv]p3).
5224 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5225   if (checkPlaceholderForOverload(*this, From))
5226     return ExprError();
5227 
5228   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5229   if (!ICS.isBad())
5230     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5231 
5232   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5233     return Diag(From->getLocStart(),
5234                 diag::err_typecheck_bool_condition)
5235                   << From->getType() << From->getSourceRange();
5236   return ExprError();
5237 }
5238 
5239 /// Check that the specified conversion is permitted in a converted constant
5240 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5241 /// is acceptable.
5242 static bool CheckConvertedConstantConversions(Sema &S,
5243                                               StandardConversionSequence &SCS) {
5244   // Since we know that the target type is an integral or unscoped enumeration
5245   // type, most conversion kinds are impossible. All possible First and Third
5246   // conversions are fine.
5247   switch (SCS.Second) {
5248   case ICK_Identity:
5249   case ICK_Function_Conversion:
5250   case ICK_Integral_Promotion:
5251   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5252   case ICK_Zero_Queue_Conversion:
5253     return true;
5254 
5255   case ICK_Boolean_Conversion:
5256     // Conversion from an integral or unscoped enumeration type to bool is
5257     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5258     // conversion, so we allow it in a converted constant expression.
5259     //
5260     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5261     // a lot of popular code. We should at least add a warning for this
5262     // (non-conforming) extension.
5263     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5264            SCS.getToType(2)->isBooleanType();
5265 
5266   case ICK_Pointer_Conversion:
5267   case ICK_Pointer_Member:
5268     // C++1z: null pointer conversions and null member pointer conversions are
5269     // only permitted if the source type is std::nullptr_t.
5270     return SCS.getFromType()->isNullPtrType();
5271 
5272   case ICK_Floating_Promotion:
5273   case ICK_Complex_Promotion:
5274   case ICK_Floating_Conversion:
5275   case ICK_Complex_Conversion:
5276   case ICK_Floating_Integral:
5277   case ICK_Compatible_Conversion:
5278   case ICK_Derived_To_Base:
5279   case ICK_Vector_Conversion:
5280   case ICK_Vector_Splat:
5281   case ICK_Complex_Real:
5282   case ICK_Block_Pointer_Conversion:
5283   case ICK_TransparentUnionConversion:
5284   case ICK_Writeback_Conversion:
5285   case ICK_Zero_Event_Conversion:
5286   case ICK_C_Only_Conversion:
5287   case ICK_Incompatible_Pointer_Conversion:
5288     return false;
5289 
5290   case ICK_Lvalue_To_Rvalue:
5291   case ICK_Array_To_Pointer:
5292   case ICK_Function_To_Pointer:
5293     llvm_unreachable("found a first conversion kind in Second");
5294 
5295   case ICK_Qualification:
5296     llvm_unreachable("found a third conversion kind in Second");
5297 
5298   case ICK_Num_Conversion_Kinds:
5299     break;
5300   }
5301 
5302   llvm_unreachable("unknown conversion kind");
5303 }
5304 
5305 /// CheckConvertedConstantExpression - Check that the expression From is a
5306 /// converted constant expression of type T, perform the conversion and produce
5307 /// the converted expression, per C++11 [expr.const]p3.
5308 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5309                                                    QualType T, APValue &Value,
5310                                                    Sema::CCEKind CCE,
5311                                                    bool RequireInt) {
5312   assert(S.getLangOpts().CPlusPlus11 &&
5313          "converted constant expression outside C++11");
5314 
5315   if (checkPlaceholderForOverload(S, From))
5316     return ExprError();
5317 
5318   // C++1z [expr.const]p3:
5319   //  A converted constant expression of type T is an expression,
5320   //  implicitly converted to type T, where the converted
5321   //  expression is a constant expression and the implicit conversion
5322   //  sequence contains only [... list of conversions ...].
5323   // C++1z [stmt.if]p2:
5324   //  If the if statement is of the form if constexpr, the value of the
5325   //  condition shall be a contextually converted constant expression of type
5326   //  bool.
5327   ImplicitConversionSequence ICS =
5328       CCE == Sema::CCEK_ConstexprIf
5329           ? TryContextuallyConvertToBool(S, From)
5330           : TryCopyInitialization(S, From, T,
5331                                   /*SuppressUserConversions=*/false,
5332                                   /*InOverloadResolution=*/false,
5333                                   /*AllowObjcWritebackConversion=*/false,
5334                                   /*AllowExplicit=*/false);
5335   StandardConversionSequence *SCS = nullptr;
5336   switch (ICS.getKind()) {
5337   case ImplicitConversionSequence::StandardConversion:
5338     SCS = &ICS.Standard;
5339     break;
5340   case ImplicitConversionSequence::UserDefinedConversion:
5341     // We are converting to a non-class type, so the Before sequence
5342     // must be trivial.
5343     SCS = &ICS.UserDefined.After;
5344     break;
5345   case ImplicitConversionSequence::AmbiguousConversion:
5346   case ImplicitConversionSequence::BadConversion:
5347     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5348       return S.Diag(From->getLocStart(),
5349                     diag::err_typecheck_converted_constant_expression)
5350                 << From->getType() << From->getSourceRange() << T;
5351     return ExprError();
5352 
5353   case ImplicitConversionSequence::EllipsisConversion:
5354     llvm_unreachable("ellipsis conversion in converted constant expression");
5355   }
5356 
5357   // Check that we would only use permitted conversions.
5358   if (!CheckConvertedConstantConversions(S, *SCS)) {
5359     return S.Diag(From->getLocStart(),
5360                   diag::err_typecheck_converted_constant_expression_disallowed)
5361              << From->getType() << From->getSourceRange() << T;
5362   }
5363   // [...] and where the reference binding (if any) binds directly.
5364   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5365     return S.Diag(From->getLocStart(),
5366                   diag::err_typecheck_converted_constant_expression_indirect)
5367              << From->getType() << From->getSourceRange() << T;
5368   }
5369 
5370   ExprResult Result =
5371       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5372   if (Result.isInvalid())
5373     return Result;
5374 
5375   // Check for a narrowing implicit conversion.
5376   APValue PreNarrowingValue;
5377   QualType PreNarrowingType;
5378   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5379                                 PreNarrowingType)) {
5380   case NK_Dependent_Narrowing:
5381     // Implicit conversion to a narrower type, but the expression is
5382     // value-dependent so we can't tell whether it's actually narrowing.
5383   case NK_Variable_Narrowing:
5384     // Implicit conversion to a narrower type, and the value is not a constant
5385     // expression. We'll diagnose this in a moment.
5386   case NK_Not_Narrowing:
5387     break;
5388 
5389   case NK_Constant_Narrowing:
5390     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5391       << CCE << /*Constant*/1
5392       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5393     break;
5394 
5395   case NK_Type_Narrowing:
5396     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5397       << CCE << /*Constant*/0 << From->getType() << T;
5398     break;
5399   }
5400 
5401   if (Result.get()->isValueDependent()) {
5402     Value = APValue();
5403     return Result;
5404   }
5405 
5406   // Check the expression is a constant expression.
5407   SmallVector<PartialDiagnosticAt, 8> Notes;
5408   Expr::EvalResult Eval;
5409   Eval.Diag = &Notes;
5410   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5411                                    ? Expr::EvaluateForMangling
5412                                    : Expr::EvaluateForCodeGen;
5413 
5414   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5415       (RequireInt && !Eval.Val.isInt())) {
5416     // The expression can't be folded, so we can't keep it at this position in
5417     // the AST.
5418     Result = ExprError();
5419   } else {
5420     Value = Eval.Val;
5421 
5422     if (Notes.empty()) {
5423       // It's a constant expression.
5424       return Result;
5425     }
5426   }
5427 
5428   // It's not a constant expression. Produce an appropriate diagnostic.
5429   if (Notes.size() == 1 &&
5430       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5431     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5432   else {
5433     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5434       << CCE << From->getSourceRange();
5435     for (unsigned I = 0; I < Notes.size(); ++I)
5436       S.Diag(Notes[I].first, Notes[I].second);
5437   }
5438   return ExprError();
5439 }
5440 
5441 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5442                                                   APValue &Value, CCEKind CCE) {
5443   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5444 }
5445 
5446 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5447                                                   llvm::APSInt &Value,
5448                                                   CCEKind CCE) {
5449   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5450 
5451   APValue V;
5452   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5453   if (!R.isInvalid() && !R.get()->isValueDependent())
5454     Value = V.getInt();
5455   return R;
5456 }
5457 
5458 
5459 /// dropPointerConversions - If the given standard conversion sequence
5460 /// involves any pointer conversions, remove them.  This may change
5461 /// the result type of the conversion sequence.
5462 static void dropPointerConversion(StandardConversionSequence &SCS) {
5463   if (SCS.Second == ICK_Pointer_Conversion) {
5464     SCS.Second = ICK_Identity;
5465     SCS.Third = ICK_Identity;
5466     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5467   }
5468 }
5469 
5470 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5471 /// convert the expression From to an Objective-C pointer type.
5472 static ImplicitConversionSequence
5473 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5474   // Do an implicit conversion to 'id'.
5475   QualType Ty = S.Context.getObjCIdType();
5476   ImplicitConversionSequence ICS
5477     = TryImplicitConversion(S, From, Ty,
5478                             // FIXME: Are these flags correct?
5479                             /*SuppressUserConversions=*/false,
5480                             /*AllowExplicit=*/true,
5481                             /*InOverloadResolution=*/false,
5482                             /*CStyle=*/false,
5483                             /*AllowObjCWritebackConversion=*/false,
5484                             /*AllowObjCConversionOnExplicit=*/true);
5485 
5486   // Strip off any final conversions to 'id'.
5487   switch (ICS.getKind()) {
5488   case ImplicitConversionSequence::BadConversion:
5489   case ImplicitConversionSequence::AmbiguousConversion:
5490   case ImplicitConversionSequence::EllipsisConversion:
5491     break;
5492 
5493   case ImplicitConversionSequence::UserDefinedConversion:
5494     dropPointerConversion(ICS.UserDefined.After);
5495     break;
5496 
5497   case ImplicitConversionSequence::StandardConversion:
5498     dropPointerConversion(ICS.Standard);
5499     break;
5500   }
5501 
5502   return ICS;
5503 }
5504 
5505 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5506 /// conversion of the expression From to an Objective-C pointer type.
5507 /// Returns a valid but null ExprResult if no conversion sequence exists.
5508 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5509   if (checkPlaceholderForOverload(*this, From))
5510     return ExprError();
5511 
5512   QualType Ty = Context.getObjCIdType();
5513   ImplicitConversionSequence ICS =
5514     TryContextuallyConvertToObjCPointer(*this, From);
5515   if (!ICS.isBad())
5516     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5517   return ExprResult();
5518 }
5519 
5520 /// Determine whether the provided type is an integral type, or an enumeration
5521 /// type of a permitted flavor.
5522 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5523   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5524                                  : T->isIntegralOrUnscopedEnumerationType();
5525 }
5526 
5527 static ExprResult
5528 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5529                             Sema::ContextualImplicitConverter &Converter,
5530                             QualType T, UnresolvedSetImpl &ViableConversions) {
5531 
5532   if (Converter.Suppress)
5533     return ExprError();
5534 
5535   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5536   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5537     CXXConversionDecl *Conv =
5538         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5539     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5540     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5541   }
5542   return From;
5543 }
5544 
5545 static bool
5546 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5547                            Sema::ContextualImplicitConverter &Converter,
5548                            QualType T, bool HadMultipleCandidates,
5549                            UnresolvedSetImpl &ExplicitConversions) {
5550   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5551     DeclAccessPair Found = ExplicitConversions[0];
5552     CXXConversionDecl *Conversion =
5553         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5554 
5555     // The user probably meant to invoke the given explicit
5556     // conversion; use it.
5557     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5558     std::string TypeStr;
5559     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5560 
5561     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5562         << FixItHint::CreateInsertion(From->getLocStart(),
5563                                       "static_cast<" + TypeStr + ">(")
5564         << FixItHint::CreateInsertion(
5565                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5566     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5567 
5568     // If we aren't in a SFINAE context, build a call to the
5569     // explicit conversion function.
5570     if (SemaRef.isSFINAEContext())
5571       return true;
5572 
5573     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5574     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5575                                                        HadMultipleCandidates);
5576     if (Result.isInvalid())
5577       return true;
5578     // Record usage of conversion in an implicit cast.
5579     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5580                                     CK_UserDefinedConversion, Result.get(),
5581                                     nullptr, Result.get()->getValueKind());
5582   }
5583   return false;
5584 }
5585 
5586 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5587                              Sema::ContextualImplicitConverter &Converter,
5588                              QualType T, bool HadMultipleCandidates,
5589                              DeclAccessPair &Found) {
5590   CXXConversionDecl *Conversion =
5591       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5592   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5593 
5594   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5595   if (!Converter.SuppressConversion) {
5596     if (SemaRef.isSFINAEContext())
5597       return true;
5598 
5599     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5600         << From->getSourceRange();
5601   }
5602 
5603   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5604                                                      HadMultipleCandidates);
5605   if (Result.isInvalid())
5606     return true;
5607   // Record usage of conversion in an implicit cast.
5608   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5609                                   CK_UserDefinedConversion, Result.get(),
5610                                   nullptr, Result.get()->getValueKind());
5611   return false;
5612 }
5613 
5614 static ExprResult finishContextualImplicitConversion(
5615     Sema &SemaRef, SourceLocation Loc, Expr *From,
5616     Sema::ContextualImplicitConverter &Converter) {
5617   if (!Converter.match(From->getType()) && !Converter.Suppress)
5618     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5619         << From->getSourceRange();
5620 
5621   return SemaRef.DefaultLvalueConversion(From);
5622 }
5623 
5624 static void
5625 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5626                                   UnresolvedSetImpl &ViableConversions,
5627                                   OverloadCandidateSet &CandidateSet) {
5628   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5629     DeclAccessPair FoundDecl = ViableConversions[I];
5630     NamedDecl *D = FoundDecl.getDecl();
5631     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5632     if (isa<UsingShadowDecl>(D))
5633       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5634 
5635     CXXConversionDecl *Conv;
5636     FunctionTemplateDecl *ConvTemplate;
5637     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5638       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5639     else
5640       Conv = cast<CXXConversionDecl>(D);
5641 
5642     if (ConvTemplate)
5643       SemaRef.AddTemplateConversionCandidate(
5644         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5645         /*AllowObjCConversionOnExplicit=*/false);
5646     else
5647       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5648                                      ToType, CandidateSet,
5649                                      /*AllowObjCConversionOnExplicit=*/false);
5650   }
5651 }
5652 
5653 /// Attempt to convert the given expression to a type which is accepted
5654 /// by the given converter.
5655 ///
5656 /// This routine will attempt to convert an expression of class type to a
5657 /// type accepted by the specified converter. In C++11 and before, the class
5658 /// must have a single non-explicit conversion function converting to a matching
5659 /// type. In C++1y, there can be multiple such conversion functions, but only
5660 /// one target type.
5661 ///
5662 /// \param Loc The source location of the construct that requires the
5663 /// conversion.
5664 ///
5665 /// \param From The expression we're converting from.
5666 ///
5667 /// \param Converter Used to control and diagnose the conversion process.
5668 ///
5669 /// \returns The expression, converted to an integral or enumeration type if
5670 /// successful.
5671 ExprResult Sema::PerformContextualImplicitConversion(
5672     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5673   // We can't perform any more checking for type-dependent expressions.
5674   if (From->isTypeDependent())
5675     return From;
5676 
5677   // Process placeholders immediately.
5678   if (From->hasPlaceholderType()) {
5679     ExprResult result = CheckPlaceholderExpr(From);
5680     if (result.isInvalid())
5681       return result;
5682     From = result.get();
5683   }
5684 
5685   // If the expression already has a matching type, we're golden.
5686   QualType T = From->getType();
5687   if (Converter.match(T))
5688     return DefaultLvalueConversion(From);
5689 
5690   // FIXME: Check for missing '()' if T is a function type?
5691 
5692   // We can only perform contextual implicit conversions on objects of class
5693   // type.
5694   const RecordType *RecordTy = T->getAs<RecordType>();
5695   if (!RecordTy || !getLangOpts().CPlusPlus) {
5696     if (!Converter.Suppress)
5697       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5698     return From;
5699   }
5700 
5701   // We must have a complete class type.
5702   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5703     ContextualImplicitConverter &Converter;
5704     Expr *From;
5705 
5706     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5707         : Converter(Converter), From(From) {}
5708 
5709     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5710       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5711     }
5712   } IncompleteDiagnoser(Converter, From);
5713 
5714   if (Converter.Suppress ? !isCompleteType(Loc, T)
5715                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5716     return From;
5717 
5718   // Look for a conversion to an integral or enumeration type.
5719   UnresolvedSet<4>
5720       ViableConversions; // These are *potentially* viable in C++1y.
5721   UnresolvedSet<4> ExplicitConversions;
5722   const auto &Conversions =
5723       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5724 
5725   bool HadMultipleCandidates =
5726       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5727 
5728   // To check that there is only one target type, in C++1y:
5729   QualType ToType;
5730   bool HasUniqueTargetType = true;
5731 
5732   // Collect explicit or viable (potentially in C++1y) conversions.
5733   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5734     NamedDecl *D = (*I)->getUnderlyingDecl();
5735     CXXConversionDecl *Conversion;
5736     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5737     if (ConvTemplate) {
5738       if (getLangOpts().CPlusPlus14)
5739         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5740       else
5741         continue; // C++11 does not consider conversion operator templates(?).
5742     } else
5743       Conversion = cast<CXXConversionDecl>(D);
5744 
5745     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5746            "Conversion operator templates are considered potentially "
5747            "viable in C++1y");
5748 
5749     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5750     if (Converter.match(CurToType) || ConvTemplate) {
5751 
5752       if (Conversion->isExplicit()) {
5753         // FIXME: For C++1y, do we need this restriction?
5754         // cf. diagnoseNoViableConversion()
5755         if (!ConvTemplate)
5756           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5757       } else {
5758         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5759           if (ToType.isNull())
5760             ToType = CurToType.getUnqualifiedType();
5761           else if (HasUniqueTargetType &&
5762                    (CurToType.getUnqualifiedType() != ToType))
5763             HasUniqueTargetType = false;
5764         }
5765         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5766       }
5767     }
5768   }
5769 
5770   if (getLangOpts().CPlusPlus14) {
5771     // C++1y [conv]p6:
5772     // ... An expression e of class type E appearing in such a context
5773     // is said to be contextually implicitly converted to a specified
5774     // type T and is well-formed if and only if e can be implicitly
5775     // converted to a type T that is determined as follows: E is searched
5776     // for conversion functions whose return type is cv T or reference to
5777     // cv T such that T is allowed by the context. There shall be
5778     // exactly one such T.
5779 
5780     // If no unique T is found:
5781     if (ToType.isNull()) {
5782       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5783                                      HadMultipleCandidates,
5784                                      ExplicitConversions))
5785         return ExprError();
5786       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5787     }
5788 
5789     // If more than one unique Ts are found:
5790     if (!HasUniqueTargetType)
5791       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5792                                          ViableConversions);
5793 
5794     // If one unique T is found:
5795     // First, build a candidate set from the previously recorded
5796     // potentially viable conversions.
5797     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5798     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5799                                       CandidateSet);
5800 
5801     // Then, perform overload resolution over the candidate set.
5802     OverloadCandidateSet::iterator Best;
5803     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5804     case OR_Success: {
5805       // Apply this conversion.
5806       DeclAccessPair Found =
5807           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5808       if (recordConversion(*this, Loc, From, Converter, T,
5809                            HadMultipleCandidates, Found))
5810         return ExprError();
5811       break;
5812     }
5813     case OR_Ambiguous:
5814       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5815                                          ViableConversions);
5816     case OR_No_Viable_Function:
5817       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5818                                      HadMultipleCandidates,
5819                                      ExplicitConversions))
5820         return ExprError();
5821       LLVM_FALLTHROUGH;
5822     case OR_Deleted:
5823       // We'll complain below about a non-integral condition type.
5824       break;
5825     }
5826   } else {
5827     switch (ViableConversions.size()) {
5828     case 0: {
5829       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5830                                      HadMultipleCandidates,
5831                                      ExplicitConversions))
5832         return ExprError();
5833 
5834       // We'll complain below about a non-integral condition type.
5835       break;
5836     }
5837     case 1: {
5838       // Apply this conversion.
5839       DeclAccessPair Found = ViableConversions[0];
5840       if (recordConversion(*this, Loc, From, Converter, T,
5841                            HadMultipleCandidates, Found))
5842         return ExprError();
5843       break;
5844     }
5845     default:
5846       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5847                                          ViableConversions);
5848     }
5849   }
5850 
5851   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5852 }
5853 
5854 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5855 /// an acceptable non-member overloaded operator for a call whose
5856 /// arguments have types T1 (and, if non-empty, T2). This routine
5857 /// implements the check in C++ [over.match.oper]p3b2 concerning
5858 /// enumeration types.
5859 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5860                                                    FunctionDecl *Fn,
5861                                                    ArrayRef<Expr *> Args) {
5862   QualType T1 = Args[0]->getType();
5863   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5864 
5865   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5866     return true;
5867 
5868   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5869     return true;
5870 
5871   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5872   if (Proto->getNumParams() < 1)
5873     return false;
5874 
5875   if (T1->isEnumeralType()) {
5876     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5877     if (Context.hasSameUnqualifiedType(T1, ArgType))
5878       return true;
5879   }
5880 
5881   if (Proto->getNumParams() < 2)
5882     return false;
5883 
5884   if (!T2.isNull() && T2->isEnumeralType()) {
5885     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5886     if (Context.hasSameUnqualifiedType(T2, ArgType))
5887       return true;
5888   }
5889 
5890   return false;
5891 }
5892 
5893 /// AddOverloadCandidate - Adds the given function to the set of
5894 /// candidate functions, using the given function call arguments.  If
5895 /// @p SuppressUserConversions, then don't allow user-defined
5896 /// conversions via constructors or conversion operators.
5897 ///
5898 /// \param PartialOverloading true if we are performing "partial" overloading
5899 /// based on an incomplete set of function arguments. This feature is used by
5900 /// code completion.
5901 void
5902 Sema::AddOverloadCandidate(FunctionDecl *Function,
5903                            DeclAccessPair FoundDecl,
5904                            ArrayRef<Expr *> Args,
5905                            OverloadCandidateSet &CandidateSet,
5906                            bool SuppressUserConversions,
5907                            bool PartialOverloading,
5908                            bool AllowExplicit,
5909                            ConversionSequenceList EarlyConversions) {
5910   const FunctionProtoType *Proto
5911     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5912   assert(Proto && "Functions without a prototype cannot be overloaded");
5913   assert(!Function->getDescribedFunctionTemplate() &&
5914          "Use AddTemplateOverloadCandidate for function templates");
5915 
5916   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5917     if (!isa<CXXConstructorDecl>(Method)) {
5918       // If we get here, it's because we're calling a member function
5919       // that is named without a member access expression (e.g.,
5920       // "this->f") that was either written explicitly or created
5921       // implicitly. This can happen with a qualified call to a member
5922       // function, e.g., X::f(). We use an empty type for the implied
5923       // object argument (C++ [over.call.func]p3), and the acting context
5924       // is irrelevant.
5925       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5926                          Expr::Classification::makeSimpleLValue(), Args,
5927                          CandidateSet, SuppressUserConversions,
5928                          PartialOverloading, EarlyConversions);
5929       return;
5930     }
5931     // We treat a constructor like a non-member function, since its object
5932     // argument doesn't participate in overload resolution.
5933   }
5934 
5935   if (!CandidateSet.isNewCandidate(Function))
5936     return;
5937 
5938   // C++ [over.match.oper]p3:
5939   //   if no operand has a class type, only those non-member functions in the
5940   //   lookup set that have a first parameter of type T1 or "reference to
5941   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5942   //   is a right operand) a second parameter of type T2 or "reference to
5943   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5944   //   candidate functions.
5945   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5946       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5947     return;
5948 
5949   // C++11 [class.copy]p11: [DR1402]
5950   //   A defaulted move constructor that is defined as deleted is ignored by
5951   //   overload resolution.
5952   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5953   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5954       Constructor->isMoveConstructor())
5955     return;
5956 
5957   // Overload resolution is always an unevaluated context.
5958   EnterExpressionEvaluationContext Unevaluated(
5959       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5960 
5961   // Add this candidate
5962   OverloadCandidate &Candidate =
5963       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5964   Candidate.FoundDecl = FoundDecl;
5965   Candidate.Function = Function;
5966   Candidate.Viable = true;
5967   Candidate.IsSurrogate = false;
5968   Candidate.IgnoreObjectArgument = false;
5969   Candidate.ExplicitCallArguments = Args.size();
5970 
5971   if (Function->isMultiVersion() &&
5972       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5973     Candidate.Viable = false;
5974     Candidate.FailureKind = ovl_non_default_multiversion_function;
5975     return;
5976   }
5977 
5978   if (Constructor) {
5979     // C++ [class.copy]p3:
5980     //   A member function template is never instantiated to perform the copy
5981     //   of a class object to an object of its class type.
5982     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5983     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5984         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5985          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5986                        ClassType))) {
5987       Candidate.Viable = false;
5988       Candidate.FailureKind = ovl_fail_illegal_constructor;
5989       return;
5990     }
5991 
5992     // C++ [over.match.funcs]p8: (proposed DR resolution)
5993     //   A constructor inherited from class type C that has a first parameter
5994     //   of type "reference to P" (including such a constructor instantiated
5995     //   from a template) is excluded from the set of candidate functions when
5996     //   constructing an object of type cv D if the argument list has exactly
5997     //   one argument and D is reference-related to P and P is reference-related
5998     //   to C.
5999     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6000     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6001         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6002       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6003       QualType C = Context.getRecordType(Constructor->getParent());
6004       QualType D = Context.getRecordType(Shadow->getParent());
6005       SourceLocation Loc = Args.front()->getExprLoc();
6006       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6007           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6008         Candidate.Viable = false;
6009         Candidate.FailureKind = ovl_fail_inhctor_slice;
6010         return;
6011       }
6012     }
6013   }
6014 
6015   unsigned NumParams = Proto->getNumParams();
6016 
6017   // (C++ 13.3.2p2): A candidate function having fewer than m
6018   // parameters is viable only if it has an ellipsis in its parameter
6019   // list (8.3.5).
6020   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6021       !Proto->isVariadic()) {
6022     Candidate.Viable = false;
6023     Candidate.FailureKind = ovl_fail_too_many_arguments;
6024     return;
6025   }
6026 
6027   // (C++ 13.3.2p2): A candidate function having more than m parameters
6028   // is viable only if the (m+1)st parameter has a default argument
6029   // (8.3.6). For the purposes of overload resolution, the
6030   // parameter list is truncated on the right, so that there are
6031   // exactly m parameters.
6032   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6033   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6034     // Not enough arguments.
6035     Candidate.Viable = false;
6036     Candidate.FailureKind = ovl_fail_too_few_arguments;
6037     return;
6038   }
6039 
6040   // (CUDA B.1): Check for invalid calls between targets.
6041   if (getLangOpts().CUDA)
6042     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6043       // Skip the check for callers that are implicit members, because in this
6044       // case we may not yet know what the member's target is; the target is
6045       // inferred for the member automatically, based on the bases and fields of
6046       // the class.
6047       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6048         Candidate.Viable = false;
6049         Candidate.FailureKind = ovl_fail_bad_target;
6050         return;
6051       }
6052 
6053   // Determine the implicit conversion sequences for each of the
6054   // arguments.
6055   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6056     if (Candidate.Conversions[ArgIdx].isInitialized()) {
6057       // We already formed a conversion sequence for this parameter during
6058       // template argument deduction.
6059     } else if (ArgIdx < NumParams) {
6060       // (C++ 13.3.2p3): for F to be a viable function, there shall
6061       // exist for each argument an implicit conversion sequence
6062       // (13.3.3.1) that converts that argument to the corresponding
6063       // parameter of F.
6064       QualType ParamType = Proto->getParamType(ArgIdx);
6065       Candidate.Conversions[ArgIdx]
6066         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6067                                 SuppressUserConversions,
6068                                 /*InOverloadResolution=*/true,
6069                                 /*AllowObjCWritebackConversion=*/
6070                                   getLangOpts().ObjCAutoRefCount,
6071                                 AllowExplicit);
6072       if (Candidate.Conversions[ArgIdx].isBad()) {
6073         Candidate.Viable = false;
6074         Candidate.FailureKind = ovl_fail_bad_conversion;
6075         return;
6076       }
6077     } else {
6078       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6079       // argument for which there is no corresponding parameter is
6080       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6081       Candidate.Conversions[ArgIdx].setEllipsis();
6082     }
6083   }
6084 
6085   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6086     Candidate.Viable = false;
6087     Candidate.FailureKind = ovl_fail_enable_if;
6088     Candidate.DeductionFailure.Data = FailedAttr;
6089     return;
6090   }
6091 
6092   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6093     Candidate.Viable = false;
6094     Candidate.FailureKind = ovl_fail_ext_disabled;
6095     return;
6096   }
6097 }
6098 
6099 ObjCMethodDecl *
6100 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6101                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6102   if (Methods.size() <= 1)
6103     return nullptr;
6104 
6105   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6106     bool Match = true;
6107     ObjCMethodDecl *Method = Methods[b];
6108     unsigned NumNamedArgs = Sel.getNumArgs();
6109     // Method might have more arguments than selector indicates. This is due
6110     // to addition of c-style arguments in method.
6111     if (Method->param_size() > NumNamedArgs)
6112       NumNamedArgs = Method->param_size();
6113     if (Args.size() < NumNamedArgs)
6114       continue;
6115 
6116     for (unsigned i = 0; i < NumNamedArgs; i++) {
6117       // We can't do any type-checking on a type-dependent argument.
6118       if (Args[i]->isTypeDependent()) {
6119         Match = false;
6120         break;
6121       }
6122 
6123       ParmVarDecl *param = Method->parameters()[i];
6124       Expr *argExpr = Args[i];
6125       assert(argExpr && "SelectBestMethod(): missing expression");
6126 
6127       // Strip the unbridged-cast placeholder expression off unless it's
6128       // a consumed argument.
6129       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6130           !param->hasAttr<CFConsumedAttr>())
6131         argExpr = stripARCUnbridgedCast(argExpr);
6132 
6133       // If the parameter is __unknown_anytype, move on to the next method.
6134       if (param->getType() == Context.UnknownAnyTy) {
6135         Match = false;
6136         break;
6137       }
6138 
6139       ImplicitConversionSequence ConversionState
6140         = TryCopyInitialization(*this, argExpr, param->getType(),
6141                                 /*SuppressUserConversions*/false,
6142                                 /*InOverloadResolution=*/true,
6143                                 /*AllowObjCWritebackConversion=*/
6144                                 getLangOpts().ObjCAutoRefCount,
6145                                 /*AllowExplicit*/false);
6146       // This function looks for a reasonably-exact match, so we consider
6147       // incompatible pointer conversions to be a failure here.
6148       if (ConversionState.isBad() ||
6149           (ConversionState.isStandard() &&
6150            ConversionState.Standard.Second ==
6151                ICK_Incompatible_Pointer_Conversion)) {
6152         Match = false;
6153         break;
6154       }
6155     }
6156     // Promote additional arguments to variadic methods.
6157     if (Match && Method->isVariadic()) {
6158       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6159         if (Args[i]->isTypeDependent()) {
6160           Match = false;
6161           break;
6162         }
6163         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6164                                                           nullptr);
6165         if (Arg.isInvalid()) {
6166           Match = false;
6167           break;
6168         }
6169       }
6170     } else {
6171       // Check for extra arguments to non-variadic methods.
6172       if (Args.size() != NumNamedArgs)
6173         Match = false;
6174       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6175         // Special case when selectors have no argument. In this case, select
6176         // one with the most general result type of 'id'.
6177         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6178           QualType ReturnT = Methods[b]->getReturnType();
6179           if (ReturnT->isObjCIdType())
6180             return Methods[b];
6181         }
6182       }
6183     }
6184 
6185     if (Match)
6186       return Method;
6187   }
6188   return nullptr;
6189 }
6190 
6191 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6192 // enable_if is order-sensitive. As a result, we need to reverse things
6193 // sometimes. Size of 4 elements is arbitrary.
6194 static SmallVector<EnableIfAttr *, 4>
6195 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6196   SmallVector<EnableIfAttr *, 4> Result;
6197   if (!Function->hasAttrs())
6198     return Result;
6199 
6200   const auto &FuncAttrs = Function->getAttrs();
6201   for (Attr *Attr : FuncAttrs)
6202     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6203       Result.push_back(EnableIf);
6204 
6205   std::reverse(Result.begin(), Result.end());
6206   return Result;
6207 }
6208 
6209 static bool
6210 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6211                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6212                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6213                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6214   if (ThisArg) {
6215     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6216     assert(!isa<CXXConstructorDecl>(Method) &&
6217            "Shouldn't have `this` for ctors!");
6218     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6219     ExprResult R = S.PerformObjectArgumentInitialization(
6220         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6221     if (R.isInvalid())
6222       return false;
6223     ConvertedThis = R.get();
6224   } else {
6225     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6226       (void)MD;
6227       assert((MissingImplicitThis || MD->isStatic() ||
6228               isa<CXXConstructorDecl>(MD)) &&
6229              "Expected `this` for non-ctor instance methods");
6230     }
6231     ConvertedThis = nullptr;
6232   }
6233 
6234   // Ignore any variadic arguments. Converting them is pointless, since the
6235   // user can't refer to them in the function condition.
6236   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6237 
6238   // Convert the arguments.
6239   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6240     ExprResult R;
6241     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6242                                         S.Context, Function->getParamDecl(I)),
6243                                     SourceLocation(), Args[I]);
6244 
6245     if (R.isInvalid())
6246       return false;
6247 
6248     ConvertedArgs.push_back(R.get());
6249   }
6250 
6251   if (Trap.hasErrorOccurred())
6252     return false;
6253 
6254   // Push default arguments if needed.
6255   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6256     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6257       ParmVarDecl *P = Function->getParamDecl(i);
6258       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6259                          ? P->getUninstantiatedDefaultArg()
6260                          : P->getDefaultArg();
6261       // This can only happen in code completion, i.e. when PartialOverloading
6262       // is true.
6263       if (!DefArg)
6264         return false;
6265       ExprResult R =
6266           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6267                                           S.Context, Function->getParamDecl(i)),
6268                                       SourceLocation(), DefArg);
6269       if (R.isInvalid())
6270         return false;
6271       ConvertedArgs.push_back(R.get());
6272     }
6273 
6274     if (Trap.hasErrorOccurred())
6275       return false;
6276   }
6277   return true;
6278 }
6279 
6280 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6281                                   bool MissingImplicitThis) {
6282   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6283       getOrderedEnableIfAttrs(Function);
6284   if (EnableIfAttrs.empty())
6285     return nullptr;
6286 
6287   SFINAETrap Trap(*this);
6288   SmallVector<Expr *, 16> ConvertedArgs;
6289   // FIXME: We should look into making enable_if late-parsed.
6290   Expr *DiscardedThis;
6291   if (!convertArgsForAvailabilityChecks(
6292           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6293           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6294     return EnableIfAttrs[0];
6295 
6296   for (auto *EIA : EnableIfAttrs) {
6297     APValue Result;
6298     // FIXME: This doesn't consider value-dependent cases, because doing so is
6299     // very difficult. Ideally, we should handle them more gracefully.
6300     if (!EIA->getCond()->EvaluateWithSubstitution(
6301             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6302       return EIA;
6303 
6304     if (!Result.isInt() || !Result.getInt().getBoolValue())
6305       return EIA;
6306   }
6307   return nullptr;
6308 }
6309 
6310 template <typename CheckFn>
6311 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6312                                         bool ArgDependent, SourceLocation Loc,
6313                                         CheckFn &&IsSuccessful) {
6314   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6315   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6316     if (ArgDependent == DIA->getArgDependent())
6317       Attrs.push_back(DIA);
6318   }
6319 
6320   // Common case: No diagnose_if attributes, so we can quit early.
6321   if (Attrs.empty())
6322     return false;
6323 
6324   auto WarningBegin = std::stable_partition(
6325       Attrs.begin(), Attrs.end(),
6326       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6327 
6328   // Note that diagnose_if attributes are late-parsed, so they appear in the
6329   // correct order (unlike enable_if attributes).
6330   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6331                                IsSuccessful);
6332   if (ErrAttr != WarningBegin) {
6333     const DiagnoseIfAttr *DIA = *ErrAttr;
6334     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6335     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6336         << DIA->getParent() << DIA->getCond()->getSourceRange();
6337     return true;
6338   }
6339 
6340   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6341     if (IsSuccessful(DIA)) {
6342       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6343       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6344           << DIA->getParent() << DIA->getCond()->getSourceRange();
6345     }
6346 
6347   return false;
6348 }
6349 
6350 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6351                                                const Expr *ThisArg,
6352                                                ArrayRef<const Expr *> Args,
6353                                                SourceLocation Loc) {
6354   return diagnoseDiagnoseIfAttrsWith(
6355       *this, Function, /*ArgDependent=*/true, Loc,
6356       [&](const DiagnoseIfAttr *DIA) {
6357         APValue Result;
6358         // It's sane to use the same Args for any redecl of this function, since
6359         // EvaluateWithSubstitution only cares about the position of each
6360         // argument in the arg list, not the ParmVarDecl* it maps to.
6361         if (!DIA->getCond()->EvaluateWithSubstitution(
6362                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6363           return false;
6364         return Result.isInt() && Result.getInt().getBoolValue();
6365       });
6366 }
6367 
6368 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6369                                                  SourceLocation Loc) {
6370   return diagnoseDiagnoseIfAttrsWith(
6371       *this, ND, /*ArgDependent=*/false, Loc,
6372       [&](const DiagnoseIfAttr *DIA) {
6373         bool Result;
6374         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6375                Result;
6376       });
6377 }
6378 
6379 /// Add all of the function declarations in the given function set to
6380 /// the overload candidate set.
6381 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6382                                  ArrayRef<Expr *> Args,
6383                                  OverloadCandidateSet& CandidateSet,
6384                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6385                                  bool SuppressUserConversions,
6386                                  bool PartialOverloading,
6387                                  bool FirstArgumentIsBase) {
6388   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6389     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6390     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6391       ArrayRef<Expr *> FunctionArgs = Args;
6392       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6393         QualType ObjectType;
6394         Expr::Classification ObjectClassification;
6395         if (Args.size() > 0) {
6396           if (Expr *E = Args[0]) {
6397             // Use the explicit base to restrict the lookup:
6398             ObjectType = E->getType();
6399             ObjectClassification = E->Classify(Context);
6400           } // .. else there is an implit base.
6401           FunctionArgs = Args.slice(1);
6402         }
6403         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6404                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6405                            ObjectClassification, FunctionArgs, CandidateSet,
6406                            SuppressUserConversions, PartialOverloading);
6407       } else {
6408         // Slice the first argument (which is the base) when we access
6409         // static method as non-static
6410         if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6411                                              !isa<CXXConstructorDecl>(FD)))) {
6412           assert(cast<CXXMethodDecl>(FD)->isStatic());
6413           FunctionArgs = Args.slice(1);
6414         }
6415         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6416                              SuppressUserConversions, PartialOverloading);
6417       }
6418     } else {
6419       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6420       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6421           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6422         QualType ObjectType;
6423         Expr::Classification ObjectClassification;
6424         if (Expr *E = Args[0]) {
6425           // Use the explicit base to restrict the lookup:
6426           ObjectType = E->getType();
6427           ObjectClassification = E->Classify(Context);
6428         } // .. else there is an implit base.
6429         AddMethodTemplateCandidate(
6430             FunTmpl, F.getPair(),
6431             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6432             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6433             Args.slice(1), CandidateSet, SuppressUserConversions,
6434             PartialOverloading);
6435       } else {
6436         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6437                                      ExplicitTemplateArgs, Args,
6438                                      CandidateSet, SuppressUserConversions,
6439                                      PartialOverloading);
6440       }
6441     }
6442   }
6443 }
6444 
6445 /// AddMethodCandidate - Adds a named decl (which is some kind of
6446 /// method) as a method candidate to the given overload set.
6447 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6448                               QualType ObjectType,
6449                               Expr::Classification ObjectClassification,
6450                               ArrayRef<Expr *> Args,
6451                               OverloadCandidateSet& CandidateSet,
6452                               bool SuppressUserConversions) {
6453   NamedDecl *Decl = FoundDecl.getDecl();
6454   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6455 
6456   if (isa<UsingShadowDecl>(Decl))
6457     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6458 
6459   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6460     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6461            "Expected a member function template");
6462     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6463                                /*ExplicitArgs*/ nullptr, ObjectType,
6464                                ObjectClassification, Args, CandidateSet,
6465                                SuppressUserConversions);
6466   } else {
6467     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6468                        ObjectType, ObjectClassification, Args, CandidateSet,
6469                        SuppressUserConversions);
6470   }
6471 }
6472 
6473 /// AddMethodCandidate - Adds the given C++ member function to the set
6474 /// of candidate functions, using the given function call arguments
6475 /// and the object argument (@c Object). For example, in a call
6476 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6477 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6478 /// allow user-defined conversions via constructors or conversion
6479 /// operators.
6480 void
6481 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6482                          CXXRecordDecl *ActingContext, QualType ObjectType,
6483                          Expr::Classification ObjectClassification,
6484                          ArrayRef<Expr *> Args,
6485                          OverloadCandidateSet &CandidateSet,
6486                          bool SuppressUserConversions,
6487                          bool PartialOverloading,
6488                          ConversionSequenceList EarlyConversions) {
6489   const FunctionProtoType *Proto
6490     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6491   assert(Proto && "Methods without a prototype cannot be overloaded");
6492   assert(!isa<CXXConstructorDecl>(Method) &&
6493          "Use AddOverloadCandidate for constructors");
6494 
6495   if (!CandidateSet.isNewCandidate(Method))
6496     return;
6497 
6498   // C++11 [class.copy]p23: [DR1402]
6499   //   A defaulted move assignment operator that is defined as deleted is
6500   //   ignored by overload resolution.
6501   if (Method->isDefaulted() && Method->isDeleted() &&
6502       Method->isMoveAssignmentOperator())
6503     return;
6504 
6505   // Overload resolution is always an unevaluated context.
6506   EnterExpressionEvaluationContext Unevaluated(
6507       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6508 
6509   // Add this candidate
6510   OverloadCandidate &Candidate =
6511       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6512   Candidate.FoundDecl = FoundDecl;
6513   Candidate.Function = Method;
6514   Candidate.IsSurrogate = false;
6515   Candidate.IgnoreObjectArgument = false;
6516   Candidate.ExplicitCallArguments = Args.size();
6517 
6518   unsigned NumParams = Proto->getNumParams();
6519 
6520   // (C++ 13.3.2p2): A candidate function having fewer than m
6521   // parameters is viable only if it has an ellipsis in its parameter
6522   // list (8.3.5).
6523   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6524       !Proto->isVariadic()) {
6525     Candidate.Viable = false;
6526     Candidate.FailureKind = ovl_fail_too_many_arguments;
6527     return;
6528   }
6529 
6530   // (C++ 13.3.2p2): A candidate function having more than m parameters
6531   // is viable only if the (m+1)st parameter has a default argument
6532   // (8.3.6). For the purposes of overload resolution, the
6533   // parameter list is truncated on the right, so that there are
6534   // exactly m parameters.
6535   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6536   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6537     // Not enough arguments.
6538     Candidate.Viable = false;
6539     Candidate.FailureKind = ovl_fail_too_few_arguments;
6540     return;
6541   }
6542 
6543   Candidate.Viable = true;
6544 
6545   if (Method->isStatic() || ObjectType.isNull())
6546     // The implicit object argument is ignored.
6547     Candidate.IgnoreObjectArgument = true;
6548   else {
6549     // Determine the implicit conversion sequence for the object
6550     // parameter.
6551     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6552         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6553         Method, ActingContext);
6554     if (Candidate.Conversions[0].isBad()) {
6555       Candidate.Viable = false;
6556       Candidate.FailureKind = ovl_fail_bad_conversion;
6557       return;
6558     }
6559   }
6560 
6561   // (CUDA B.1): Check for invalid calls between targets.
6562   if (getLangOpts().CUDA)
6563     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6564       if (!IsAllowedCUDACall(Caller, Method)) {
6565         Candidate.Viable = false;
6566         Candidate.FailureKind = ovl_fail_bad_target;
6567         return;
6568       }
6569 
6570   // Determine the implicit conversion sequences for each of the
6571   // arguments.
6572   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6573     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6574       // We already formed a conversion sequence for this parameter during
6575       // template argument deduction.
6576     } else if (ArgIdx < NumParams) {
6577       // (C++ 13.3.2p3): for F to be a viable function, there shall
6578       // exist for each argument an implicit conversion sequence
6579       // (13.3.3.1) that converts that argument to the corresponding
6580       // parameter of F.
6581       QualType ParamType = Proto->getParamType(ArgIdx);
6582       Candidate.Conversions[ArgIdx + 1]
6583         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6584                                 SuppressUserConversions,
6585                                 /*InOverloadResolution=*/true,
6586                                 /*AllowObjCWritebackConversion=*/
6587                                   getLangOpts().ObjCAutoRefCount);
6588       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6589         Candidate.Viable = false;
6590         Candidate.FailureKind = ovl_fail_bad_conversion;
6591         return;
6592       }
6593     } else {
6594       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6595       // argument for which there is no corresponding parameter is
6596       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6597       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6598     }
6599   }
6600 
6601   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6602     Candidate.Viable = false;
6603     Candidate.FailureKind = ovl_fail_enable_if;
6604     Candidate.DeductionFailure.Data = FailedAttr;
6605     return;
6606   }
6607 
6608   if (Method->isMultiVersion() &&
6609       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6610     Candidate.Viable = false;
6611     Candidate.FailureKind = ovl_non_default_multiversion_function;
6612   }
6613 }
6614 
6615 /// Add a C++ member function template as a candidate to the candidate
6616 /// set, using template argument deduction to produce an appropriate member
6617 /// function template specialization.
6618 void
6619 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6620                                  DeclAccessPair FoundDecl,
6621                                  CXXRecordDecl *ActingContext,
6622                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6623                                  QualType ObjectType,
6624                                  Expr::Classification ObjectClassification,
6625                                  ArrayRef<Expr *> Args,
6626                                  OverloadCandidateSet& CandidateSet,
6627                                  bool SuppressUserConversions,
6628                                  bool PartialOverloading) {
6629   if (!CandidateSet.isNewCandidate(MethodTmpl))
6630     return;
6631 
6632   // C++ [over.match.funcs]p7:
6633   //   In each case where a candidate is a function template, candidate
6634   //   function template specializations are generated using template argument
6635   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6636   //   candidate functions in the usual way.113) A given name can refer to one
6637   //   or more function templates and also to a set of overloaded non-template
6638   //   functions. In such a case, the candidate functions generated from each
6639   //   function template are combined with the set of non-template candidate
6640   //   functions.
6641   TemplateDeductionInfo Info(CandidateSet.getLocation());
6642   FunctionDecl *Specialization = nullptr;
6643   ConversionSequenceList Conversions;
6644   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6645           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6646           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6647             return CheckNonDependentConversions(
6648                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6649                 SuppressUserConversions, ActingContext, ObjectType,
6650                 ObjectClassification);
6651           })) {
6652     OverloadCandidate &Candidate =
6653         CandidateSet.addCandidate(Conversions.size(), Conversions);
6654     Candidate.FoundDecl = FoundDecl;
6655     Candidate.Function = MethodTmpl->getTemplatedDecl();
6656     Candidate.Viable = false;
6657     Candidate.IsSurrogate = false;
6658     Candidate.IgnoreObjectArgument =
6659         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6660         ObjectType.isNull();
6661     Candidate.ExplicitCallArguments = Args.size();
6662     if (Result == TDK_NonDependentConversionFailure)
6663       Candidate.FailureKind = ovl_fail_bad_conversion;
6664     else {
6665       Candidate.FailureKind = ovl_fail_bad_deduction;
6666       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6667                                                             Info);
6668     }
6669     return;
6670   }
6671 
6672   // Add the function template specialization produced by template argument
6673   // deduction as a candidate.
6674   assert(Specialization && "Missing member function template specialization?");
6675   assert(isa<CXXMethodDecl>(Specialization) &&
6676          "Specialization is not a member function?");
6677   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6678                      ActingContext, ObjectType, ObjectClassification, Args,
6679                      CandidateSet, SuppressUserConversions, PartialOverloading,
6680                      Conversions);
6681 }
6682 
6683 /// Add a C++ function template specialization as a candidate
6684 /// in the candidate set, using template argument deduction to produce
6685 /// an appropriate function template specialization.
6686 void
6687 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6688                                    DeclAccessPair FoundDecl,
6689                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6690                                    ArrayRef<Expr *> Args,
6691                                    OverloadCandidateSet& CandidateSet,
6692                                    bool SuppressUserConversions,
6693                                    bool PartialOverloading) {
6694   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6695     return;
6696 
6697   // C++ [over.match.funcs]p7:
6698   //   In each case where a candidate is a function template, candidate
6699   //   function template specializations are generated using template argument
6700   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6701   //   candidate functions in the usual way.113) A given name can refer to one
6702   //   or more function templates and also to a set of overloaded non-template
6703   //   functions. In such a case, the candidate functions generated from each
6704   //   function template are combined with the set of non-template candidate
6705   //   functions.
6706   TemplateDeductionInfo Info(CandidateSet.getLocation());
6707   FunctionDecl *Specialization = nullptr;
6708   ConversionSequenceList Conversions;
6709   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6710           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6711           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6712             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6713                                                 Args, CandidateSet, Conversions,
6714                                                 SuppressUserConversions);
6715           })) {
6716     OverloadCandidate &Candidate =
6717         CandidateSet.addCandidate(Conversions.size(), Conversions);
6718     Candidate.FoundDecl = FoundDecl;
6719     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6720     Candidate.Viable = false;
6721     Candidate.IsSurrogate = false;
6722     // Ignore the object argument if there is one, since we don't have an object
6723     // type.
6724     Candidate.IgnoreObjectArgument =
6725         isa<CXXMethodDecl>(Candidate.Function) &&
6726         !isa<CXXConstructorDecl>(Candidate.Function);
6727     Candidate.ExplicitCallArguments = Args.size();
6728     if (Result == TDK_NonDependentConversionFailure)
6729       Candidate.FailureKind = ovl_fail_bad_conversion;
6730     else {
6731       Candidate.FailureKind = ovl_fail_bad_deduction;
6732       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6733                                                             Info);
6734     }
6735     return;
6736   }
6737 
6738   // Add the function template specialization produced by template argument
6739   // deduction as a candidate.
6740   assert(Specialization && "Missing function template specialization?");
6741   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6742                        SuppressUserConversions, PartialOverloading,
6743                        /*AllowExplicit*/false, Conversions);
6744 }
6745 
6746 /// Check that implicit conversion sequences can be formed for each argument
6747 /// whose corresponding parameter has a non-dependent type, per DR1391's
6748 /// [temp.deduct.call]p10.
6749 bool Sema::CheckNonDependentConversions(
6750     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6751     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6752     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6753     CXXRecordDecl *ActingContext, QualType ObjectType,
6754     Expr::Classification ObjectClassification) {
6755   // FIXME: The cases in which we allow explicit conversions for constructor
6756   // arguments never consider calling a constructor template. It's not clear
6757   // that is correct.
6758   const bool AllowExplicit = false;
6759 
6760   auto *FD = FunctionTemplate->getTemplatedDecl();
6761   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6762   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6763   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6764 
6765   Conversions =
6766       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6767 
6768   // Overload resolution is always an unevaluated context.
6769   EnterExpressionEvaluationContext Unevaluated(
6770       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6771 
6772   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6773   // require that, but this check should never result in a hard error, and
6774   // overload resolution is permitted to sidestep instantiations.
6775   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6776       !ObjectType.isNull()) {
6777     Conversions[0] = TryObjectArgumentInitialization(
6778         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6779         Method, ActingContext);
6780     if (Conversions[0].isBad())
6781       return true;
6782   }
6783 
6784   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6785        ++I) {
6786     QualType ParamType = ParamTypes[I];
6787     if (!ParamType->isDependentType()) {
6788       Conversions[ThisConversions + I]
6789         = TryCopyInitialization(*this, Args[I], ParamType,
6790                                 SuppressUserConversions,
6791                                 /*InOverloadResolution=*/true,
6792                                 /*AllowObjCWritebackConversion=*/
6793                                   getLangOpts().ObjCAutoRefCount,
6794                                 AllowExplicit);
6795       if (Conversions[ThisConversions + I].isBad())
6796         return true;
6797     }
6798   }
6799 
6800   return false;
6801 }
6802 
6803 /// Determine whether this is an allowable conversion from the result
6804 /// of an explicit conversion operator to the expected type, per C++
6805 /// [over.match.conv]p1 and [over.match.ref]p1.
6806 ///
6807 /// \param ConvType The return type of the conversion function.
6808 ///
6809 /// \param ToType The type we are converting to.
6810 ///
6811 /// \param AllowObjCPointerConversion Allow a conversion from one
6812 /// Objective-C pointer to another.
6813 ///
6814 /// \returns true if the conversion is allowable, false otherwise.
6815 static bool isAllowableExplicitConversion(Sema &S,
6816                                           QualType ConvType, QualType ToType,
6817                                           bool AllowObjCPointerConversion) {
6818   QualType ToNonRefType = ToType.getNonReferenceType();
6819 
6820   // Easy case: the types are the same.
6821   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6822     return true;
6823 
6824   // Allow qualification conversions.
6825   bool ObjCLifetimeConversion;
6826   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6827                                   ObjCLifetimeConversion))
6828     return true;
6829 
6830   // If we're not allowed to consider Objective-C pointer conversions,
6831   // we're done.
6832   if (!AllowObjCPointerConversion)
6833     return false;
6834 
6835   // Is this an Objective-C pointer conversion?
6836   bool IncompatibleObjC = false;
6837   QualType ConvertedType;
6838   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6839                                    IncompatibleObjC);
6840 }
6841 
6842 /// AddConversionCandidate - Add a C++ conversion function as a
6843 /// candidate in the candidate set (C++ [over.match.conv],
6844 /// C++ [over.match.copy]). From is the expression we're converting from,
6845 /// and ToType is the type that we're eventually trying to convert to
6846 /// (which may or may not be the same type as the type that the
6847 /// conversion function produces).
6848 void
6849 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6850                              DeclAccessPair FoundDecl,
6851                              CXXRecordDecl *ActingContext,
6852                              Expr *From, QualType ToType,
6853                              OverloadCandidateSet& CandidateSet,
6854                              bool AllowObjCConversionOnExplicit,
6855                              bool AllowResultConversion) {
6856   assert(!Conversion->getDescribedFunctionTemplate() &&
6857          "Conversion function templates use AddTemplateConversionCandidate");
6858   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6859   if (!CandidateSet.isNewCandidate(Conversion))
6860     return;
6861 
6862   // If the conversion function has an undeduced return type, trigger its
6863   // deduction now.
6864   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6865     if (DeduceReturnType(Conversion, From->getExprLoc()))
6866       return;
6867     ConvType = Conversion->getConversionType().getNonReferenceType();
6868   }
6869 
6870   // If we don't allow any conversion of the result type, ignore conversion
6871   // functions that don't convert to exactly (possibly cv-qualified) T.
6872   if (!AllowResultConversion &&
6873       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6874     return;
6875 
6876   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6877   // operator is only a candidate if its return type is the target type or
6878   // can be converted to the target type with a qualification conversion.
6879   if (Conversion->isExplicit() &&
6880       !isAllowableExplicitConversion(*this, ConvType, ToType,
6881                                      AllowObjCConversionOnExplicit))
6882     return;
6883 
6884   // Overload resolution is always an unevaluated context.
6885   EnterExpressionEvaluationContext Unevaluated(
6886       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6887 
6888   // Add this candidate
6889   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6890   Candidate.FoundDecl = FoundDecl;
6891   Candidate.Function = Conversion;
6892   Candidate.IsSurrogate = false;
6893   Candidate.IgnoreObjectArgument = false;
6894   Candidate.FinalConversion.setAsIdentityConversion();
6895   Candidate.FinalConversion.setFromType(ConvType);
6896   Candidate.FinalConversion.setAllToTypes(ToType);
6897   Candidate.Viable = true;
6898   Candidate.ExplicitCallArguments = 1;
6899 
6900   // C++ [over.match.funcs]p4:
6901   //   For conversion functions, the function is considered to be a member of
6902   //   the class of the implicit implied object argument for the purpose of
6903   //   defining the type of the implicit object parameter.
6904   //
6905   // Determine the implicit conversion sequence for the implicit
6906   // object parameter.
6907   QualType ImplicitParamType = From->getType();
6908   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6909     ImplicitParamType = FromPtrType->getPointeeType();
6910   CXXRecordDecl *ConversionContext
6911     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6912 
6913   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6914       *this, CandidateSet.getLocation(), From->getType(),
6915       From->Classify(Context), Conversion, ConversionContext);
6916 
6917   if (Candidate.Conversions[0].isBad()) {
6918     Candidate.Viable = false;
6919     Candidate.FailureKind = ovl_fail_bad_conversion;
6920     return;
6921   }
6922 
6923   // We won't go through a user-defined type conversion function to convert a
6924   // derived to base as such conversions are given Conversion Rank. They only
6925   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6926   QualType FromCanon
6927     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6928   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6929   if (FromCanon == ToCanon ||
6930       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6931     Candidate.Viable = false;
6932     Candidate.FailureKind = ovl_fail_trivial_conversion;
6933     return;
6934   }
6935 
6936   // To determine what the conversion from the result of calling the
6937   // conversion function to the type we're eventually trying to
6938   // convert to (ToType), we need to synthesize a call to the
6939   // conversion function and attempt copy initialization from it. This
6940   // makes sure that we get the right semantics with respect to
6941   // lvalues/rvalues and the type. Fortunately, we can allocate this
6942   // call on the stack and we don't need its arguments to be
6943   // well-formed.
6944   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6945                             VK_LValue, From->getLocStart());
6946   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6947                                 Context.getPointerType(Conversion->getType()),
6948                                 CK_FunctionToPointerDecay,
6949                                 &ConversionRef, VK_RValue);
6950 
6951   QualType ConversionType = Conversion->getConversionType();
6952   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6953     Candidate.Viable = false;
6954     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6955     return;
6956   }
6957 
6958   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6959 
6960   // Note that it is safe to allocate CallExpr on the stack here because
6961   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6962   // allocator).
6963   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6964   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6965                 From->getLocStart());
6966   ImplicitConversionSequence ICS =
6967     TryCopyInitialization(*this, &Call, ToType,
6968                           /*SuppressUserConversions=*/true,
6969                           /*InOverloadResolution=*/false,
6970                           /*AllowObjCWritebackConversion=*/false);
6971 
6972   switch (ICS.getKind()) {
6973   case ImplicitConversionSequence::StandardConversion:
6974     Candidate.FinalConversion = ICS.Standard;
6975 
6976     // C++ [over.ics.user]p3:
6977     //   If the user-defined conversion is specified by a specialization of a
6978     //   conversion function template, the second standard conversion sequence
6979     //   shall have exact match rank.
6980     if (Conversion->getPrimaryTemplate() &&
6981         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6982       Candidate.Viable = false;
6983       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6984       return;
6985     }
6986 
6987     // C++0x [dcl.init.ref]p5:
6988     //    In the second case, if the reference is an rvalue reference and
6989     //    the second standard conversion sequence of the user-defined
6990     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6991     //    program is ill-formed.
6992     if (ToType->isRValueReferenceType() &&
6993         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6994       Candidate.Viable = false;
6995       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6996       return;
6997     }
6998     break;
6999 
7000   case ImplicitConversionSequence::BadConversion:
7001     Candidate.Viable = false;
7002     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7003     return;
7004 
7005   default:
7006     llvm_unreachable(
7007            "Can only end up with a standard conversion sequence or failure");
7008   }
7009 
7010   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7011     Candidate.Viable = false;
7012     Candidate.FailureKind = ovl_fail_enable_if;
7013     Candidate.DeductionFailure.Data = FailedAttr;
7014     return;
7015   }
7016 
7017   if (Conversion->isMultiVersion() &&
7018       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7019     Candidate.Viable = false;
7020     Candidate.FailureKind = ovl_non_default_multiversion_function;
7021   }
7022 }
7023 
7024 /// Adds a conversion function template specialization
7025 /// candidate to the overload set, using template argument deduction
7026 /// to deduce the template arguments of the conversion function
7027 /// template from the type that we are converting to (C++
7028 /// [temp.deduct.conv]).
7029 void
7030 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7031                                      DeclAccessPair FoundDecl,
7032                                      CXXRecordDecl *ActingDC,
7033                                      Expr *From, QualType ToType,
7034                                      OverloadCandidateSet &CandidateSet,
7035                                      bool AllowObjCConversionOnExplicit,
7036                                      bool AllowResultConversion) {
7037   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7038          "Only conversion function templates permitted here");
7039 
7040   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7041     return;
7042 
7043   TemplateDeductionInfo Info(CandidateSet.getLocation());
7044   CXXConversionDecl *Specialization = nullptr;
7045   if (TemplateDeductionResult Result
7046         = DeduceTemplateArguments(FunctionTemplate, ToType,
7047                                   Specialization, Info)) {
7048     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7049     Candidate.FoundDecl = FoundDecl;
7050     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7051     Candidate.Viable = false;
7052     Candidate.FailureKind = ovl_fail_bad_deduction;
7053     Candidate.IsSurrogate = false;
7054     Candidate.IgnoreObjectArgument = false;
7055     Candidate.ExplicitCallArguments = 1;
7056     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7057                                                           Info);
7058     return;
7059   }
7060 
7061   // Add the conversion function template specialization produced by
7062   // template argument deduction as a candidate.
7063   assert(Specialization && "Missing function template specialization?");
7064   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7065                          CandidateSet, AllowObjCConversionOnExplicit,
7066                          AllowResultConversion);
7067 }
7068 
7069 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7070 /// converts the given @c Object to a function pointer via the
7071 /// conversion function @c Conversion, and then attempts to call it
7072 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7073 /// the type of function that we'll eventually be calling.
7074 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7075                                  DeclAccessPair FoundDecl,
7076                                  CXXRecordDecl *ActingContext,
7077                                  const FunctionProtoType *Proto,
7078                                  Expr *Object,
7079                                  ArrayRef<Expr *> Args,
7080                                  OverloadCandidateSet& CandidateSet) {
7081   if (!CandidateSet.isNewCandidate(Conversion))
7082     return;
7083 
7084   // Overload resolution is always an unevaluated context.
7085   EnterExpressionEvaluationContext Unevaluated(
7086       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7087 
7088   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7089   Candidate.FoundDecl = FoundDecl;
7090   Candidate.Function = nullptr;
7091   Candidate.Surrogate = Conversion;
7092   Candidate.Viable = true;
7093   Candidate.IsSurrogate = true;
7094   Candidate.IgnoreObjectArgument = false;
7095   Candidate.ExplicitCallArguments = Args.size();
7096 
7097   // Determine the implicit conversion sequence for the implicit
7098   // object parameter.
7099   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7100       *this, CandidateSet.getLocation(), Object->getType(),
7101       Object->Classify(Context), Conversion, ActingContext);
7102   if (ObjectInit.isBad()) {
7103     Candidate.Viable = false;
7104     Candidate.FailureKind = ovl_fail_bad_conversion;
7105     Candidate.Conversions[0] = ObjectInit;
7106     return;
7107   }
7108 
7109   // The first conversion is actually a user-defined conversion whose
7110   // first conversion is ObjectInit's standard conversion (which is
7111   // effectively a reference binding). Record it as such.
7112   Candidate.Conversions[0].setUserDefined();
7113   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7114   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7115   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7116   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7117   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7118   Candidate.Conversions[0].UserDefined.After
7119     = Candidate.Conversions[0].UserDefined.Before;
7120   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7121 
7122   // Find the
7123   unsigned NumParams = Proto->getNumParams();
7124 
7125   // (C++ 13.3.2p2): A candidate function having fewer than m
7126   // parameters is viable only if it has an ellipsis in its parameter
7127   // list (8.3.5).
7128   if (Args.size() > NumParams && !Proto->isVariadic()) {
7129     Candidate.Viable = false;
7130     Candidate.FailureKind = ovl_fail_too_many_arguments;
7131     return;
7132   }
7133 
7134   // Function types don't have any default arguments, so just check if
7135   // we have enough arguments.
7136   if (Args.size() < NumParams) {
7137     // Not enough arguments.
7138     Candidate.Viable = false;
7139     Candidate.FailureKind = ovl_fail_too_few_arguments;
7140     return;
7141   }
7142 
7143   // Determine the implicit conversion sequences for each of the
7144   // arguments.
7145   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7146     if (ArgIdx < NumParams) {
7147       // (C++ 13.3.2p3): for F to be a viable function, there shall
7148       // exist for each argument an implicit conversion sequence
7149       // (13.3.3.1) that converts that argument to the corresponding
7150       // parameter of F.
7151       QualType ParamType = Proto->getParamType(ArgIdx);
7152       Candidate.Conversions[ArgIdx + 1]
7153         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7154                                 /*SuppressUserConversions=*/false,
7155                                 /*InOverloadResolution=*/false,
7156                                 /*AllowObjCWritebackConversion=*/
7157                                   getLangOpts().ObjCAutoRefCount);
7158       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7159         Candidate.Viable = false;
7160         Candidate.FailureKind = ovl_fail_bad_conversion;
7161         return;
7162       }
7163     } else {
7164       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7165       // argument for which there is no corresponding parameter is
7166       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7167       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7168     }
7169   }
7170 
7171   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7172     Candidate.Viable = false;
7173     Candidate.FailureKind = ovl_fail_enable_if;
7174     Candidate.DeductionFailure.Data = FailedAttr;
7175     return;
7176   }
7177 }
7178 
7179 /// Add overload candidates for overloaded operators that are
7180 /// member functions.
7181 ///
7182 /// Add the overloaded operator candidates that are member functions
7183 /// for the operator Op that was used in an operator expression such
7184 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7185 /// CandidateSet will store the added overload candidates. (C++
7186 /// [over.match.oper]).
7187 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7188                                        SourceLocation OpLoc,
7189                                        ArrayRef<Expr *> Args,
7190                                        OverloadCandidateSet& CandidateSet,
7191                                        SourceRange OpRange) {
7192   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7193 
7194   // C++ [over.match.oper]p3:
7195   //   For a unary operator @ with an operand of a type whose
7196   //   cv-unqualified version is T1, and for a binary operator @ with
7197   //   a left operand of a type whose cv-unqualified version is T1 and
7198   //   a right operand of a type whose cv-unqualified version is T2,
7199   //   three sets of candidate functions, designated member
7200   //   candidates, non-member candidates and built-in candidates, are
7201   //   constructed as follows:
7202   QualType T1 = Args[0]->getType();
7203 
7204   //     -- If T1 is a complete class type or a class currently being
7205   //        defined, the set of member candidates is the result of the
7206   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7207   //        the set of member candidates is empty.
7208   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7209     // Complete the type if it can be completed.
7210     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7211       return;
7212     // If the type is neither complete nor being defined, bail out now.
7213     if (!T1Rec->getDecl()->getDefinition())
7214       return;
7215 
7216     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7217     LookupQualifiedName(Operators, T1Rec->getDecl());
7218     Operators.suppressDiagnostics();
7219 
7220     for (LookupResult::iterator Oper = Operators.begin(),
7221                              OperEnd = Operators.end();
7222          Oper != OperEnd;
7223          ++Oper)
7224       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7225                          Args[0]->Classify(Context), Args.slice(1),
7226                          CandidateSet, /*SuppressUserConversions=*/false);
7227   }
7228 }
7229 
7230 /// AddBuiltinCandidate - Add a candidate for a built-in
7231 /// operator. ResultTy and ParamTys are the result and parameter types
7232 /// of the built-in candidate, respectively. Args and NumArgs are the
7233 /// arguments being passed to the candidate. IsAssignmentOperator
7234 /// should be true when this built-in candidate is an assignment
7235 /// operator. NumContextualBoolArguments is the number of arguments
7236 /// (at the beginning of the argument list) that will be contextually
7237 /// converted to bool.
7238 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7239                                OverloadCandidateSet& CandidateSet,
7240                                bool IsAssignmentOperator,
7241                                unsigned NumContextualBoolArguments) {
7242   // Overload resolution is always an unevaluated context.
7243   EnterExpressionEvaluationContext Unevaluated(
7244       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7245 
7246   // Add this candidate
7247   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7248   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7249   Candidate.Function = nullptr;
7250   Candidate.IsSurrogate = false;
7251   Candidate.IgnoreObjectArgument = false;
7252   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7253 
7254   // Determine the implicit conversion sequences for each of the
7255   // arguments.
7256   Candidate.Viable = true;
7257   Candidate.ExplicitCallArguments = Args.size();
7258   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7259     // C++ [over.match.oper]p4:
7260     //   For the built-in assignment operators, conversions of the
7261     //   left operand are restricted as follows:
7262     //     -- no temporaries are introduced to hold the left operand, and
7263     //     -- no user-defined conversions are applied to the left
7264     //        operand to achieve a type match with the left-most
7265     //        parameter of a built-in candidate.
7266     //
7267     // We block these conversions by turning off user-defined
7268     // conversions, since that is the only way that initialization of
7269     // a reference to a non-class type can occur from something that
7270     // is not of the same type.
7271     if (ArgIdx < NumContextualBoolArguments) {
7272       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7273              "Contextual conversion to bool requires bool type");
7274       Candidate.Conversions[ArgIdx]
7275         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7276     } else {
7277       Candidate.Conversions[ArgIdx]
7278         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7279                                 ArgIdx == 0 && IsAssignmentOperator,
7280                                 /*InOverloadResolution=*/false,
7281                                 /*AllowObjCWritebackConversion=*/
7282                                   getLangOpts().ObjCAutoRefCount);
7283     }
7284     if (Candidate.Conversions[ArgIdx].isBad()) {
7285       Candidate.Viable = false;
7286       Candidate.FailureKind = ovl_fail_bad_conversion;
7287       break;
7288     }
7289   }
7290 }
7291 
7292 namespace {
7293 
7294 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7295 /// candidate operator functions for built-in operators (C++
7296 /// [over.built]). The types are separated into pointer types and
7297 /// enumeration types.
7298 class BuiltinCandidateTypeSet  {
7299   /// TypeSet - A set of types.
7300   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7301                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7302 
7303   /// PointerTypes - The set of pointer types that will be used in the
7304   /// built-in candidates.
7305   TypeSet PointerTypes;
7306 
7307   /// MemberPointerTypes - The set of member pointer types that will be
7308   /// used in the built-in candidates.
7309   TypeSet MemberPointerTypes;
7310 
7311   /// EnumerationTypes - The set of enumeration types that will be
7312   /// used in the built-in candidates.
7313   TypeSet EnumerationTypes;
7314 
7315   /// The set of vector types that will be used in the built-in
7316   /// candidates.
7317   TypeSet VectorTypes;
7318 
7319   /// A flag indicating non-record types are viable candidates
7320   bool HasNonRecordTypes;
7321 
7322   /// A flag indicating whether either arithmetic or enumeration types
7323   /// were present in the candidate set.
7324   bool HasArithmeticOrEnumeralTypes;
7325 
7326   /// A flag indicating whether the nullptr type was present in the
7327   /// candidate set.
7328   bool HasNullPtrType;
7329 
7330   /// Sema - The semantic analysis instance where we are building the
7331   /// candidate type set.
7332   Sema &SemaRef;
7333 
7334   /// Context - The AST context in which we will build the type sets.
7335   ASTContext &Context;
7336 
7337   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7338                                                const Qualifiers &VisibleQuals);
7339   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7340 
7341 public:
7342   /// iterator - Iterates through the types that are part of the set.
7343   typedef TypeSet::iterator iterator;
7344 
7345   BuiltinCandidateTypeSet(Sema &SemaRef)
7346     : HasNonRecordTypes(false),
7347       HasArithmeticOrEnumeralTypes(false),
7348       HasNullPtrType(false),
7349       SemaRef(SemaRef),
7350       Context(SemaRef.Context) { }
7351 
7352   void AddTypesConvertedFrom(QualType Ty,
7353                              SourceLocation Loc,
7354                              bool AllowUserConversions,
7355                              bool AllowExplicitConversions,
7356                              const Qualifiers &VisibleTypeConversionsQuals);
7357 
7358   /// pointer_begin - First pointer type found;
7359   iterator pointer_begin() { return PointerTypes.begin(); }
7360 
7361   /// pointer_end - Past the last pointer type found;
7362   iterator pointer_end() { return PointerTypes.end(); }
7363 
7364   /// member_pointer_begin - First member pointer type found;
7365   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7366 
7367   /// member_pointer_end - Past the last member pointer type found;
7368   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7369 
7370   /// enumeration_begin - First enumeration type found;
7371   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7372 
7373   /// enumeration_end - Past the last enumeration type found;
7374   iterator enumeration_end() { return EnumerationTypes.end(); }
7375 
7376   iterator vector_begin() { return VectorTypes.begin(); }
7377   iterator vector_end() { return VectorTypes.end(); }
7378 
7379   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7380   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7381   bool hasNullPtrType() const { return HasNullPtrType; }
7382 };
7383 
7384 } // end anonymous namespace
7385 
7386 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7387 /// the set of pointer types along with any more-qualified variants of
7388 /// that type. For example, if @p Ty is "int const *", this routine
7389 /// will add "int const *", "int const volatile *", "int const
7390 /// restrict *", and "int const volatile restrict *" to the set of
7391 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7392 /// false otherwise.
7393 ///
7394 /// FIXME: what to do about extended qualifiers?
7395 bool
7396 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7397                                              const Qualifiers &VisibleQuals) {
7398 
7399   // Insert this type.
7400   if (!PointerTypes.insert(Ty))
7401     return false;
7402 
7403   QualType PointeeTy;
7404   const PointerType *PointerTy = Ty->getAs<PointerType>();
7405   bool buildObjCPtr = false;
7406   if (!PointerTy) {
7407     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7408     PointeeTy = PTy->getPointeeType();
7409     buildObjCPtr = true;
7410   } else {
7411     PointeeTy = PointerTy->getPointeeType();
7412   }
7413 
7414   // Don't add qualified variants of arrays. For one, they're not allowed
7415   // (the qualifier would sink to the element type), and for another, the
7416   // only overload situation where it matters is subscript or pointer +- int,
7417   // and those shouldn't have qualifier variants anyway.
7418   if (PointeeTy->isArrayType())
7419     return true;
7420 
7421   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7422   bool hasVolatile = VisibleQuals.hasVolatile();
7423   bool hasRestrict = VisibleQuals.hasRestrict();
7424 
7425   // Iterate through all strict supersets of BaseCVR.
7426   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7427     if ((CVR | BaseCVR) != CVR) continue;
7428     // Skip over volatile if no volatile found anywhere in the types.
7429     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7430 
7431     // Skip over restrict if no restrict found anywhere in the types, or if
7432     // the type cannot be restrict-qualified.
7433     if ((CVR & Qualifiers::Restrict) &&
7434         (!hasRestrict ||
7435          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7436       continue;
7437 
7438     // Build qualified pointee type.
7439     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7440 
7441     // Build qualified pointer type.
7442     QualType QPointerTy;
7443     if (!buildObjCPtr)
7444       QPointerTy = Context.getPointerType(QPointeeTy);
7445     else
7446       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7447 
7448     // Insert qualified pointer type.
7449     PointerTypes.insert(QPointerTy);
7450   }
7451 
7452   return true;
7453 }
7454 
7455 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7456 /// to the set of pointer types along with any more-qualified variants of
7457 /// that type. For example, if @p Ty is "int const *", this routine
7458 /// will add "int const *", "int const volatile *", "int const
7459 /// restrict *", and "int const volatile restrict *" to the set of
7460 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7461 /// false otherwise.
7462 ///
7463 /// FIXME: what to do about extended qualifiers?
7464 bool
7465 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7466     QualType Ty) {
7467   // Insert this type.
7468   if (!MemberPointerTypes.insert(Ty))
7469     return false;
7470 
7471   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7472   assert(PointerTy && "type was not a member pointer type!");
7473 
7474   QualType PointeeTy = PointerTy->getPointeeType();
7475   // Don't add qualified variants of arrays. For one, they're not allowed
7476   // (the qualifier would sink to the element type), and for another, the
7477   // only overload situation where it matters is subscript or pointer +- int,
7478   // and those shouldn't have qualifier variants anyway.
7479   if (PointeeTy->isArrayType())
7480     return true;
7481   const Type *ClassTy = PointerTy->getClass();
7482 
7483   // Iterate through all strict supersets of the pointee type's CVR
7484   // qualifiers.
7485   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7486   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7487     if ((CVR | BaseCVR) != CVR) continue;
7488 
7489     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7490     MemberPointerTypes.insert(
7491       Context.getMemberPointerType(QPointeeTy, ClassTy));
7492   }
7493 
7494   return true;
7495 }
7496 
7497 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7498 /// Ty can be implicit converted to the given set of @p Types. We're
7499 /// primarily interested in pointer types and enumeration types. We also
7500 /// take member pointer types, for the conditional operator.
7501 /// AllowUserConversions is true if we should look at the conversion
7502 /// functions of a class type, and AllowExplicitConversions if we
7503 /// should also include the explicit conversion functions of a class
7504 /// type.
7505 void
7506 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7507                                                SourceLocation Loc,
7508                                                bool AllowUserConversions,
7509                                                bool AllowExplicitConversions,
7510                                                const Qualifiers &VisibleQuals) {
7511   // Only deal with canonical types.
7512   Ty = Context.getCanonicalType(Ty);
7513 
7514   // Look through reference types; they aren't part of the type of an
7515   // expression for the purposes of conversions.
7516   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7517     Ty = RefTy->getPointeeType();
7518 
7519   // If we're dealing with an array type, decay to the pointer.
7520   if (Ty->isArrayType())
7521     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7522 
7523   // Otherwise, we don't care about qualifiers on the type.
7524   Ty = Ty.getLocalUnqualifiedType();
7525 
7526   // Flag if we ever add a non-record type.
7527   const RecordType *TyRec = Ty->getAs<RecordType>();
7528   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7529 
7530   // Flag if we encounter an arithmetic type.
7531   HasArithmeticOrEnumeralTypes =
7532     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7533 
7534   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7535     PointerTypes.insert(Ty);
7536   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7537     // Insert our type, and its more-qualified variants, into the set
7538     // of types.
7539     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7540       return;
7541   } else if (Ty->isMemberPointerType()) {
7542     // Member pointers are far easier, since the pointee can't be converted.
7543     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7544       return;
7545   } else if (Ty->isEnumeralType()) {
7546     HasArithmeticOrEnumeralTypes = true;
7547     EnumerationTypes.insert(Ty);
7548   } else if (Ty->isVectorType()) {
7549     // We treat vector types as arithmetic types in many contexts as an
7550     // extension.
7551     HasArithmeticOrEnumeralTypes = true;
7552     VectorTypes.insert(Ty);
7553   } else if (Ty->isNullPtrType()) {
7554     HasNullPtrType = true;
7555   } else if (AllowUserConversions && TyRec) {
7556     // No conversion functions in incomplete types.
7557     if (!SemaRef.isCompleteType(Loc, Ty))
7558       return;
7559 
7560     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7561     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7562       if (isa<UsingShadowDecl>(D))
7563         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7564 
7565       // Skip conversion function templates; they don't tell us anything
7566       // about which builtin types we can convert to.
7567       if (isa<FunctionTemplateDecl>(D))
7568         continue;
7569 
7570       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7571       if (AllowExplicitConversions || !Conv->isExplicit()) {
7572         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7573                               VisibleQuals);
7574       }
7575     }
7576   }
7577 }
7578 
7579 /// Helper function for AddBuiltinOperatorCandidates() that adds
7580 /// the volatile- and non-volatile-qualified assignment operators for the
7581 /// given type to the candidate set.
7582 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7583                                                    QualType T,
7584                                                    ArrayRef<Expr *> Args,
7585                                     OverloadCandidateSet &CandidateSet) {
7586   QualType ParamTypes[2];
7587 
7588   // T& operator=(T&, T)
7589   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7590   ParamTypes[1] = T;
7591   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7592                         /*IsAssignmentOperator=*/true);
7593 
7594   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7595     // volatile T& operator=(volatile T&, T)
7596     ParamTypes[0]
7597       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7598     ParamTypes[1] = T;
7599     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7600                           /*IsAssignmentOperator=*/true);
7601   }
7602 }
7603 
7604 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7605 /// if any, found in visible type conversion functions found in ArgExpr's type.
7606 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7607     Qualifiers VRQuals;
7608     const RecordType *TyRec;
7609     if (const MemberPointerType *RHSMPType =
7610         ArgExpr->getType()->getAs<MemberPointerType>())
7611       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7612     else
7613       TyRec = ArgExpr->getType()->getAs<RecordType>();
7614     if (!TyRec) {
7615       // Just to be safe, assume the worst case.
7616       VRQuals.addVolatile();
7617       VRQuals.addRestrict();
7618       return VRQuals;
7619     }
7620 
7621     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7622     if (!ClassDecl->hasDefinition())
7623       return VRQuals;
7624 
7625     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7626       if (isa<UsingShadowDecl>(D))
7627         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7628       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7629         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7630         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7631           CanTy = ResTypeRef->getPointeeType();
7632         // Need to go down the pointer/mempointer chain and add qualifiers
7633         // as see them.
7634         bool done = false;
7635         while (!done) {
7636           if (CanTy.isRestrictQualified())
7637             VRQuals.addRestrict();
7638           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7639             CanTy = ResTypePtr->getPointeeType();
7640           else if (const MemberPointerType *ResTypeMPtr =
7641                 CanTy->getAs<MemberPointerType>())
7642             CanTy = ResTypeMPtr->getPointeeType();
7643           else
7644             done = true;
7645           if (CanTy.isVolatileQualified())
7646             VRQuals.addVolatile();
7647           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7648             return VRQuals;
7649         }
7650       }
7651     }
7652     return VRQuals;
7653 }
7654 
7655 namespace {
7656 
7657 /// Helper class to manage the addition of builtin operator overload
7658 /// candidates. It provides shared state and utility methods used throughout
7659 /// the process, as well as a helper method to add each group of builtin
7660 /// operator overloads from the standard to a candidate set.
7661 class BuiltinOperatorOverloadBuilder {
7662   // Common instance state available to all overload candidate addition methods.
7663   Sema &S;
7664   ArrayRef<Expr *> Args;
7665   Qualifiers VisibleTypeConversionsQuals;
7666   bool HasArithmeticOrEnumeralCandidateType;
7667   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7668   OverloadCandidateSet &CandidateSet;
7669 
7670   static constexpr int ArithmeticTypesCap = 24;
7671   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7672 
7673   // Define some indices used to iterate over the arithemetic types in
7674   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7675   // types are that preserved by promotion (C++ [over.built]p2).
7676   unsigned FirstIntegralType,
7677            LastIntegralType;
7678   unsigned FirstPromotedIntegralType,
7679            LastPromotedIntegralType;
7680   unsigned FirstPromotedArithmeticType,
7681            LastPromotedArithmeticType;
7682   unsigned NumArithmeticTypes;
7683 
7684   void InitArithmeticTypes() {
7685     // Start of promoted types.
7686     FirstPromotedArithmeticType = 0;
7687     ArithmeticTypes.push_back(S.Context.FloatTy);
7688     ArithmeticTypes.push_back(S.Context.DoubleTy);
7689     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7690     if (S.Context.getTargetInfo().hasFloat128Type())
7691       ArithmeticTypes.push_back(S.Context.Float128Ty);
7692 
7693     // Start of integral types.
7694     FirstIntegralType = ArithmeticTypes.size();
7695     FirstPromotedIntegralType = ArithmeticTypes.size();
7696     ArithmeticTypes.push_back(S.Context.IntTy);
7697     ArithmeticTypes.push_back(S.Context.LongTy);
7698     ArithmeticTypes.push_back(S.Context.LongLongTy);
7699     if (S.Context.getTargetInfo().hasInt128Type())
7700       ArithmeticTypes.push_back(S.Context.Int128Ty);
7701     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7702     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7703     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7704     if (S.Context.getTargetInfo().hasInt128Type())
7705       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7706     LastPromotedIntegralType = ArithmeticTypes.size();
7707     LastPromotedArithmeticType = ArithmeticTypes.size();
7708     // End of promoted types.
7709 
7710     ArithmeticTypes.push_back(S.Context.BoolTy);
7711     ArithmeticTypes.push_back(S.Context.CharTy);
7712     ArithmeticTypes.push_back(S.Context.WCharTy);
7713     if (S.Context.getLangOpts().Char8)
7714       ArithmeticTypes.push_back(S.Context.Char8Ty);
7715     ArithmeticTypes.push_back(S.Context.Char16Ty);
7716     ArithmeticTypes.push_back(S.Context.Char32Ty);
7717     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7718     ArithmeticTypes.push_back(S.Context.ShortTy);
7719     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7720     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7721     LastIntegralType = ArithmeticTypes.size();
7722     NumArithmeticTypes = ArithmeticTypes.size();
7723     // End of integral types.
7724     // FIXME: What about complex? What about half?
7725 
7726     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7727            "Enough inline storage for all arithmetic types.");
7728   }
7729 
7730   /// Helper method to factor out the common pattern of adding overloads
7731   /// for '++' and '--' builtin operators.
7732   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7733                                            bool HasVolatile,
7734                                            bool HasRestrict) {
7735     QualType ParamTypes[2] = {
7736       S.Context.getLValueReferenceType(CandidateTy),
7737       S.Context.IntTy
7738     };
7739 
7740     // Non-volatile version.
7741     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7742 
7743     // Use a heuristic to reduce number of builtin candidates in the set:
7744     // add volatile version only if there are conversions to a volatile type.
7745     if (HasVolatile) {
7746       ParamTypes[0] =
7747         S.Context.getLValueReferenceType(
7748           S.Context.getVolatileType(CandidateTy));
7749       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7750     }
7751 
7752     // Add restrict version only if there are conversions to a restrict type
7753     // and our candidate type is a non-restrict-qualified pointer.
7754     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7755         !CandidateTy.isRestrictQualified()) {
7756       ParamTypes[0]
7757         = S.Context.getLValueReferenceType(
7758             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7759       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7760 
7761       if (HasVolatile) {
7762         ParamTypes[0]
7763           = S.Context.getLValueReferenceType(
7764               S.Context.getCVRQualifiedType(CandidateTy,
7765                                             (Qualifiers::Volatile |
7766                                              Qualifiers::Restrict)));
7767         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7768       }
7769     }
7770 
7771   }
7772 
7773 public:
7774   BuiltinOperatorOverloadBuilder(
7775     Sema &S, ArrayRef<Expr *> Args,
7776     Qualifiers VisibleTypeConversionsQuals,
7777     bool HasArithmeticOrEnumeralCandidateType,
7778     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7779     OverloadCandidateSet &CandidateSet)
7780     : S(S), Args(Args),
7781       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7782       HasArithmeticOrEnumeralCandidateType(
7783         HasArithmeticOrEnumeralCandidateType),
7784       CandidateTypes(CandidateTypes),
7785       CandidateSet(CandidateSet) {
7786 
7787     InitArithmeticTypes();
7788   }
7789 
7790   // Increment is deprecated for bool since C++17.
7791   //
7792   // C++ [over.built]p3:
7793   //
7794   //   For every pair (T, VQ), where T is an arithmetic type other
7795   //   than bool, and VQ is either volatile or empty, there exist
7796   //   candidate operator functions of the form
7797   //
7798   //       VQ T&      operator++(VQ T&);
7799   //       T          operator++(VQ T&, int);
7800   //
7801   // C++ [over.built]p4:
7802   //
7803   //   For every pair (T, VQ), where T is an arithmetic type other
7804   //   than bool, and VQ is either volatile or empty, there exist
7805   //   candidate operator functions of the form
7806   //
7807   //       VQ T&      operator--(VQ T&);
7808   //       T          operator--(VQ T&, int);
7809   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7810     if (!HasArithmeticOrEnumeralCandidateType)
7811       return;
7812 
7813     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7814       const auto TypeOfT = ArithmeticTypes[Arith];
7815       if (TypeOfT == S.Context.BoolTy) {
7816         if (Op == OO_MinusMinus)
7817           continue;
7818         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7819           continue;
7820       }
7821       addPlusPlusMinusMinusStyleOverloads(
7822         TypeOfT,
7823         VisibleTypeConversionsQuals.hasVolatile(),
7824         VisibleTypeConversionsQuals.hasRestrict());
7825     }
7826   }
7827 
7828   // C++ [over.built]p5:
7829   //
7830   //   For every pair (T, VQ), where T is a cv-qualified or
7831   //   cv-unqualified object type, and VQ is either volatile or
7832   //   empty, there exist candidate operator functions of the form
7833   //
7834   //       T*VQ&      operator++(T*VQ&);
7835   //       T*VQ&      operator--(T*VQ&);
7836   //       T*         operator++(T*VQ&, int);
7837   //       T*         operator--(T*VQ&, int);
7838   void addPlusPlusMinusMinusPointerOverloads() {
7839     for (BuiltinCandidateTypeSet::iterator
7840               Ptr = CandidateTypes[0].pointer_begin(),
7841            PtrEnd = CandidateTypes[0].pointer_end();
7842          Ptr != PtrEnd; ++Ptr) {
7843       // Skip pointer types that aren't pointers to object types.
7844       if (!(*Ptr)->getPointeeType()->isObjectType())
7845         continue;
7846 
7847       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7848         (!(*Ptr).isVolatileQualified() &&
7849          VisibleTypeConversionsQuals.hasVolatile()),
7850         (!(*Ptr).isRestrictQualified() &&
7851          VisibleTypeConversionsQuals.hasRestrict()));
7852     }
7853   }
7854 
7855   // C++ [over.built]p6:
7856   //   For every cv-qualified or cv-unqualified object type T, there
7857   //   exist candidate operator functions of the form
7858   //
7859   //       T&         operator*(T*);
7860   //
7861   // C++ [over.built]p7:
7862   //   For every function type T that does not have cv-qualifiers or a
7863   //   ref-qualifier, there exist candidate operator functions of the form
7864   //       T&         operator*(T*);
7865   void addUnaryStarPointerOverloads() {
7866     for (BuiltinCandidateTypeSet::iterator
7867               Ptr = CandidateTypes[0].pointer_begin(),
7868            PtrEnd = CandidateTypes[0].pointer_end();
7869          Ptr != PtrEnd; ++Ptr) {
7870       QualType ParamTy = *Ptr;
7871       QualType PointeeTy = ParamTy->getPointeeType();
7872       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7873         continue;
7874 
7875       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7876         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7877           continue;
7878 
7879       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7880     }
7881   }
7882 
7883   // C++ [over.built]p9:
7884   //  For every promoted arithmetic type T, there exist candidate
7885   //  operator functions of the form
7886   //
7887   //       T         operator+(T);
7888   //       T         operator-(T);
7889   void addUnaryPlusOrMinusArithmeticOverloads() {
7890     if (!HasArithmeticOrEnumeralCandidateType)
7891       return;
7892 
7893     for (unsigned Arith = FirstPromotedArithmeticType;
7894          Arith < LastPromotedArithmeticType; ++Arith) {
7895       QualType ArithTy = ArithmeticTypes[Arith];
7896       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7897     }
7898 
7899     // Extension: We also add these operators for vector types.
7900     for (BuiltinCandidateTypeSet::iterator
7901               Vec = CandidateTypes[0].vector_begin(),
7902            VecEnd = CandidateTypes[0].vector_end();
7903          Vec != VecEnd; ++Vec) {
7904       QualType VecTy = *Vec;
7905       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7906     }
7907   }
7908 
7909   // C++ [over.built]p8:
7910   //   For every type T, there exist candidate operator functions of
7911   //   the form
7912   //
7913   //       T*         operator+(T*);
7914   void addUnaryPlusPointerOverloads() {
7915     for (BuiltinCandidateTypeSet::iterator
7916               Ptr = CandidateTypes[0].pointer_begin(),
7917            PtrEnd = CandidateTypes[0].pointer_end();
7918          Ptr != PtrEnd; ++Ptr) {
7919       QualType ParamTy = *Ptr;
7920       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7921     }
7922   }
7923 
7924   // C++ [over.built]p10:
7925   //   For every promoted integral type T, there exist candidate
7926   //   operator functions of the form
7927   //
7928   //        T         operator~(T);
7929   void addUnaryTildePromotedIntegralOverloads() {
7930     if (!HasArithmeticOrEnumeralCandidateType)
7931       return;
7932 
7933     for (unsigned Int = FirstPromotedIntegralType;
7934          Int < LastPromotedIntegralType; ++Int) {
7935       QualType IntTy = ArithmeticTypes[Int];
7936       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7937     }
7938 
7939     // Extension: We also add this operator for vector types.
7940     for (BuiltinCandidateTypeSet::iterator
7941               Vec = CandidateTypes[0].vector_begin(),
7942            VecEnd = CandidateTypes[0].vector_end();
7943          Vec != VecEnd; ++Vec) {
7944       QualType VecTy = *Vec;
7945       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7946     }
7947   }
7948 
7949   // C++ [over.match.oper]p16:
7950   //   For every pointer to member type T or type std::nullptr_t, there
7951   //   exist candidate operator functions of the form
7952   //
7953   //        bool operator==(T,T);
7954   //        bool operator!=(T,T);
7955   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7956     /// Set of (canonical) types that we've already handled.
7957     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7958 
7959     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7960       for (BuiltinCandidateTypeSet::iterator
7961                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7962              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7963            MemPtr != MemPtrEnd;
7964            ++MemPtr) {
7965         // Don't add the same builtin candidate twice.
7966         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7967           continue;
7968 
7969         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7970         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7971       }
7972 
7973       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7974         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7975         if (AddedTypes.insert(NullPtrTy).second) {
7976           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7977           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7978         }
7979       }
7980     }
7981   }
7982 
7983   // C++ [over.built]p15:
7984   //
7985   //   For every T, where T is an enumeration type or a pointer type,
7986   //   there exist candidate operator functions of the form
7987   //
7988   //        bool       operator<(T, T);
7989   //        bool       operator>(T, T);
7990   //        bool       operator<=(T, T);
7991   //        bool       operator>=(T, T);
7992   //        bool       operator==(T, T);
7993   //        bool       operator!=(T, T);
7994   //           R       operator<=>(T, T)
7995   void addGenericBinaryPointerOrEnumeralOverloads() {
7996     // C++ [over.match.oper]p3:
7997     //   [...]the built-in candidates include all of the candidate operator
7998     //   functions defined in 13.6 that, compared to the given operator, [...]
7999     //   do not have the same parameter-type-list as any non-template non-member
8000     //   candidate.
8001     //
8002     // Note that in practice, this only affects enumeration types because there
8003     // aren't any built-in candidates of record type, and a user-defined operator
8004     // must have an operand of record or enumeration type. Also, the only other
8005     // overloaded operator with enumeration arguments, operator=,
8006     // cannot be overloaded for enumeration types, so this is the only place
8007     // where we must suppress candidates like this.
8008     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8009       UserDefinedBinaryOperators;
8010 
8011     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8012       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8013           CandidateTypes[ArgIdx].enumeration_end()) {
8014         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8015                                          CEnd = CandidateSet.end();
8016              C != CEnd; ++C) {
8017           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8018             continue;
8019 
8020           if (C->Function->isFunctionTemplateSpecialization())
8021             continue;
8022 
8023           QualType FirstParamType =
8024             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8025           QualType SecondParamType =
8026             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8027 
8028           // Skip if either parameter isn't of enumeral type.
8029           if (!FirstParamType->isEnumeralType() ||
8030               !SecondParamType->isEnumeralType())
8031             continue;
8032 
8033           // Add this operator to the set of known user-defined operators.
8034           UserDefinedBinaryOperators.insert(
8035             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8036                            S.Context.getCanonicalType(SecondParamType)));
8037         }
8038       }
8039     }
8040 
8041     /// Set of (canonical) types that we've already handled.
8042     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8043 
8044     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8045       for (BuiltinCandidateTypeSet::iterator
8046                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8047              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8048            Ptr != PtrEnd; ++Ptr) {
8049         // Don't add the same builtin candidate twice.
8050         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8051           continue;
8052 
8053         QualType ParamTypes[2] = { *Ptr, *Ptr };
8054         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8055       }
8056       for (BuiltinCandidateTypeSet::iterator
8057                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8058              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8059            Enum != EnumEnd; ++Enum) {
8060         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8061 
8062         // Don't add the same builtin candidate twice, or if a user defined
8063         // candidate exists.
8064         if (!AddedTypes.insert(CanonType).second ||
8065             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8066                                                             CanonType)))
8067           continue;
8068         QualType ParamTypes[2] = { *Enum, *Enum };
8069         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8070       }
8071     }
8072   }
8073 
8074   // C++ [over.built]p13:
8075   //
8076   //   For every cv-qualified or cv-unqualified object type T
8077   //   there exist candidate operator functions of the form
8078   //
8079   //      T*         operator+(T*, ptrdiff_t);
8080   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8081   //      T*         operator-(T*, ptrdiff_t);
8082   //      T*         operator+(ptrdiff_t, T*);
8083   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8084   //
8085   // C++ [over.built]p14:
8086   //
8087   //   For every T, where T is a pointer to object type, there
8088   //   exist candidate operator functions of the form
8089   //
8090   //      ptrdiff_t  operator-(T, T);
8091   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8092     /// Set of (canonical) types that we've already handled.
8093     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8094 
8095     for (int Arg = 0; Arg < 2; ++Arg) {
8096       QualType AsymmetricParamTypes[2] = {
8097         S.Context.getPointerDiffType(),
8098         S.Context.getPointerDiffType(),
8099       };
8100       for (BuiltinCandidateTypeSet::iterator
8101                 Ptr = CandidateTypes[Arg].pointer_begin(),
8102              PtrEnd = CandidateTypes[Arg].pointer_end();
8103            Ptr != PtrEnd; ++Ptr) {
8104         QualType PointeeTy = (*Ptr)->getPointeeType();
8105         if (!PointeeTy->isObjectType())
8106           continue;
8107 
8108         AsymmetricParamTypes[Arg] = *Ptr;
8109         if (Arg == 0 || Op == OO_Plus) {
8110           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8111           // T* operator+(ptrdiff_t, T*);
8112           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8113         }
8114         if (Op == OO_Minus) {
8115           // ptrdiff_t operator-(T, T);
8116           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8117             continue;
8118 
8119           QualType ParamTypes[2] = { *Ptr, *Ptr };
8120           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8121         }
8122       }
8123     }
8124   }
8125 
8126   // C++ [over.built]p12:
8127   //
8128   //   For every pair of promoted arithmetic types L and R, there
8129   //   exist candidate operator functions of the form
8130   //
8131   //        LR         operator*(L, R);
8132   //        LR         operator/(L, R);
8133   //        LR         operator+(L, R);
8134   //        LR         operator-(L, R);
8135   //        bool       operator<(L, R);
8136   //        bool       operator>(L, R);
8137   //        bool       operator<=(L, R);
8138   //        bool       operator>=(L, R);
8139   //        bool       operator==(L, R);
8140   //        bool       operator!=(L, R);
8141   //
8142   //   where LR is the result of the usual arithmetic conversions
8143   //   between types L and R.
8144   //
8145   // C++ [over.built]p24:
8146   //
8147   //   For every pair of promoted arithmetic types L and R, there exist
8148   //   candidate operator functions of the form
8149   //
8150   //        LR       operator?(bool, L, R);
8151   //
8152   //   where LR is the result of the usual arithmetic conversions
8153   //   between types L and R.
8154   // Our candidates ignore the first parameter.
8155   void addGenericBinaryArithmeticOverloads() {
8156     if (!HasArithmeticOrEnumeralCandidateType)
8157       return;
8158 
8159     for (unsigned Left = FirstPromotedArithmeticType;
8160          Left < LastPromotedArithmeticType; ++Left) {
8161       for (unsigned Right = FirstPromotedArithmeticType;
8162            Right < LastPromotedArithmeticType; ++Right) {
8163         QualType LandR[2] = { ArithmeticTypes[Left],
8164                               ArithmeticTypes[Right] };
8165         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8166       }
8167     }
8168 
8169     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8170     // conditional operator for vector types.
8171     for (BuiltinCandidateTypeSet::iterator
8172               Vec1 = CandidateTypes[0].vector_begin(),
8173            Vec1End = CandidateTypes[0].vector_end();
8174          Vec1 != Vec1End; ++Vec1) {
8175       for (BuiltinCandidateTypeSet::iterator
8176                 Vec2 = CandidateTypes[1].vector_begin(),
8177              Vec2End = CandidateTypes[1].vector_end();
8178            Vec2 != Vec2End; ++Vec2) {
8179         QualType LandR[2] = { *Vec1, *Vec2 };
8180         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8181       }
8182     }
8183   }
8184 
8185   // C++2a [over.built]p14:
8186   //
8187   //   For every integral type T there exists a candidate operator function
8188   //   of the form
8189   //
8190   //        std::strong_ordering operator<=>(T, T)
8191   //
8192   // C++2a [over.built]p15:
8193   //
8194   //   For every pair of floating-point types L and R, there exists a candidate
8195   //   operator function of the form
8196   //
8197   //       std::partial_ordering operator<=>(L, R);
8198   //
8199   // FIXME: The current specification for integral types doesn't play nice with
8200   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8201   // comparisons. Under the current spec this can lead to ambiguity during
8202   // overload resolution. For example:
8203   //
8204   //   enum A : int {a};
8205   //   auto x = (a <=> (long)42);
8206   //
8207   //   error: call is ambiguous for arguments 'A' and 'long'.
8208   //   note: candidate operator<=>(int, int)
8209   //   note: candidate operator<=>(long, long)
8210   //
8211   // To avoid this error, this function deviates from the specification and adds
8212   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8213   // arithmetic types (the same as the generic relational overloads).
8214   //
8215   // For now this function acts as a placeholder.
8216   void addThreeWayArithmeticOverloads() {
8217     addGenericBinaryArithmeticOverloads();
8218   }
8219 
8220   // C++ [over.built]p17:
8221   //
8222   //   For every pair of promoted integral types L and R, there
8223   //   exist candidate operator functions of the form
8224   //
8225   //      LR         operator%(L, R);
8226   //      LR         operator&(L, R);
8227   //      LR         operator^(L, R);
8228   //      LR         operator|(L, R);
8229   //      L          operator<<(L, R);
8230   //      L          operator>>(L, R);
8231   //
8232   //   where LR is the result of the usual arithmetic conversions
8233   //   between types L and R.
8234   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8235     if (!HasArithmeticOrEnumeralCandidateType)
8236       return;
8237 
8238     for (unsigned Left = FirstPromotedIntegralType;
8239          Left < LastPromotedIntegralType; ++Left) {
8240       for (unsigned Right = FirstPromotedIntegralType;
8241            Right < LastPromotedIntegralType; ++Right) {
8242         QualType LandR[2] = { ArithmeticTypes[Left],
8243                               ArithmeticTypes[Right] };
8244         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8245       }
8246     }
8247   }
8248 
8249   // C++ [over.built]p20:
8250   //
8251   //   For every pair (T, VQ), where T is an enumeration or
8252   //   pointer to member type and VQ is either volatile or
8253   //   empty, there exist candidate operator functions of the form
8254   //
8255   //        VQ T&      operator=(VQ T&, T);
8256   void addAssignmentMemberPointerOrEnumeralOverloads() {
8257     /// Set of (canonical) types that we've already handled.
8258     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8259 
8260     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8261       for (BuiltinCandidateTypeSet::iterator
8262                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8263              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8264            Enum != EnumEnd; ++Enum) {
8265         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8266           continue;
8267 
8268         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8269       }
8270 
8271       for (BuiltinCandidateTypeSet::iterator
8272                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8273              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8274            MemPtr != MemPtrEnd; ++MemPtr) {
8275         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8276           continue;
8277 
8278         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8279       }
8280     }
8281   }
8282 
8283   // C++ [over.built]p19:
8284   //
8285   //   For every pair (T, VQ), where T is any type and VQ is either
8286   //   volatile or empty, there exist candidate operator functions
8287   //   of the form
8288   //
8289   //        T*VQ&      operator=(T*VQ&, T*);
8290   //
8291   // C++ [over.built]p21:
8292   //
8293   //   For every pair (T, VQ), where T is a cv-qualified or
8294   //   cv-unqualified object type and VQ is either volatile or
8295   //   empty, there exist candidate operator functions of the form
8296   //
8297   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8298   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8299   void addAssignmentPointerOverloads(bool isEqualOp) {
8300     /// Set of (canonical) types that we've already handled.
8301     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8302 
8303     for (BuiltinCandidateTypeSet::iterator
8304               Ptr = CandidateTypes[0].pointer_begin(),
8305            PtrEnd = CandidateTypes[0].pointer_end();
8306          Ptr != PtrEnd; ++Ptr) {
8307       // If this is operator=, keep track of the builtin candidates we added.
8308       if (isEqualOp)
8309         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8310       else if (!(*Ptr)->getPointeeType()->isObjectType())
8311         continue;
8312 
8313       // non-volatile version
8314       QualType ParamTypes[2] = {
8315         S.Context.getLValueReferenceType(*Ptr),
8316         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8317       };
8318       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8319                             /*IsAssigmentOperator=*/ isEqualOp);
8320 
8321       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8322                           VisibleTypeConversionsQuals.hasVolatile();
8323       if (NeedVolatile) {
8324         // volatile version
8325         ParamTypes[0] =
8326           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8327         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8328                               /*IsAssigmentOperator=*/isEqualOp);
8329       }
8330 
8331       if (!(*Ptr).isRestrictQualified() &&
8332           VisibleTypeConversionsQuals.hasRestrict()) {
8333         // restrict version
8334         ParamTypes[0]
8335           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8336         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8337                               /*IsAssigmentOperator=*/isEqualOp);
8338 
8339         if (NeedVolatile) {
8340           // volatile restrict version
8341           ParamTypes[0]
8342             = S.Context.getLValueReferenceType(
8343                 S.Context.getCVRQualifiedType(*Ptr,
8344                                               (Qualifiers::Volatile |
8345                                                Qualifiers::Restrict)));
8346           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8347                                 /*IsAssigmentOperator=*/isEqualOp);
8348         }
8349       }
8350     }
8351 
8352     if (isEqualOp) {
8353       for (BuiltinCandidateTypeSet::iterator
8354                 Ptr = CandidateTypes[1].pointer_begin(),
8355              PtrEnd = CandidateTypes[1].pointer_end();
8356            Ptr != PtrEnd; ++Ptr) {
8357         // Make sure we don't add the same candidate twice.
8358         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8359           continue;
8360 
8361         QualType ParamTypes[2] = {
8362           S.Context.getLValueReferenceType(*Ptr),
8363           *Ptr,
8364         };
8365 
8366         // non-volatile version
8367         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8368                               /*IsAssigmentOperator=*/true);
8369 
8370         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8371                            VisibleTypeConversionsQuals.hasVolatile();
8372         if (NeedVolatile) {
8373           // volatile version
8374           ParamTypes[0] =
8375             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8376           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8377                                 /*IsAssigmentOperator=*/true);
8378         }
8379 
8380         if (!(*Ptr).isRestrictQualified() &&
8381             VisibleTypeConversionsQuals.hasRestrict()) {
8382           // restrict version
8383           ParamTypes[0]
8384             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8385           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8386                                 /*IsAssigmentOperator=*/true);
8387 
8388           if (NeedVolatile) {
8389             // volatile restrict version
8390             ParamTypes[0]
8391               = S.Context.getLValueReferenceType(
8392                   S.Context.getCVRQualifiedType(*Ptr,
8393                                                 (Qualifiers::Volatile |
8394                                                  Qualifiers::Restrict)));
8395             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8396                                   /*IsAssigmentOperator=*/true);
8397           }
8398         }
8399       }
8400     }
8401   }
8402 
8403   // C++ [over.built]p18:
8404   //
8405   //   For every triple (L, VQ, R), where L is an arithmetic type,
8406   //   VQ is either volatile or empty, and R is a promoted
8407   //   arithmetic type, there exist candidate operator functions of
8408   //   the form
8409   //
8410   //        VQ L&      operator=(VQ L&, R);
8411   //        VQ L&      operator*=(VQ L&, R);
8412   //        VQ L&      operator/=(VQ L&, R);
8413   //        VQ L&      operator+=(VQ L&, R);
8414   //        VQ L&      operator-=(VQ L&, R);
8415   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8416     if (!HasArithmeticOrEnumeralCandidateType)
8417       return;
8418 
8419     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8420       for (unsigned Right = FirstPromotedArithmeticType;
8421            Right < LastPromotedArithmeticType; ++Right) {
8422         QualType ParamTypes[2];
8423         ParamTypes[1] = ArithmeticTypes[Right];
8424 
8425         // Add this built-in operator as a candidate (VQ is empty).
8426         ParamTypes[0] =
8427           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8428         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8429                               /*IsAssigmentOperator=*/isEqualOp);
8430 
8431         // Add this built-in operator as a candidate (VQ is 'volatile').
8432         if (VisibleTypeConversionsQuals.hasVolatile()) {
8433           ParamTypes[0] =
8434             S.Context.getVolatileType(ArithmeticTypes[Left]);
8435           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8436           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8437                                 /*IsAssigmentOperator=*/isEqualOp);
8438         }
8439       }
8440     }
8441 
8442     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8443     for (BuiltinCandidateTypeSet::iterator
8444               Vec1 = CandidateTypes[0].vector_begin(),
8445            Vec1End = CandidateTypes[0].vector_end();
8446          Vec1 != Vec1End; ++Vec1) {
8447       for (BuiltinCandidateTypeSet::iterator
8448                 Vec2 = CandidateTypes[1].vector_begin(),
8449              Vec2End = CandidateTypes[1].vector_end();
8450            Vec2 != Vec2End; ++Vec2) {
8451         QualType ParamTypes[2];
8452         ParamTypes[1] = *Vec2;
8453         // Add this built-in operator as a candidate (VQ is empty).
8454         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8455         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8456                               /*IsAssigmentOperator=*/isEqualOp);
8457 
8458         // Add this built-in operator as a candidate (VQ is 'volatile').
8459         if (VisibleTypeConversionsQuals.hasVolatile()) {
8460           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8461           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8462           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8463                                 /*IsAssigmentOperator=*/isEqualOp);
8464         }
8465       }
8466     }
8467   }
8468 
8469   // C++ [over.built]p22:
8470   //
8471   //   For every triple (L, VQ, R), where L is an integral type, VQ
8472   //   is either volatile or empty, and R is a promoted integral
8473   //   type, there exist candidate operator functions of the form
8474   //
8475   //        VQ L&       operator%=(VQ L&, R);
8476   //        VQ L&       operator<<=(VQ L&, R);
8477   //        VQ L&       operator>>=(VQ L&, R);
8478   //        VQ L&       operator&=(VQ L&, R);
8479   //        VQ L&       operator^=(VQ L&, R);
8480   //        VQ L&       operator|=(VQ L&, R);
8481   void addAssignmentIntegralOverloads() {
8482     if (!HasArithmeticOrEnumeralCandidateType)
8483       return;
8484 
8485     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8486       for (unsigned Right = FirstPromotedIntegralType;
8487            Right < LastPromotedIntegralType; ++Right) {
8488         QualType ParamTypes[2];
8489         ParamTypes[1] = ArithmeticTypes[Right];
8490 
8491         // Add this built-in operator as a candidate (VQ is empty).
8492         ParamTypes[0] =
8493           S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8494         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8495         if (VisibleTypeConversionsQuals.hasVolatile()) {
8496           // Add this built-in operator as a candidate (VQ is 'volatile').
8497           ParamTypes[0] = ArithmeticTypes[Left];
8498           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8499           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8500           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8501         }
8502       }
8503     }
8504   }
8505 
8506   // C++ [over.operator]p23:
8507   //
8508   //   There also exist candidate operator functions of the form
8509   //
8510   //        bool        operator!(bool);
8511   //        bool        operator&&(bool, bool);
8512   //        bool        operator||(bool, bool);
8513   void addExclaimOverload() {
8514     QualType ParamTy = S.Context.BoolTy;
8515     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8516                           /*IsAssignmentOperator=*/false,
8517                           /*NumContextualBoolArguments=*/1);
8518   }
8519   void addAmpAmpOrPipePipeOverload() {
8520     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8521     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8522                           /*IsAssignmentOperator=*/false,
8523                           /*NumContextualBoolArguments=*/2);
8524   }
8525 
8526   // C++ [over.built]p13:
8527   //
8528   //   For every cv-qualified or cv-unqualified object type T there
8529   //   exist candidate operator functions of the form
8530   //
8531   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8532   //        T&         operator[](T*, ptrdiff_t);
8533   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8534   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8535   //        T&         operator[](ptrdiff_t, T*);
8536   void addSubscriptOverloads() {
8537     for (BuiltinCandidateTypeSet::iterator
8538               Ptr = CandidateTypes[0].pointer_begin(),
8539            PtrEnd = CandidateTypes[0].pointer_end();
8540          Ptr != PtrEnd; ++Ptr) {
8541       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8542       QualType PointeeType = (*Ptr)->getPointeeType();
8543       if (!PointeeType->isObjectType())
8544         continue;
8545 
8546       // T& operator[](T*, ptrdiff_t)
8547       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8548     }
8549 
8550     for (BuiltinCandidateTypeSet::iterator
8551               Ptr = CandidateTypes[1].pointer_begin(),
8552            PtrEnd = CandidateTypes[1].pointer_end();
8553          Ptr != PtrEnd; ++Ptr) {
8554       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8555       QualType PointeeType = (*Ptr)->getPointeeType();
8556       if (!PointeeType->isObjectType())
8557         continue;
8558 
8559       // T& operator[](ptrdiff_t, T*)
8560       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8561     }
8562   }
8563 
8564   // C++ [over.built]p11:
8565   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8566   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8567   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8568   //    there exist candidate operator functions of the form
8569   //
8570   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8571   //
8572   //    where CV12 is the union of CV1 and CV2.
8573   void addArrowStarOverloads() {
8574     for (BuiltinCandidateTypeSet::iterator
8575              Ptr = CandidateTypes[0].pointer_begin(),
8576            PtrEnd = CandidateTypes[0].pointer_end();
8577          Ptr != PtrEnd; ++Ptr) {
8578       QualType C1Ty = (*Ptr);
8579       QualType C1;
8580       QualifierCollector Q1;
8581       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8582       if (!isa<RecordType>(C1))
8583         continue;
8584       // heuristic to reduce number of builtin candidates in the set.
8585       // Add volatile/restrict version only if there are conversions to a
8586       // volatile/restrict type.
8587       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8588         continue;
8589       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8590         continue;
8591       for (BuiltinCandidateTypeSet::iterator
8592                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8593              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8594            MemPtr != MemPtrEnd; ++MemPtr) {
8595         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8596         QualType C2 = QualType(mptr->getClass(), 0);
8597         C2 = C2.getUnqualifiedType();
8598         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8599           break;
8600         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8601         // build CV12 T&
8602         QualType T = mptr->getPointeeType();
8603         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8604             T.isVolatileQualified())
8605           continue;
8606         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8607             T.isRestrictQualified())
8608           continue;
8609         T = Q1.apply(S.Context, T);
8610         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8611       }
8612     }
8613   }
8614 
8615   // Note that we don't consider the first argument, since it has been
8616   // contextually converted to bool long ago. The candidates below are
8617   // therefore added as binary.
8618   //
8619   // C++ [over.built]p25:
8620   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8621   //   enumeration type, there exist candidate operator functions of the form
8622   //
8623   //        T        operator?(bool, T, T);
8624   //
8625   void addConditionalOperatorOverloads() {
8626     /// Set of (canonical) types that we've already handled.
8627     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8628 
8629     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8630       for (BuiltinCandidateTypeSet::iterator
8631                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8632              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8633            Ptr != PtrEnd; ++Ptr) {
8634         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8635           continue;
8636 
8637         QualType ParamTypes[2] = { *Ptr, *Ptr };
8638         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8639       }
8640 
8641       for (BuiltinCandidateTypeSet::iterator
8642                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8643              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8644            MemPtr != MemPtrEnd; ++MemPtr) {
8645         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8646           continue;
8647 
8648         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8649         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8650       }
8651 
8652       if (S.getLangOpts().CPlusPlus11) {
8653         for (BuiltinCandidateTypeSet::iterator
8654                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8655                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8656              Enum != EnumEnd; ++Enum) {
8657           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8658             continue;
8659 
8660           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8661             continue;
8662 
8663           QualType ParamTypes[2] = { *Enum, *Enum };
8664           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8665         }
8666       }
8667     }
8668   }
8669 };
8670 
8671 } // end anonymous namespace
8672 
8673 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8674 /// operator overloads to the candidate set (C++ [over.built]), based
8675 /// on the operator @p Op and the arguments given. For example, if the
8676 /// operator is a binary '+', this routine might add "int
8677 /// operator+(int, int)" to cover integer addition.
8678 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8679                                         SourceLocation OpLoc,
8680                                         ArrayRef<Expr *> Args,
8681                                         OverloadCandidateSet &CandidateSet) {
8682   // Find all of the types that the arguments can convert to, but only
8683   // if the operator we're looking at has built-in operator candidates
8684   // that make use of these types. Also record whether we encounter non-record
8685   // candidate types or either arithmetic or enumeral candidate types.
8686   Qualifiers VisibleTypeConversionsQuals;
8687   VisibleTypeConversionsQuals.addConst();
8688   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8689     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8690 
8691   bool HasNonRecordCandidateType = false;
8692   bool HasArithmeticOrEnumeralCandidateType = false;
8693   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8694   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8695     CandidateTypes.emplace_back(*this);
8696     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8697                                                  OpLoc,
8698                                                  true,
8699                                                  (Op == OO_Exclaim ||
8700                                                   Op == OO_AmpAmp ||
8701                                                   Op == OO_PipePipe),
8702                                                  VisibleTypeConversionsQuals);
8703     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8704         CandidateTypes[ArgIdx].hasNonRecordTypes();
8705     HasArithmeticOrEnumeralCandidateType =
8706         HasArithmeticOrEnumeralCandidateType ||
8707         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8708   }
8709 
8710   // Exit early when no non-record types have been added to the candidate set
8711   // for any of the arguments to the operator.
8712   //
8713   // We can't exit early for !, ||, or &&, since there we have always have
8714   // 'bool' overloads.
8715   if (!HasNonRecordCandidateType &&
8716       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8717     return;
8718 
8719   // Setup an object to manage the common state for building overloads.
8720   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8721                                            VisibleTypeConversionsQuals,
8722                                            HasArithmeticOrEnumeralCandidateType,
8723                                            CandidateTypes, CandidateSet);
8724 
8725   // Dispatch over the operation to add in only those overloads which apply.
8726   switch (Op) {
8727   case OO_None:
8728   case NUM_OVERLOADED_OPERATORS:
8729     llvm_unreachable("Expected an overloaded operator");
8730 
8731   case OO_New:
8732   case OO_Delete:
8733   case OO_Array_New:
8734   case OO_Array_Delete:
8735   case OO_Call:
8736     llvm_unreachable(
8737                     "Special operators don't use AddBuiltinOperatorCandidates");
8738 
8739   case OO_Comma:
8740   case OO_Arrow:
8741   case OO_Coawait:
8742     // C++ [over.match.oper]p3:
8743     //   -- For the operator ',', the unary operator '&', the
8744     //      operator '->', or the operator 'co_await', the
8745     //      built-in candidates set is empty.
8746     break;
8747 
8748   case OO_Plus: // '+' is either unary or binary
8749     if (Args.size() == 1)
8750       OpBuilder.addUnaryPlusPointerOverloads();
8751     LLVM_FALLTHROUGH;
8752 
8753   case OO_Minus: // '-' is either unary or binary
8754     if (Args.size() == 1) {
8755       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8756     } else {
8757       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8758       OpBuilder.addGenericBinaryArithmeticOverloads();
8759     }
8760     break;
8761 
8762   case OO_Star: // '*' is either unary or binary
8763     if (Args.size() == 1)
8764       OpBuilder.addUnaryStarPointerOverloads();
8765     else
8766       OpBuilder.addGenericBinaryArithmeticOverloads();
8767     break;
8768 
8769   case OO_Slash:
8770     OpBuilder.addGenericBinaryArithmeticOverloads();
8771     break;
8772 
8773   case OO_PlusPlus:
8774   case OO_MinusMinus:
8775     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8776     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8777     break;
8778 
8779   case OO_EqualEqual:
8780   case OO_ExclaimEqual:
8781     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8782     LLVM_FALLTHROUGH;
8783 
8784   case OO_Less:
8785   case OO_Greater:
8786   case OO_LessEqual:
8787   case OO_GreaterEqual:
8788     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8789     OpBuilder.addGenericBinaryArithmeticOverloads();
8790     break;
8791 
8792   case OO_Spaceship:
8793     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8794     OpBuilder.addThreeWayArithmeticOverloads();
8795     break;
8796 
8797   case OO_Percent:
8798   case OO_Caret:
8799   case OO_Pipe:
8800   case OO_LessLess:
8801   case OO_GreaterGreater:
8802     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8803     break;
8804 
8805   case OO_Amp: // '&' is either unary or binary
8806     if (Args.size() == 1)
8807       // C++ [over.match.oper]p3:
8808       //   -- For the operator ',', the unary operator '&', or the
8809       //      operator '->', the built-in candidates set is empty.
8810       break;
8811 
8812     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8813     break;
8814 
8815   case OO_Tilde:
8816     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8817     break;
8818 
8819   case OO_Equal:
8820     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8821     LLVM_FALLTHROUGH;
8822 
8823   case OO_PlusEqual:
8824   case OO_MinusEqual:
8825     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8826     LLVM_FALLTHROUGH;
8827 
8828   case OO_StarEqual:
8829   case OO_SlashEqual:
8830     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8831     break;
8832 
8833   case OO_PercentEqual:
8834   case OO_LessLessEqual:
8835   case OO_GreaterGreaterEqual:
8836   case OO_AmpEqual:
8837   case OO_CaretEqual:
8838   case OO_PipeEqual:
8839     OpBuilder.addAssignmentIntegralOverloads();
8840     break;
8841 
8842   case OO_Exclaim:
8843     OpBuilder.addExclaimOverload();
8844     break;
8845 
8846   case OO_AmpAmp:
8847   case OO_PipePipe:
8848     OpBuilder.addAmpAmpOrPipePipeOverload();
8849     break;
8850 
8851   case OO_Subscript:
8852     OpBuilder.addSubscriptOverloads();
8853     break;
8854 
8855   case OO_ArrowStar:
8856     OpBuilder.addArrowStarOverloads();
8857     break;
8858 
8859   case OO_Conditional:
8860     OpBuilder.addConditionalOperatorOverloads();
8861     OpBuilder.addGenericBinaryArithmeticOverloads();
8862     break;
8863   }
8864 }
8865 
8866 /// Add function candidates found via argument-dependent lookup
8867 /// to the set of overloading candidates.
8868 ///
8869 /// This routine performs argument-dependent name lookup based on the
8870 /// given function name (which may also be an operator name) and adds
8871 /// all of the overload candidates found by ADL to the overload
8872 /// candidate set (C++ [basic.lookup.argdep]).
8873 void
8874 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8875                                            SourceLocation Loc,
8876                                            ArrayRef<Expr *> Args,
8877                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8878                                            OverloadCandidateSet& CandidateSet,
8879                                            bool PartialOverloading) {
8880   ADLResult Fns;
8881 
8882   // FIXME: This approach for uniquing ADL results (and removing
8883   // redundant candidates from the set) relies on pointer-equality,
8884   // which means we need to key off the canonical decl.  However,
8885   // always going back to the canonical decl might not get us the
8886   // right set of default arguments.  What default arguments are
8887   // we supposed to consider on ADL candidates, anyway?
8888 
8889   // FIXME: Pass in the explicit template arguments?
8890   ArgumentDependentLookup(Name, Loc, Args, Fns);
8891 
8892   // Erase all of the candidates we already knew about.
8893   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8894                                    CandEnd = CandidateSet.end();
8895        Cand != CandEnd; ++Cand)
8896     if (Cand->Function) {
8897       Fns.erase(Cand->Function);
8898       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8899         Fns.erase(FunTmpl);
8900     }
8901 
8902   // For each of the ADL candidates we found, add it to the overload
8903   // set.
8904   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8905     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8906     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8907       if (ExplicitTemplateArgs)
8908         continue;
8909 
8910       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8911                            PartialOverloading);
8912     } else
8913       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8914                                    FoundDecl, ExplicitTemplateArgs,
8915                                    Args, CandidateSet, PartialOverloading);
8916   }
8917 }
8918 
8919 namespace {
8920 enum class Comparison { Equal, Better, Worse };
8921 }
8922 
8923 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8924 /// overload resolution.
8925 ///
8926 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8927 /// Cand1's first N enable_if attributes have precisely the same conditions as
8928 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8929 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8930 ///
8931 /// Note that you can have a pair of candidates such that Cand1's enable_if
8932 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8933 /// worse than Cand1's.
8934 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8935                                        const FunctionDecl *Cand2) {
8936   // Common case: One (or both) decls don't have enable_if attrs.
8937   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8938   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8939   if (!Cand1Attr || !Cand2Attr) {
8940     if (Cand1Attr == Cand2Attr)
8941       return Comparison::Equal;
8942     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8943   }
8944 
8945   // FIXME: The next several lines are just
8946   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8947   // instead of reverse order which is how they're stored in the AST.
8948   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8949   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8950 
8951   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8952   // has fewer enable_if attributes than Cand2.
8953   if (Cand1Attrs.size() < Cand2Attrs.size())
8954     return Comparison::Worse;
8955 
8956   auto Cand1I = Cand1Attrs.begin();
8957   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8958   for (auto &Cand2A : Cand2Attrs) {
8959     Cand1ID.clear();
8960     Cand2ID.clear();
8961 
8962     auto &Cand1A = *Cand1I++;
8963     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8964     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8965     if (Cand1ID != Cand2ID)
8966       return Comparison::Worse;
8967   }
8968 
8969   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8970 }
8971 
8972 /// isBetterOverloadCandidate - Determines whether the first overload
8973 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8974 bool clang::isBetterOverloadCandidate(
8975     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8976     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8977   // Define viable functions to be better candidates than non-viable
8978   // functions.
8979   if (!Cand2.Viable)
8980     return Cand1.Viable;
8981   else if (!Cand1.Viable)
8982     return false;
8983 
8984   // C++ [over.match.best]p1:
8985   //
8986   //   -- if F is a static member function, ICS1(F) is defined such
8987   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8988   //      any function G, and, symmetrically, ICS1(G) is neither
8989   //      better nor worse than ICS1(F).
8990   unsigned StartArg = 0;
8991   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8992     StartArg = 1;
8993 
8994   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8995     // We don't allow incompatible pointer conversions in C++.
8996     if (!S.getLangOpts().CPlusPlus)
8997       return ICS.isStandard() &&
8998              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8999 
9000     // The only ill-formed conversion we allow in C++ is the string literal to
9001     // char* conversion, which is only considered ill-formed after C++11.
9002     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9003            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9004   };
9005 
9006   // Define functions that don't require ill-formed conversions for a given
9007   // argument to be better candidates than functions that do.
9008   unsigned NumArgs = Cand1.Conversions.size();
9009   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9010   bool HasBetterConversion = false;
9011   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9012     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9013     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9014     if (Cand1Bad != Cand2Bad) {
9015       if (Cand1Bad)
9016         return false;
9017       HasBetterConversion = true;
9018     }
9019   }
9020 
9021   if (HasBetterConversion)
9022     return true;
9023 
9024   // C++ [over.match.best]p1:
9025   //   A viable function F1 is defined to be a better function than another
9026   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9027   //   conversion sequence than ICSi(F2), and then...
9028   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9029     switch (CompareImplicitConversionSequences(S, Loc,
9030                                                Cand1.Conversions[ArgIdx],
9031                                                Cand2.Conversions[ArgIdx])) {
9032     case ImplicitConversionSequence::Better:
9033       // Cand1 has a better conversion sequence.
9034       HasBetterConversion = true;
9035       break;
9036 
9037     case ImplicitConversionSequence::Worse:
9038       // Cand1 can't be better than Cand2.
9039       return false;
9040 
9041     case ImplicitConversionSequence::Indistinguishable:
9042       // Do nothing.
9043       break;
9044     }
9045   }
9046 
9047   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9048   //       ICSj(F2), or, if not that,
9049   if (HasBetterConversion)
9050     return true;
9051 
9052   //   -- the context is an initialization by user-defined conversion
9053   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9054   //      from the return type of F1 to the destination type (i.e.,
9055   //      the type of the entity being initialized) is a better
9056   //      conversion sequence than the standard conversion sequence
9057   //      from the return type of F2 to the destination type.
9058   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9059       Cand1.Function && Cand2.Function &&
9060       isa<CXXConversionDecl>(Cand1.Function) &&
9061       isa<CXXConversionDecl>(Cand2.Function)) {
9062     // First check whether we prefer one of the conversion functions over the
9063     // other. This only distinguishes the results in non-standard, extension
9064     // cases such as the conversion from a lambda closure type to a function
9065     // pointer or block.
9066     ImplicitConversionSequence::CompareKind Result =
9067         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9068     if (Result == ImplicitConversionSequence::Indistinguishable)
9069       Result = CompareStandardConversionSequences(S, Loc,
9070                                                   Cand1.FinalConversion,
9071                                                   Cand2.FinalConversion);
9072 
9073     if (Result != ImplicitConversionSequence::Indistinguishable)
9074       return Result == ImplicitConversionSequence::Better;
9075 
9076     // FIXME: Compare kind of reference binding if conversion functions
9077     // convert to a reference type used in direct reference binding, per
9078     // C++14 [over.match.best]p1 section 2 bullet 3.
9079   }
9080 
9081   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9082   // as combined with the resolution to CWG issue 243.
9083   //
9084   // When the context is initialization by constructor ([over.match.ctor] or
9085   // either phase of [over.match.list]), a constructor is preferred over
9086   // a conversion function.
9087   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9088       Cand1.Function && Cand2.Function &&
9089       isa<CXXConstructorDecl>(Cand1.Function) !=
9090           isa<CXXConstructorDecl>(Cand2.Function))
9091     return isa<CXXConstructorDecl>(Cand1.Function);
9092 
9093   //    -- F1 is a non-template function and F2 is a function template
9094   //       specialization, or, if not that,
9095   bool Cand1IsSpecialization = Cand1.Function &&
9096                                Cand1.Function->getPrimaryTemplate();
9097   bool Cand2IsSpecialization = Cand2.Function &&
9098                                Cand2.Function->getPrimaryTemplate();
9099   if (Cand1IsSpecialization != Cand2IsSpecialization)
9100     return Cand2IsSpecialization;
9101 
9102   //   -- F1 and F2 are function template specializations, and the function
9103   //      template for F1 is more specialized than the template for F2
9104   //      according to the partial ordering rules described in 14.5.5.2, or,
9105   //      if not that,
9106   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9107     if (FunctionTemplateDecl *BetterTemplate
9108           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9109                                          Cand2.Function->getPrimaryTemplate(),
9110                                          Loc,
9111                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9112                                                              : TPOC_Call,
9113                                          Cand1.ExplicitCallArguments,
9114                                          Cand2.ExplicitCallArguments))
9115       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9116   }
9117 
9118   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9119   // A derived-class constructor beats an (inherited) base class constructor.
9120   bool Cand1IsInherited =
9121       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9122   bool Cand2IsInherited =
9123       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9124   if (Cand1IsInherited != Cand2IsInherited)
9125     return Cand2IsInherited;
9126   else if (Cand1IsInherited) {
9127     assert(Cand2IsInherited);
9128     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9129     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9130     if (Cand1Class->isDerivedFrom(Cand2Class))
9131       return true;
9132     if (Cand2Class->isDerivedFrom(Cand1Class))
9133       return false;
9134     // Inherited from sibling base classes: still ambiguous.
9135   }
9136 
9137   // Check C++17 tie-breakers for deduction guides.
9138   {
9139     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9140     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9141     if (Guide1 && Guide2) {
9142       //  -- F1 is generated from a deduction-guide and F2 is not
9143       if (Guide1->isImplicit() != Guide2->isImplicit())
9144         return Guide2->isImplicit();
9145 
9146       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9147       if (Guide1->isCopyDeductionCandidate())
9148         return true;
9149     }
9150   }
9151 
9152   // Check for enable_if value-based overload resolution.
9153   if (Cand1.Function && Cand2.Function) {
9154     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9155     if (Cmp != Comparison::Equal)
9156       return Cmp == Comparison::Better;
9157   }
9158 
9159   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9160     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9161     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9162            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9163   }
9164 
9165   bool HasPS1 = Cand1.Function != nullptr &&
9166                 functionHasPassObjectSizeParams(Cand1.Function);
9167   bool HasPS2 = Cand2.Function != nullptr &&
9168                 functionHasPassObjectSizeParams(Cand2.Function);
9169   return HasPS1 != HasPS2 && HasPS1;
9170 }
9171 
9172 /// Determine whether two declarations are "equivalent" for the purposes of
9173 /// name lookup and overload resolution. This applies when the same internal/no
9174 /// linkage entity is defined by two modules (probably by textually including
9175 /// the same header). In such a case, we don't consider the declarations to
9176 /// declare the same entity, but we also don't want lookups with both
9177 /// declarations visible to be ambiguous in some cases (this happens when using
9178 /// a modularized libstdc++).
9179 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9180                                                   const NamedDecl *B) {
9181   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9182   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9183   if (!VA || !VB)
9184     return false;
9185 
9186   // The declarations must be declaring the same name as an internal linkage
9187   // entity in different modules.
9188   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9189           VB->getDeclContext()->getRedeclContext()) ||
9190       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9191           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9192       VA->isExternallyVisible() || VB->isExternallyVisible())
9193     return false;
9194 
9195   // Check that the declarations appear to be equivalent.
9196   //
9197   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9198   // For constants and functions, we should check the initializer or body is
9199   // the same. For non-constant variables, we shouldn't allow it at all.
9200   if (Context.hasSameType(VA->getType(), VB->getType()))
9201     return true;
9202 
9203   // Enum constants within unnamed enumerations will have different types, but
9204   // may still be similar enough to be interchangeable for our purposes.
9205   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9206     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9207       // Only handle anonymous enums. If the enumerations were named and
9208       // equivalent, they would have been merged to the same type.
9209       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9210       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9211       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9212           !Context.hasSameType(EnumA->getIntegerType(),
9213                                EnumB->getIntegerType()))
9214         return false;
9215       // Allow this only if the value is the same for both enumerators.
9216       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9217     }
9218   }
9219 
9220   // Nothing else is sufficiently similar.
9221   return false;
9222 }
9223 
9224 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9225     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9226   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9227 
9228   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9229   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9230       << !M << (M ? M->getFullModuleName() : "");
9231 
9232   for (auto *E : Equiv) {
9233     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9234     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9235         << !M << (M ? M->getFullModuleName() : "");
9236   }
9237 }
9238 
9239 /// Computes the best viable function (C++ 13.3.3)
9240 /// within an overload candidate set.
9241 ///
9242 /// \param Loc The location of the function name (or operator symbol) for
9243 /// which overload resolution occurs.
9244 ///
9245 /// \param Best If overload resolution was successful or found a deleted
9246 /// function, \p Best points to the candidate function found.
9247 ///
9248 /// \returns The result of overload resolution.
9249 OverloadingResult
9250 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9251                                          iterator &Best) {
9252   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9253   std::transform(begin(), end(), std::back_inserter(Candidates),
9254                  [](OverloadCandidate &Cand) { return &Cand; });
9255 
9256   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9257   // are accepted by both clang and NVCC. However, during a particular
9258   // compilation mode only one call variant is viable. We need to
9259   // exclude non-viable overload candidates from consideration based
9260   // only on their host/device attributes. Specifically, if one
9261   // candidate call is WrongSide and the other is SameSide, we ignore
9262   // the WrongSide candidate.
9263   if (S.getLangOpts().CUDA) {
9264     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9265     bool ContainsSameSideCandidate =
9266         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9267           return Cand->Function &&
9268                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9269                      Sema::CFP_SameSide;
9270         });
9271     if (ContainsSameSideCandidate) {
9272       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9273         return Cand->Function &&
9274                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9275                    Sema::CFP_WrongSide;
9276       };
9277       llvm::erase_if(Candidates, IsWrongSideCandidate);
9278     }
9279   }
9280 
9281   // Find the best viable function.
9282   Best = end();
9283   for (auto *Cand : Candidates)
9284     if (Cand->Viable)
9285       if (Best == end() ||
9286           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9287         Best = Cand;
9288 
9289   // If we didn't find any viable functions, abort.
9290   if (Best == end())
9291     return OR_No_Viable_Function;
9292 
9293   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9294 
9295   // Make sure that this function is better than every other viable
9296   // function. If not, we have an ambiguity.
9297   for (auto *Cand : Candidates) {
9298     if (Cand->Viable && Cand != Best &&
9299         !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9300       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9301                                                    Cand->Function)) {
9302         EquivalentCands.push_back(Cand->Function);
9303         continue;
9304       }
9305 
9306       Best = end();
9307       return OR_Ambiguous;
9308     }
9309   }
9310 
9311   // Best is the best viable function.
9312   if (Best->Function &&
9313       (Best->Function->isDeleted() ||
9314        S.isFunctionConsideredUnavailable(Best->Function)))
9315     return OR_Deleted;
9316 
9317   if (!EquivalentCands.empty())
9318     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9319                                                     EquivalentCands);
9320 
9321   return OR_Success;
9322 }
9323 
9324 namespace {
9325 
9326 enum OverloadCandidateKind {
9327   oc_function,
9328   oc_method,
9329   oc_constructor,
9330   oc_function_template,
9331   oc_method_template,
9332   oc_constructor_template,
9333   oc_implicit_default_constructor,
9334   oc_implicit_copy_constructor,
9335   oc_implicit_move_constructor,
9336   oc_implicit_copy_assignment,
9337   oc_implicit_move_assignment,
9338   oc_inherited_constructor,
9339   oc_inherited_constructor_template
9340 };
9341 
9342 static OverloadCandidateKind
9343 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9344                           std::string &Description) {
9345   bool isTemplate = false;
9346 
9347   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9348     isTemplate = true;
9349     Description = S.getTemplateArgumentBindingsText(
9350       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9351   }
9352 
9353   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9354     if (!Ctor->isImplicit()) {
9355       if (isa<ConstructorUsingShadowDecl>(Found))
9356         return isTemplate ? oc_inherited_constructor_template
9357                           : oc_inherited_constructor;
9358       else
9359         return isTemplate ? oc_constructor_template : oc_constructor;
9360     }
9361 
9362     if (Ctor->isDefaultConstructor())
9363       return oc_implicit_default_constructor;
9364 
9365     if (Ctor->isMoveConstructor())
9366       return oc_implicit_move_constructor;
9367 
9368     assert(Ctor->isCopyConstructor() &&
9369            "unexpected sort of implicit constructor");
9370     return oc_implicit_copy_constructor;
9371   }
9372 
9373   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9374     // This actually gets spelled 'candidate function' for now, but
9375     // it doesn't hurt to split it out.
9376     if (!Meth->isImplicit())
9377       return isTemplate ? oc_method_template : oc_method;
9378 
9379     if (Meth->isMoveAssignmentOperator())
9380       return oc_implicit_move_assignment;
9381 
9382     if (Meth->isCopyAssignmentOperator())
9383       return oc_implicit_copy_assignment;
9384 
9385     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9386     return oc_method;
9387   }
9388 
9389   return isTemplate ? oc_function_template : oc_function;
9390 }
9391 
9392 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9393   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9394   // set.
9395   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9396     S.Diag(FoundDecl->getLocation(),
9397            diag::note_ovl_candidate_inherited_constructor)
9398       << Shadow->getNominatedBaseClass();
9399 }
9400 
9401 } // end anonymous namespace
9402 
9403 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9404                                     const FunctionDecl *FD) {
9405   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9406     bool AlwaysTrue;
9407     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9408       return false;
9409     if (!AlwaysTrue)
9410       return false;
9411   }
9412   return true;
9413 }
9414 
9415 /// Returns true if we can take the address of the function.
9416 ///
9417 /// \param Complain - If true, we'll emit a diagnostic
9418 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9419 ///   we in overload resolution?
9420 /// \param Loc - The location of the statement we're complaining about. Ignored
9421 ///   if we're not complaining, or if we're in overload resolution.
9422 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9423                                               bool Complain,
9424                                               bool InOverloadResolution,
9425                                               SourceLocation Loc) {
9426   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9427     if (Complain) {
9428       if (InOverloadResolution)
9429         S.Diag(FD->getLocStart(),
9430                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9431       else
9432         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9433     }
9434     return false;
9435   }
9436 
9437   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9438     return P->hasAttr<PassObjectSizeAttr>();
9439   });
9440   if (I == FD->param_end())
9441     return true;
9442 
9443   if (Complain) {
9444     // Add one to ParamNo because it's user-facing
9445     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9446     if (InOverloadResolution)
9447       S.Diag(FD->getLocation(),
9448              diag::note_ovl_candidate_has_pass_object_size_params)
9449           << ParamNo;
9450     else
9451       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9452           << FD << ParamNo;
9453   }
9454   return false;
9455 }
9456 
9457 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9458                                                const FunctionDecl *FD) {
9459   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9460                                            /*InOverloadResolution=*/true,
9461                                            /*Loc=*/SourceLocation());
9462 }
9463 
9464 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9465                                              bool Complain,
9466                                              SourceLocation Loc) {
9467   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9468                                              /*InOverloadResolution=*/false,
9469                                              Loc);
9470 }
9471 
9472 // Notes the location of an overload candidate.
9473 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9474                                  QualType DestType, bool TakingAddress) {
9475   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9476     return;
9477   if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9478     return;
9479 
9480   std::string FnDesc;
9481   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9482   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9483                              << (unsigned) K << Fn << FnDesc;
9484 
9485   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9486   Diag(Fn->getLocation(), PD);
9487   MaybeEmitInheritedConstructorNote(*this, Found);
9488 }
9489 
9490 // Notes the location of all overload candidates designated through
9491 // OverloadedExpr
9492 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9493                                      bool TakingAddress) {
9494   assert(OverloadedExpr->getType() == Context.OverloadTy);
9495 
9496   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9497   OverloadExpr *OvlExpr = Ovl.Expression;
9498 
9499   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9500                             IEnd = OvlExpr->decls_end();
9501        I != IEnd; ++I) {
9502     if (FunctionTemplateDecl *FunTmpl =
9503                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9504       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9505                             TakingAddress);
9506     } else if (FunctionDecl *Fun
9507                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9508       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9509     }
9510   }
9511 }
9512 
9513 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9514 /// "lead" diagnostic; it will be given two arguments, the source and
9515 /// target types of the conversion.
9516 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9517                                  Sema &S,
9518                                  SourceLocation CaretLoc,
9519                                  const PartialDiagnostic &PDiag) const {
9520   S.Diag(CaretLoc, PDiag)
9521     << Ambiguous.getFromType() << Ambiguous.getToType();
9522   // FIXME: The note limiting machinery is borrowed from
9523   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9524   // refactoring here.
9525   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9526   unsigned CandsShown = 0;
9527   AmbiguousConversionSequence::const_iterator I, E;
9528   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9529     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9530       break;
9531     ++CandsShown;
9532     S.NoteOverloadCandidate(I->first, I->second);
9533   }
9534   if (I != E)
9535     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9536 }
9537 
9538 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9539                                   unsigned I, bool TakingCandidateAddress) {
9540   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9541   assert(Conv.isBad());
9542   assert(Cand->Function && "for now, candidate must be a function");
9543   FunctionDecl *Fn = Cand->Function;
9544 
9545   // There's a conversion slot for the object argument if this is a
9546   // non-constructor method.  Note that 'I' corresponds the
9547   // conversion-slot index.
9548   bool isObjectArgument = false;
9549   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9550     if (I == 0)
9551       isObjectArgument = true;
9552     else
9553       I--;
9554   }
9555 
9556   std::string FnDesc;
9557   OverloadCandidateKind FnKind =
9558       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9559 
9560   Expr *FromExpr = Conv.Bad.FromExpr;
9561   QualType FromTy = Conv.Bad.getFromType();
9562   QualType ToTy = Conv.Bad.getToType();
9563 
9564   if (FromTy == S.Context.OverloadTy) {
9565     assert(FromExpr && "overload set argument came from implicit argument?");
9566     Expr *E = FromExpr->IgnoreParens();
9567     if (isa<UnaryOperator>(E))
9568       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9569     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9570 
9571     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9572       << (unsigned) FnKind << FnDesc
9573       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9574       << ToTy << Name << I+1;
9575     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9576     return;
9577   }
9578 
9579   // Do some hand-waving analysis to see if the non-viability is due
9580   // to a qualifier mismatch.
9581   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9582   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9583   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9584     CToTy = RT->getPointeeType();
9585   else {
9586     // TODO: detect and diagnose the full richness of const mismatches.
9587     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9588       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9589         CFromTy = FromPT->getPointeeType();
9590         CToTy = ToPT->getPointeeType();
9591       }
9592   }
9593 
9594   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9595       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9596     Qualifiers FromQs = CFromTy.getQualifiers();
9597     Qualifiers ToQs = CToTy.getQualifiers();
9598 
9599     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9600       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9601         << (unsigned) FnKind << FnDesc
9602         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9603         << FromTy
9604         << FromQs.getAddressSpaceAttributePrintValue()
9605         << ToQs.getAddressSpaceAttributePrintValue()
9606         << (unsigned) isObjectArgument << I+1;
9607       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9608       return;
9609     }
9610 
9611     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9612       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9613         << (unsigned) FnKind << FnDesc
9614         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9615         << FromTy
9616         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9617         << (unsigned) isObjectArgument << I+1;
9618       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9619       return;
9620     }
9621 
9622     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9623       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9624       << (unsigned) FnKind << FnDesc
9625       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9626       << FromTy
9627       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9628       << (unsigned) isObjectArgument << I+1;
9629       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9630       return;
9631     }
9632 
9633     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9634       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9635         << (unsigned) FnKind << FnDesc
9636         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9637         << FromTy << FromQs.hasUnaligned() << I+1;
9638       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9639       return;
9640     }
9641 
9642     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9643     assert(CVR && "unexpected qualifiers mismatch");
9644 
9645     if (isObjectArgument) {
9646       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9647         << (unsigned) FnKind << FnDesc
9648         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9649         << FromTy << (CVR - 1);
9650     } else {
9651       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9652         << (unsigned) FnKind << FnDesc
9653         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9654         << FromTy << (CVR - 1) << I+1;
9655     }
9656     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9657     return;
9658   }
9659 
9660   // Special diagnostic for failure to convert an initializer list, since
9661   // telling the user that it has type void is not useful.
9662   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9663     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9664       << (unsigned) FnKind << FnDesc
9665       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9666       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9667     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9668     return;
9669   }
9670 
9671   // Diagnose references or pointers to incomplete types differently,
9672   // since it's far from impossible that the incompleteness triggered
9673   // the failure.
9674   QualType TempFromTy = FromTy.getNonReferenceType();
9675   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9676     TempFromTy = PTy->getPointeeType();
9677   if (TempFromTy->isIncompleteType()) {
9678     // Emit the generic diagnostic and, optionally, add the hints to it.
9679     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9680       << (unsigned) FnKind << FnDesc
9681       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9682       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9683       << (unsigned) (Cand->Fix.Kind);
9684 
9685     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9686     return;
9687   }
9688 
9689   // Diagnose base -> derived pointer conversions.
9690   unsigned BaseToDerivedConversion = 0;
9691   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9692     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9693       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9694                                                FromPtrTy->getPointeeType()) &&
9695           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9696           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9697           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9698                           FromPtrTy->getPointeeType()))
9699         BaseToDerivedConversion = 1;
9700     }
9701   } else if (const ObjCObjectPointerType *FromPtrTy
9702                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9703     if (const ObjCObjectPointerType *ToPtrTy
9704                                         = ToTy->getAs<ObjCObjectPointerType>())
9705       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9706         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9707           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9708                                                 FromPtrTy->getPointeeType()) &&
9709               FromIface->isSuperClassOf(ToIface))
9710             BaseToDerivedConversion = 2;
9711   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9712     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9713         !FromTy->isIncompleteType() &&
9714         !ToRefTy->getPointeeType()->isIncompleteType() &&
9715         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9716       BaseToDerivedConversion = 3;
9717     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9718                ToTy.getNonReferenceType().getCanonicalType() ==
9719                FromTy.getNonReferenceType().getCanonicalType()) {
9720       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9721         << (unsigned) FnKind << FnDesc
9722         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9723         << (unsigned) isObjectArgument << I + 1;
9724       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9725       return;
9726     }
9727   }
9728 
9729   if (BaseToDerivedConversion) {
9730     S.Diag(Fn->getLocation(),
9731            diag::note_ovl_candidate_bad_base_to_derived_conv)
9732       << (unsigned) FnKind << FnDesc
9733       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9734       << (BaseToDerivedConversion - 1)
9735       << FromTy << ToTy << I+1;
9736     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9737     return;
9738   }
9739 
9740   if (isa<ObjCObjectPointerType>(CFromTy) &&
9741       isa<PointerType>(CToTy)) {
9742       Qualifiers FromQs = CFromTy.getQualifiers();
9743       Qualifiers ToQs = CToTy.getQualifiers();
9744       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9745         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9746         << (unsigned) FnKind << FnDesc
9747         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9748         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9749         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9750         return;
9751       }
9752   }
9753 
9754   if (TakingCandidateAddress &&
9755       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9756     return;
9757 
9758   // Emit the generic diagnostic and, optionally, add the hints to it.
9759   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9760   FDiag << (unsigned) FnKind << FnDesc
9761     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9762     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9763     << (unsigned) (Cand->Fix.Kind);
9764 
9765   // If we can fix the conversion, suggest the FixIts.
9766   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9767        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9768     FDiag << *HI;
9769   S.Diag(Fn->getLocation(), FDiag);
9770 
9771   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9772 }
9773 
9774 /// Additional arity mismatch diagnosis specific to a function overload
9775 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9776 /// over a candidate in any candidate set.
9777 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9778                                unsigned NumArgs) {
9779   FunctionDecl *Fn = Cand->Function;
9780   unsigned MinParams = Fn->getMinRequiredArguments();
9781 
9782   // With invalid overloaded operators, it's possible that we think we
9783   // have an arity mismatch when in fact it looks like we have the
9784   // right number of arguments, because only overloaded operators have
9785   // the weird behavior of overloading member and non-member functions.
9786   // Just don't report anything.
9787   if (Fn->isInvalidDecl() &&
9788       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9789     return true;
9790 
9791   if (NumArgs < MinParams) {
9792     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9793            (Cand->FailureKind == ovl_fail_bad_deduction &&
9794             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9795   } else {
9796     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9797            (Cand->FailureKind == ovl_fail_bad_deduction &&
9798             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9799   }
9800 
9801   return false;
9802 }
9803 
9804 /// General arity mismatch diagnosis over a candidate in a candidate set.
9805 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9806                                   unsigned NumFormalArgs) {
9807   assert(isa<FunctionDecl>(D) &&
9808       "The templated declaration should at least be a function"
9809       " when diagnosing bad template argument deduction due to too many"
9810       " or too few arguments");
9811 
9812   FunctionDecl *Fn = cast<FunctionDecl>(D);
9813 
9814   // TODO: treat calls to a missing default constructor as a special case
9815   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9816   unsigned MinParams = Fn->getMinRequiredArguments();
9817 
9818   // at least / at most / exactly
9819   unsigned mode, modeCount;
9820   if (NumFormalArgs < MinParams) {
9821     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9822         FnTy->isTemplateVariadic())
9823       mode = 0; // "at least"
9824     else
9825       mode = 2; // "exactly"
9826     modeCount = MinParams;
9827   } else {
9828     if (MinParams != FnTy->getNumParams())
9829       mode = 1; // "at most"
9830     else
9831       mode = 2; // "exactly"
9832     modeCount = FnTy->getNumParams();
9833   }
9834 
9835   std::string Description;
9836   OverloadCandidateKind FnKind =
9837       ClassifyOverloadCandidate(S, Found, Fn, Description);
9838 
9839   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9840     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9841       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9842       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9843   else
9844     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9845       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9846       << mode << modeCount << NumFormalArgs;
9847   MaybeEmitInheritedConstructorNote(S, Found);
9848 }
9849 
9850 /// Arity mismatch diagnosis specific to a function overload candidate.
9851 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9852                                   unsigned NumFormalArgs) {
9853   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9854     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9855 }
9856 
9857 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9858   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9859     return TD;
9860   llvm_unreachable("Unsupported: Getting the described template declaration"
9861                    " for bad deduction diagnosis");
9862 }
9863 
9864 /// Diagnose a failed template-argument deduction.
9865 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9866                                  DeductionFailureInfo &DeductionFailure,
9867                                  unsigned NumArgs,
9868                                  bool TakingCandidateAddress) {
9869   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9870   NamedDecl *ParamD;
9871   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9872   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9873   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9874   switch (DeductionFailure.Result) {
9875   case Sema::TDK_Success:
9876     llvm_unreachable("TDK_success while diagnosing bad deduction");
9877 
9878   case Sema::TDK_Incomplete: {
9879     assert(ParamD && "no parameter found for incomplete deduction result");
9880     S.Diag(Templated->getLocation(),
9881            diag::note_ovl_candidate_incomplete_deduction)
9882         << ParamD->getDeclName();
9883     MaybeEmitInheritedConstructorNote(S, Found);
9884     return;
9885   }
9886 
9887   case Sema::TDK_Underqualified: {
9888     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9889     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9890 
9891     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9892 
9893     // Param will have been canonicalized, but it should just be a
9894     // qualified version of ParamD, so move the qualifiers to that.
9895     QualifierCollector Qs;
9896     Qs.strip(Param);
9897     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9898     assert(S.Context.hasSameType(Param, NonCanonParam));
9899 
9900     // Arg has also been canonicalized, but there's nothing we can do
9901     // about that.  It also doesn't matter as much, because it won't
9902     // have any template parameters in it (because deduction isn't
9903     // done on dependent types).
9904     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9905 
9906     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9907         << ParamD->getDeclName() << Arg << NonCanonParam;
9908     MaybeEmitInheritedConstructorNote(S, Found);
9909     return;
9910   }
9911 
9912   case Sema::TDK_Inconsistent: {
9913     assert(ParamD && "no parameter found for inconsistent deduction result");
9914     int which = 0;
9915     if (isa<TemplateTypeParmDecl>(ParamD))
9916       which = 0;
9917     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9918       // Deduction might have failed because we deduced arguments of two
9919       // different types for a non-type template parameter.
9920       // FIXME: Use a different TDK value for this.
9921       QualType T1 =
9922           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9923       QualType T2 =
9924           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9925       if (!S.Context.hasSameType(T1, T2)) {
9926         S.Diag(Templated->getLocation(),
9927                diag::note_ovl_candidate_inconsistent_deduction_types)
9928           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9929           << *DeductionFailure.getSecondArg() << T2;
9930         MaybeEmitInheritedConstructorNote(S, Found);
9931         return;
9932       }
9933 
9934       which = 1;
9935     } else {
9936       which = 2;
9937     }
9938 
9939     S.Diag(Templated->getLocation(),
9940            diag::note_ovl_candidate_inconsistent_deduction)
9941         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9942         << *DeductionFailure.getSecondArg();
9943     MaybeEmitInheritedConstructorNote(S, Found);
9944     return;
9945   }
9946 
9947   case Sema::TDK_InvalidExplicitArguments:
9948     assert(ParamD && "no parameter found for invalid explicit arguments");
9949     if (ParamD->getDeclName())
9950       S.Diag(Templated->getLocation(),
9951              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9952           << ParamD->getDeclName();
9953     else {
9954       int index = 0;
9955       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9956         index = TTP->getIndex();
9957       else if (NonTypeTemplateParmDecl *NTTP
9958                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9959         index = NTTP->getIndex();
9960       else
9961         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9962       S.Diag(Templated->getLocation(),
9963              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9964           << (index + 1);
9965     }
9966     MaybeEmitInheritedConstructorNote(S, Found);
9967     return;
9968 
9969   case Sema::TDK_TooManyArguments:
9970   case Sema::TDK_TooFewArguments:
9971     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9972     return;
9973 
9974   case Sema::TDK_InstantiationDepth:
9975     S.Diag(Templated->getLocation(),
9976            diag::note_ovl_candidate_instantiation_depth);
9977     MaybeEmitInheritedConstructorNote(S, Found);
9978     return;
9979 
9980   case Sema::TDK_SubstitutionFailure: {
9981     // Format the template argument list into the argument string.
9982     SmallString<128> TemplateArgString;
9983     if (TemplateArgumentList *Args =
9984             DeductionFailure.getTemplateArgumentList()) {
9985       TemplateArgString = " ";
9986       TemplateArgString += S.getTemplateArgumentBindingsText(
9987           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9988     }
9989 
9990     // If this candidate was disabled by enable_if, say so.
9991     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9992     if (PDiag && PDiag->second.getDiagID() ==
9993           diag::err_typename_nested_not_found_enable_if) {
9994       // FIXME: Use the source range of the condition, and the fully-qualified
9995       //        name of the enable_if template. These are both present in PDiag.
9996       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9997         << "'enable_if'" << TemplateArgString;
9998       return;
9999     }
10000 
10001     // We found a specific requirement that disabled the enable_if.
10002     if (PDiag && PDiag->second.getDiagID() ==
10003         diag::err_typename_nested_not_found_requirement) {
10004       S.Diag(Templated->getLocation(),
10005              diag::note_ovl_candidate_disabled_by_requirement)
10006         << PDiag->second.getStringArg(0) << TemplateArgString;
10007       return;
10008     }
10009 
10010     // Format the SFINAE diagnostic into the argument string.
10011     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10012     //        formatted message in another diagnostic.
10013     SmallString<128> SFINAEArgString;
10014     SourceRange R;
10015     if (PDiag) {
10016       SFINAEArgString = ": ";
10017       R = SourceRange(PDiag->first, PDiag->first);
10018       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10019     }
10020 
10021     S.Diag(Templated->getLocation(),
10022            diag::note_ovl_candidate_substitution_failure)
10023         << TemplateArgString << SFINAEArgString << R;
10024     MaybeEmitInheritedConstructorNote(S, Found);
10025     return;
10026   }
10027 
10028   case Sema::TDK_DeducedMismatch:
10029   case Sema::TDK_DeducedMismatchNested: {
10030     // Format the template argument list into the argument string.
10031     SmallString<128> TemplateArgString;
10032     if (TemplateArgumentList *Args =
10033             DeductionFailure.getTemplateArgumentList()) {
10034       TemplateArgString = " ";
10035       TemplateArgString += S.getTemplateArgumentBindingsText(
10036           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10037     }
10038 
10039     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10040         << (*DeductionFailure.getCallArgIndex() + 1)
10041         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10042         << TemplateArgString
10043         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10044     break;
10045   }
10046 
10047   case Sema::TDK_NonDeducedMismatch: {
10048     // FIXME: Provide a source location to indicate what we couldn't match.
10049     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10050     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10051     if (FirstTA.getKind() == TemplateArgument::Template &&
10052         SecondTA.getKind() == TemplateArgument::Template) {
10053       TemplateName FirstTN = FirstTA.getAsTemplate();
10054       TemplateName SecondTN = SecondTA.getAsTemplate();
10055       if (FirstTN.getKind() == TemplateName::Template &&
10056           SecondTN.getKind() == TemplateName::Template) {
10057         if (FirstTN.getAsTemplateDecl()->getName() ==
10058             SecondTN.getAsTemplateDecl()->getName()) {
10059           // FIXME: This fixes a bad diagnostic where both templates are named
10060           // the same.  This particular case is a bit difficult since:
10061           // 1) It is passed as a string to the diagnostic printer.
10062           // 2) The diagnostic printer only attempts to find a better
10063           //    name for types, not decls.
10064           // Ideally, this should folded into the diagnostic printer.
10065           S.Diag(Templated->getLocation(),
10066                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10067               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10068           return;
10069         }
10070       }
10071     }
10072 
10073     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10074         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10075       return;
10076 
10077     // FIXME: For generic lambda parameters, check if the function is a lambda
10078     // call operator, and if so, emit a prettier and more informative
10079     // diagnostic that mentions 'auto' and lambda in addition to
10080     // (or instead of?) the canonical template type parameters.
10081     S.Diag(Templated->getLocation(),
10082            diag::note_ovl_candidate_non_deduced_mismatch)
10083         << FirstTA << SecondTA;
10084     return;
10085   }
10086   // TODO: diagnose these individually, then kill off
10087   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10088   case Sema::TDK_MiscellaneousDeductionFailure:
10089     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10090     MaybeEmitInheritedConstructorNote(S, Found);
10091     return;
10092   case Sema::TDK_CUDATargetMismatch:
10093     S.Diag(Templated->getLocation(),
10094            diag::note_cuda_ovl_candidate_target_mismatch);
10095     return;
10096   }
10097 }
10098 
10099 /// Diagnose a failed template-argument deduction, for function calls.
10100 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10101                                  unsigned NumArgs,
10102                                  bool TakingCandidateAddress) {
10103   unsigned TDK = Cand->DeductionFailure.Result;
10104   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10105     if (CheckArityMismatch(S, Cand, NumArgs))
10106       return;
10107   }
10108   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10109                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10110 }
10111 
10112 /// CUDA: diagnose an invalid call across targets.
10113 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10114   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10115   FunctionDecl *Callee = Cand->Function;
10116 
10117   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10118                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10119 
10120   std::string FnDesc;
10121   OverloadCandidateKind FnKind =
10122       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10123 
10124   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10125       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10126 
10127   // This could be an implicit constructor for which we could not infer the
10128   // target due to a collsion. Diagnose that case.
10129   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10130   if (Meth != nullptr && Meth->isImplicit()) {
10131     CXXRecordDecl *ParentClass = Meth->getParent();
10132     Sema::CXXSpecialMember CSM;
10133 
10134     switch (FnKind) {
10135     default:
10136       return;
10137     case oc_implicit_default_constructor:
10138       CSM = Sema::CXXDefaultConstructor;
10139       break;
10140     case oc_implicit_copy_constructor:
10141       CSM = Sema::CXXCopyConstructor;
10142       break;
10143     case oc_implicit_move_constructor:
10144       CSM = Sema::CXXMoveConstructor;
10145       break;
10146     case oc_implicit_copy_assignment:
10147       CSM = Sema::CXXCopyAssignment;
10148       break;
10149     case oc_implicit_move_assignment:
10150       CSM = Sema::CXXMoveAssignment;
10151       break;
10152     };
10153 
10154     bool ConstRHS = false;
10155     if (Meth->getNumParams()) {
10156       if (const ReferenceType *RT =
10157               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10158         ConstRHS = RT->getPointeeType().isConstQualified();
10159       }
10160     }
10161 
10162     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10163                                               /* ConstRHS */ ConstRHS,
10164                                               /* Diagnose */ true);
10165   }
10166 }
10167 
10168 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10169   FunctionDecl *Callee = Cand->Function;
10170   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10171 
10172   S.Diag(Callee->getLocation(),
10173          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10174       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10175 }
10176 
10177 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10178   FunctionDecl *Callee = Cand->Function;
10179 
10180   S.Diag(Callee->getLocation(),
10181          diag::note_ovl_candidate_disabled_by_extension);
10182 }
10183 
10184 /// Generates a 'note' diagnostic for an overload candidate.  We've
10185 /// already generated a primary error at the call site.
10186 ///
10187 /// It really does need to be a single diagnostic with its caret
10188 /// pointed at the candidate declaration.  Yes, this creates some
10189 /// major challenges of technical writing.  Yes, this makes pointing
10190 /// out problems with specific arguments quite awkward.  It's still
10191 /// better than generating twenty screens of text for every failed
10192 /// overload.
10193 ///
10194 /// It would be great to be able to express per-candidate problems
10195 /// more richly for those diagnostic clients that cared, but we'd
10196 /// still have to be just as careful with the default diagnostics.
10197 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10198                                   unsigned NumArgs,
10199                                   bool TakingCandidateAddress) {
10200   FunctionDecl *Fn = Cand->Function;
10201 
10202   // Note deleted candidates, but only if they're viable.
10203   if (Cand->Viable) {
10204     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10205       std::string FnDesc;
10206       OverloadCandidateKind FnKind =
10207         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10208 
10209       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10210         << FnKind << FnDesc
10211         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10212       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10213       return;
10214     }
10215 
10216     // We don't really have anything else to say about viable candidates.
10217     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10218     return;
10219   }
10220 
10221   switch (Cand->FailureKind) {
10222   case ovl_fail_too_many_arguments:
10223   case ovl_fail_too_few_arguments:
10224     return DiagnoseArityMismatch(S, Cand, NumArgs);
10225 
10226   case ovl_fail_bad_deduction:
10227     return DiagnoseBadDeduction(S, Cand, NumArgs,
10228                                 TakingCandidateAddress);
10229 
10230   case ovl_fail_illegal_constructor: {
10231     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10232       << (Fn->getPrimaryTemplate() ? 1 : 0);
10233     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10234     return;
10235   }
10236 
10237   case ovl_fail_trivial_conversion:
10238   case ovl_fail_bad_final_conversion:
10239   case ovl_fail_final_conversion_not_exact:
10240     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10241 
10242   case ovl_fail_bad_conversion: {
10243     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10244     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10245       if (Cand->Conversions[I].isBad())
10246         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10247 
10248     // FIXME: this currently happens when we're called from SemaInit
10249     // when user-conversion overload fails.  Figure out how to handle
10250     // those conditions and diagnose them well.
10251     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10252   }
10253 
10254   case ovl_fail_bad_target:
10255     return DiagnoseBadTarget(S, Cand);
10256 
10257   case ovl_fail_enable_if:
10258     return DiagnoseFailedEnableIfAttr(S, Cand);
10259 
10260   case ovl_fail_ext_disabled:
10261     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10262 
10263   case ovl_fail_inhctor_slice:
10264     // It's generally not interesting to note copy/move constructors here.
10265     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10266       return;
10267     S.Diag(Fn->getLocation(),
10268            diag::note_ovl_candidate_inherited_constructor_slice)
10269       << (Fn->getPrimaryTemplate() ? 1 : 0)
10270       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10271     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10272     return;
10273 
10274   case ovl_fail_addr_not_available: {
10275     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10276     (void)Available;
10277     assert(!Available);
10278     break;
10279   }
10280   case ovl_non_default_multiversion_function:
10281     // Do nothing, these should simply be ignored.
10282     break;
10283   }
10284 }
10285 
10286 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10287   // Desugar the type of the surrogate down to a function type,
10288   // retaining as many typedefs as possible while still showing
10289   // the function type (and, therefore, its parameter types).
10290   QualType FnType = Cand->Surrogate->getConversionType();
10291   bool isLValueReference = false;
10292   bool isRValueReference = false;
10293   bool isPointer = false;
10294   if (const LValueReferenceType *FnTypeRef =
10295         FnType->getAs<LValueReferenceType>()) {
10296     FnType = FnTypeRef->getPointeeType();
10297     isLValueReference = true;
10298   } else if (const RValueReferenceType *FnTypeRef =
10299                FnType->getAs<RValueReferenceType>()) {
10300     FnType = FnTypeRef->getPointeeType();
10301     isRValueReference = true;
10302   }
10303   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10304     FnType = FnTypePtr->getPointeeType();
10305     isPointer = true;
10306   }
10307   // Desugar down to a function type.
10308   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10309   // Reconstruct the pointer/reference as appropriate.
10310   if (isPointer) FnType = S.Context.getPointerType(FnType);
10311   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10312   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10313 
10314   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10315     << FnType;
10316 }
10317 
10318 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10319                                          SourceLocation OpLoc,
10320                                          OverloadCandidate *Cand) {
10321   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10322   std::string TypeStr("operator");
10323   TypeStr += Opc;
10324   TypeStr += "(";
10325   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10326   if (Cand->Conversions.size() == 1) {
10327     TypeStr += ")";
10328     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10329   } else {
10330     TypeStr += ", ";
10331     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10332     TypeStr += ")";
10333     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10334   }
10335 }
10336 
10337 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10338                                          OverloadCandidate *Cand) {
10339   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10340     if (ICS.isBad()) break; // all meaningless after first invalid
10341     if (!ICS.isAmbiguous()) continue;
10342 
10343     ICS.DiagnoseAmbiguousConversion(
10344         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10345   }
10346 }
10347 
10348 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10349   if (Cand->Function)
10350     return Cand->Function->getLocation();
10351   if (Cand->IsSurrogate)
10352     return Cand->Surrogate->getLocation();
10353   return SourceLocation();
10354 }
10355 
10356 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10357   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10358   case Sema::TDK_Success:
10359   case Sema::TDK_NonDependentConversionFailure:
10360     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10361 
10362   case Sema::TDK_Invalid:
10363   case Sema::TDK_Incomplete:
10364     return 1;
10365 
10366   case Sema::TDK_Underqualified:
10367   case Sema::TDK_Inconsistent:
10368     return 2;
10369 
10370   case Sema::TDK_SubstitutionFailure:
10371   case Sema::TDK_DeducedMismatch:
10372   case Sema::TDK_DeducedMismatchNested:
10373   case Sema::TDK_NonDeducedMismatch:
10374   case Sema::TDK_MiscellaneousDeductionFailure:
10375   case Sema::TDK_CUDATargetMismatch:
10376     return 3;
10377 
10378   case Sema::TDK_InstantiationDepth:
10379     return 4;
10380 
10381   case Sema::TDK_InvalidExplicitArguments:
10382     return 5;
10383 
10384   case Sema::TDK_TooManyArguments:
10385   case Sema::TDK_TooFewArguments:
10386     return 6;
10387   }
10388   llvm_unreachable("Unhandled deduction result");
10389 }
10390 
10391 namespace {
10392 struct CompareOverloadCandidatesForDisplay {
10393   Sema &S;
10394   SourceLocation Loc;
10395   size_t NumArgs;
10396   OverloadCandidateSet::CandidateSetKind CSK;
10397 
10398   CompareOverloadCandidatesForDisplay(
10399       Sema &S, SourceLocation Loc, size_t NArgs,
10400       OverloadCandidateSet::CandidateSetKind CSK)
10401       : S(S), NumArgs(NArgs), CSK(CSK) {}
10402 
10403   bool operator()(const OverloadCandidate *L,
10404                   const OverloadCandidate *R) {
10405     // Fast-path this check.
10406     if (L == R) return false;
10407 
10408     // Order first by viability.
10409     if (L->Viable) {
10410       if (!R->Viable) return true;
10411 
10412       // TODO: introduce a tri-valued comparison for overload
10413       // candidates.  Would be more worthwhile if we had a sort
10414       // that could exploit it.
10415       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10416         return true;
10417       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10418         return false;
10419     } else if (R->Viable)
10420       return false;
10421 
10422     assert(L->Viable == R->Viable);
10423 
10424     // Criteria by which we can sort non-viable candidates:
10425     if (!L->Viable) {
10426       // 1. Arity mismatches come after other candidates.
10427       if (L->FailureKind == ovl_fail_too_many_arguments ||
10428           L->FailureKind == ovl_fail_too_few_arguments) {
10429         if (R->FailureKind == ovl_fail_too_many_arguments ||
10430             R->FailureKind == ovl_fail_too_few_arguments) {
10431           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10432           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10433           if (LDist == RDist) {
10434             if (L->FailureKind == R->FailureKind)
10435               // Sort non-surrogates before surrogates.
10436               return !L->IsSurrogate && R->IsSurrogate;
10437             // Sort candidates requiring fewer parameters than there were
10438             // arguments given after candidates requiring more parameters
10439             // than there were arguments given.
10440             return L->FailureKind == ovl_fail_too_many_arguments;
10441           }
10442           return LDist < RDist;
10443         }
10444         return false;
10445       }
10446       if (R->FailureKind == ovl_fail_too_many_arguments ||
10447           R->FailureKind == ovl_fail_too_few_arguments)
10448         return true;
10449 
10450       // 2. Bad conversions come first and are ordered by the number
10451       // of bad conversions and quality of good conversions.
10452       if (L->FailureKind == ovl_fail_bad_conversion) {
10453         if (R->FailureKind != ovl_fail_bad_conversion)
10454           return true;
10455 
10456         // The conversion that can be fixed with a smaller number of changes,
10457         // comes first.
10458         unsigned numLFixes = L->Fix.NumConversionsFixed;
10459         unsigned numRFixes = R->Fix.NumConversionsFixed;
10460         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10461         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10462         if (numLFixes != numRFixes) {
10463           return numLFixes < numRFixes;
10464         }
10465 
10466         // If there's any ordering between the defined conversions...
10467         // FIXME: this might not be transitive.
10468         assert(L->Conversions.size() == R->Conversions.size());
10469 
10470         int leftBetter = 0;
10471         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10472         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10473           switch (CompareImplicitConversionSequences(S, Loc,
10474                                                      L->Conversions[I],
10475                                                      R->Conversions[I])) {
10476           case ImplicitConversionSequence::Better:
10477             leftBetter++;
10478             break;
10479 
10480           case ImplicitConversionSequence::Worse:
10481             leftBetter--;
10482             break;
10483 
10484           case ImplicitConversionSequence::Indistinguishable:
10485             break;
10486           }
10487         }
10488         if (leftBetter > 0) return true;
10489         if (leftBetter < 0) return false;
10490 
10491       } else if (R->FailureKind == ovl_fail_bad_conversion)
10492         return false;
10493 
10494       if (L->FailureKind == ovl_fail_bad_deduction) {
10495         if (R->FailureKind != ovl_fail_bad_deduction)
10496           return true;
10497 
10498         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10499           return RankDeductionFailure(L->DeductionFailure)
10500                < RankDeductionFailure(R->DeductionFailure);
10501       } else if (R->FailureKind == ovl_fail_bad_deduction)
10502         return false;
10503 
10504       // TODO: others?
10505     }
10506 
10507     // Sort everything else by location.
10508     SourceLocation LLoc = GetLocationForCandidate(L);
10509     SourceLocation RLoc = GetLocationForCandidate(R);
10510 
10511     // Put candidates without locations (e.g. builtins) at the end.
10512     if (LLoc.isInvalid()) return false;
10513     if (RLoc.isInvalid()) return true;
10514 
10515     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10516   }
10517 };
10518 }
10519 
10520 /// CompleteNonViableCandidate - Normally, overload resolution only
10521 /// computes up to the first bad conversion. Produces the FixIt set if
10522 /// possible.
10523 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10524                                        ArrayRef<Expr *> Args) {
10525   assert(!Cand->Viable);
10526 
10527   // Don't do anything on failures other than bad conversion.
10528   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10529 
10530   // We only want the FixIts if all the arguments can be corrected.
10531   bool Unfixable = false;
10532   // Use a implicit copy initialization to check conversion fixes.
10533   Cand->Fix.setConversionChecker(TryCopyInitialization);
10534 
10535   // Attempt to fix the bad conversion.
10536   unsigned ConvCount = Cand->Conversions.size();
10537   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10538        ++ConvIdx) {
10539     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10540     if (Cand->Conversions[ConvIdx].isInitialized() &&
10541         Cand->Conversions[ConvIdx].isBad()) {
10542       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10543       break;
10544     }
10545   }
10546 
10547   // FIXME: this should probably be preserved from the overload
10548   // operation somehow.
10549   bool SuppressUserConversions = false;
10550 
10551   unsigned ConvIdx = 0;
10552   ArrayRef<QualType> ParamTypes;
10553 
10554   if (Cand->IsSurrogate) {
10555     QualType ConvType
10556       = Cand->Surrogate->getConversionType().getNonReferenceType();
10557     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10558       ConvType = ConvPtrType->getPointeeType();
10559     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10560     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10561     ConvIdx = 1;
10562   } else if (Cand->Function) {
10563     ParamTypes =
10564         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10565     if (isa<CXXMethodDecl>(Cand->Function) &&
10566         !isa<CXXConstructorDecl>(Cand->Function)) {
10567       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10568       ConvIdx = 1;
10569     }
10570   } else {
10571     // Builtin operator.
10572     assert(ConvCount <= 3);
10573     ParamTypes = Cand->BuiltinParamTypes;
10574   }
10575 
10576   // Fill in the rest of the conversions.
10577   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10578     if (Cand->Conversions[ConvIdx].isInitialized()) {
10579       // We've already checked this conversion.
10580     } else if (ArgIdx < ParamTypes.size()) {
10581       if (ParamTypes[ArgIdx]->isDependentType())
10582         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10583             Args[ArgIdx]->getType());
10584       else {
10585         Cand->Conversions[ConvIdx] =
10586             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10587                                   SuppressUserConversions,
10588                                   /*InOverloadResolution=*/true,
10589                                   /*AllowObjCWritebackConversion=*/
10590                                   S.getLangOpts().ObjCAutoRefCount);
10591         // Store the FixIt in the candidate if it exists.
10592         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10593           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10594       }
10595     } else
10596       Cand->Conversions[ConvIdx].setEllipsis();
10597   }
10598 }
10599 
10600 /// When overload resolution fails, prints diagnostic messages containing the
10601 /// candidates in the candidate set.
10602 void OverloadCandidateSet::NoteCandidates(
10603     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10604     StringRef Opc, SourceLocation OpLoc,
10605     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10606   // Sort the candidates by viability and position.  Sorting directly would
10607   // be prohibitive, so we make a set of pointers and sort those.
10608   SmallVector<OverloadCandidate*, 32> Cands;
10609   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10610   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10611     if (!Filter(*Cand))
10612       continue;
10613     if (Cand->Viable)
10614       Cands.push_back(Cand);
10615     else if (OCD == OCD_AllCandidates) {
10616       CompleteNonViableCandidate(S, Cand, Args);
10617       if (Cand->Function || Cand->IsSurrogate)
10618         Cands.push_back(Cand);
10619       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10620       // want to list every possible builtin candidate.
10621     }
10622   }
10623 
10624   std::stable_sort(Cands.begin(), Cands.end(),
10625             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10626 
10627   bool ReportedAmbiguousConversions = false;
10628 
10629   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10630   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10631   unsigned CandsShown = 0;
10632   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10633     OverloadCandidate *Cand = *I;
10634 
10635     // Set an arbitrary limit on the number of candidate functions we'll spam
10636     // the user with.  FIXME: This limit should depend on details of the
10637     // candidate list.
10638     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10639       break;
10640     }
10641     ++CandsShown;
10642 
10643     if (Cand->Function)
10644       NoteFunctionCandidate(S, Cand, Args.size(),
10645                             /*TakingCandidateAddress=*/false);
10646     else if (Cand->IsSurrogate)
10647       NoteSurrogateCandidate(S, Cand);
10648     else {
10649       assert(Cand->Viable &&
10650              "Non-viable built-in candidates are not added to Cands.");
10651       // Generally we only see ambiguities including viable builtin
10652       // operators if overload resolution got screwed up by an
10653       // ambiguous user-defined conversion.
10654       //
10655       // FIXME: It's quite possible for different conversions to see
10656       // different ambiguities, though.
10657       if (!ReportedAmbiguousConversions) {
10658         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10659         ReportedAmbiguousConversions = true;
10660       }
10661 
10662       // If this is a viable builtin, print it.
10663       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10664     }
10665   }
10666 
10667   if (I != E)
10668     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10669 }
10670 
10671 static SourceLocation
10672 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10673   return Cand->Specialization ? Cand->Specialization->getLocation()
10674                               : SourceLocation();
10675 }
10676 
10677 namespace {
10678 struct CompareTemplateSpecCandidatesForDisplay {
10679   Sema &S;
10680   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10681 
10682   bool operator()(const TemplateSpecCandidate *L,
10683                   const TemplateSpecCandidate *R) {
10684     // Fast-path this check.
10685     if (L == R)
10686       return false;
10687 
10688     // Assuming that both candidates are not matches...
10689 
10690     // Sort by the ranking of deduction failures.
10691     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10692       return RankDeductionFailure(L->DeductionFailure) <
10693              RankDeductionFailure(R->DeductionFailure);
10694 
10695     // Sort everything else by location.
10696     SourceLocation LLoc = GetLocationForCandidate(L);
10697     SourceLocation RLoc = GetLocationForCandidate(R);
10698 
10699     // Put candidates without locations (e.g. builtins) at the end.
10700     if (LLoc.isInvalid())
10701       return false;
10702     if (RLoc.isInvalid())
10703       return true;
10704 
10705     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10706   }
10707 };
10708 }
10709 
10710 /// Diagnose a template argument deduction failure.
10711 /// We are treating these failures as overload failures due to bad
10712 /// deductions.
10713 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10714                                                  bool ForTakingAddress) {
10715   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10716                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10717 }
10718 
10719 void TemplateSpecCandidateSet::destroyCandidates() {
10720   for (iterator i = begin(), e = end(); i != e; ++i) {
10721     i->DeductionFailure.Destroy();
10722   }
10723 }
10724 
10725 void TemplateSpecCandidateSet::clear() {
10726   destroyCandidates();
10727   Candidates.clear();
10728 }
10729 
10730 /// NoteCandidates - When no template specialization match is found, prints
10731 /// diagnostic messages containing the non-matching specializations that form
10732 /// the candidate set.
10733 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10734 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10735 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10736   // Sort the candidates by position (assuming no candidate is a match).
10737   // Sorting directly would be prohibitive, so we make a set of pointers
10738   // and sort those.
10739   SmallVector<TemplateSpecCandidate *, 32> Cands;
10740   Cands.reserve(size());
10741   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10742     if (Cand->Specialization)
10743       Cands.push_back(Cand);
10744     // Otherwise, this is a non-matching builtin candidate.  We do not,
10745     // in general, want to list every possible builtin candidate.
10746   }
10747 
10748   llvm::sort(Cands.begin(), Cands.end(),
10749              CompareTemplateSpecCandidatesForDisplay(S));
10750 
10751   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10752   // for generalization purposes (?).
10753   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10754 
10755   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10756   unsigned CandsShown = 0;
10757   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10758     TemplateSpecCandidate *Cand = *I;
10759 
10760     // Set an arbitrary limit on the number of candidates we'll spam
10761     // the user with.  FIXME: This limit should depend on details of the
10762     // candidate list.
10763     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10764       break;
10765     ++CandsShown;
10766 
10767     assert(Cand->Specialization &&
10768            "Non-matching built-in candidates are not added to Cands.");
10769     Cand->NoteDeductionFailure(S, ForTakingAddress);
10770   }
10771 
10772   if (I != E)
10773     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10774 }
10775 
10776 // [PossiblyAFunctionType]  -->   [Return]
10777 // NonFunctionType --> NonFunctionType
10778 // R (A) --> R(A)
10779 // R (*)(A) --> R (A)
10780 // R (&)(A) --> R (A)
10781 // R (S::*)(A) --> R (A)
10782 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10783   QualType Ret = PossiblyAFunctionType;
10784   if (const PointerType *ToTypePtr =
10785     PossiblyAFunctionType->getAs<PointerType>())
10786     Ret = ToTypePtr->getPointeeType();
10787   else if (const ReferenceType *ToTypeRef =
10788     PossiblyAFunctionType->getAs<ReferenceType>())
10789     Ret = ToTypeRef->getPointeeType();
10790   else if (const MemberPointerType *MemTypePtr =
10791     PossiblyAFunctionType->getAs<MemberPointerType>())
10792     Ret = MemTypePtr->getPointeeType();
10793   Ret =
10794     Context.getCanonicalType(Ret).getUnqualifiedType();
10795   return Ret;
10796 }
10797 
10798 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10799                                  bool Complain = true) {
10800   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10801       S.DeduceReturnType(FD, Loc, Complain))
10802     return true;
10803 
10804   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10805   if (S.getLangOpts().CPlusPlus17 &&
10806       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10807       !S.ResolveExceptionSpec(Loc, FPT))
10808     return true;
10809 
10810   return false;
10811 }
10812 
10813 namespace {
10814 // A helper class to help with address of function resolution
10815 // - allows us to avoid passing around all those ugly parameters
10816 class AddressOfFunctionResolver {
10817   Sema& S;
10818   Expr* SourceExpr;
10819   const QualType& TargetType;
10820   QualType TargetFunctionType; // Extracted function type from target type
10821 
10822   bool Complain;
10823   //DeclAccessPair& ResultFunctionAccessPair;
10824   ASTContext& Context;
10825 
10826   bool TargetTypeIsNonStaticMemberFunction;
10827   bool FoundNonTemplateFunction;
10828   bool StaticMemberFunctionFromBoundPointer;
10829   bool HasComplained;
10830 
10831   OverloadExpr::FindResult OvlExprInfo;
10832   OverloadExpr *OvlExpr;
10833   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10834   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10835   TemplateSpecCandidateSet FailedCandidates;
10836 
10837 public:
10838   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10839                             const QualType &TargetType, bool Complain)
10840       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10841         Complain(Complain), Context(S.getASTContext()),
10842         TargetTypeIsNonStaticMemberFunction(
10843             !!TargetType->getAs<MemberPointerType>()),
10844         FoundNonTemplateFunction(false),
10845         StaticMemberFunctionFromBoundPointer(false),
10846         HasComplained(false),
10847         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10848         OvlExpr(OvlExprInfo.Expression),
10849         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10850     ExtractUnqualifiedFunctionTypeFromTargetType();
10851 
10852     if (TargetFunctionType->isFunctionType()) {
10853       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10854         if (!UME->isImplicitAccess() &&
10855             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10856           StaticMemberFunctionFromBoundPointer = true;
10857     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10858       DeclAccessPair dap;
10859       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10860               OvlExpr, false, &dap)) {
10861         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10862           if (!Method->isStatic()) {
10863             // If the target type is a non-function type and the function found
10864             // is a non-static member function, pretend as if that was the
10865             // target, it's the only possible type to end up with.
10866             TargetTypeIsNonStaticMemberFunction = true;
10867 
10868             // And skip adding the function if its not in the proper form.
10869             // We'll diagnose this due to an empty set of functions.
10870             if (!OvlExprInfo.HasFormOfMemberPointer)
10871               return;
10872           }
10873 
10874         Matches.push_back(std::make_pair(dap, Fn));
10875       }
10876       return;
10877     }
10878 
10879     if (OvlExpr->hasExplicitTemplateArgs())
10880       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10881 
10882     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10883       // C++ [over.over]p4:
10884       //   If more than one function is selected, [...]
10885       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10886         if (FoundNonTemplateFunction)
10887           EliminateAllTemplateMatches();
10888         else
10889           EliminateAllExceptMostSpecializedTemplate();
10890       }
10891     }
10892 
10893     if (S.getLangOpts().CUDA && Matches.size() > 1)
10894       EliminateSuboptimalCudaMatches();
10895   }
10896 
10897   bool hasComplained() const { return HasComplained; }
10898 
10899 private:
10900   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10901     QualType Discard;
10902     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10903            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10904   }
10905 
10906   /// \return true if A is considered a better overload candidate for the
10907   /// desired type than B.
10908   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10909     // If A doesn't have exactly the correct type, we don't want to classify it
10910     // as "better" than anything else. This way, the user is required to
10911     // disambiguate for us if there are multiple candidates and no exact match.
10912     return candidateHasExactlyCorrectType(A) &&
10913            (!candidateHasExactlyCorrectType(B) ||
10914             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10915   }
10916 
10917   /// \return true if we were able to eliminate all but one overload candidate,
10918   /// false otherwise.
10919   bool eliminiateSuboptimalOverloadCandidates() {
10920     // Same algorithm as overload resolution -- one pass to pick the "best",
10921     // another pass to be sure that nothing is better than the best.
10922     auto Best = Matches.begin();
10923     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10924       if (isBetterCandidate(I->second, Best->second))
10925         Best = I;
10926 
10927     const FunctionDecl *BestFn = Best->second;
10928     auto IsBestOrInferiorToBest = [this, BestFn](
10929         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10930       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10931     };
10932 
10933     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10934     // option, so we can potentially give the user a better error
10935     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10936       return false;
10937     Matches[0] = *Best;
10938     Matches.resize(1);
10939     return true;
10940   }
10941 
10942   bool isTargetTypeAFunction() const {
10943     return TargetFunctionType->isFunctionType();
10944   }
10945 
10946   // [ToType]     [Return]
10947 
10948   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10949   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10950   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10951   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10952     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10953   }
10954 
10955   // return true if any matching specializations were found
10956   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10957                                    const DeclAccessPair& CurAccessFunPair) {
10958     if (CXXMethodDecl *Method
10959               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10960       // Skip non-static function templates when converting to pointer, and
10961       // static when converting to member pointer.
10962       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10963         return false;
10964     }
10965     else if (TargetTypeIsNonStaticMemberFunction)
10966       return false;
10967 
10968     // C++ [over.over]p2:
10969     //   If the name is a function template, template argument deduction is
10970     //   done (14.8.2.2), and if the argument deduction succeeds, the
10971     //   resulting template argument list is used to generate a single
10972     //   function template specialization, which is added to the set of
10973     //   overloaded functions considered.
10974     FunctionDecl *Specialization = nullptr;
10975     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10976     if (Sema::TemplateDeductionResult Result
10977           = S.DeduceTemplateArguments(FunctionTemplate,
10978                                       &OvlExplicitTemplateArgs,
10979                                       TargetFunctionType, Specialization,
10980                                       Info, /*IsAddressOfFunction*/true)) {
10981       // Make a note of the failed deduction for diagnostics.
10982       FailedCandidates.addCandidate()
10983           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10984                MakeDeductionFailureInfo(Context, Result, Info));
10985       return false;
10986     }
10987 
10988     // Template argument deduction ensures that we have an exact match or
10989     // compatible pointer-to-function arguments that would be adjusted by ICS.
10990     // This function template specicalization works.
10991     assert(S.isSameOrCompatibleFunctionType(
10992               Context.getCanonicalType(Specialization->getType()),
10993               Context.getCanonicalType(TargetFunctionType)));
10994 
10995     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10996       return false;
10997 
10998     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10999     return true;
11000   }
11001 
11002   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11003                                       const DeclAccessPair& CurAccessFunPair) {
11004     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11005       // Skip non-static functions when converting to pointer, and static
11006       // when converting to member pointer.
11007       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11008         return false;
11009     }
11010     else if (TargetTypeIsNonStaticMemberFunction)
11011       return false;
11012 
11013     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11014       if (S.getLangOpts().CUDA)
11015         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11016           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11017             return false;
11018       if (FunDecl->isMultiVersion()) {
11019         const auto *TA = FunDecl->getAttr<TargetAttr>();
11020         assert(TA && "Multiversioned functions require a target attribute");
11021         if (!TA->isDefaultVersion())
11022           return false;
11023       }
11024 
11025       // If any candidate has a placeholder return type, trigger its deduction
11026       // now.
11027       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
11028                                Complain)) {
11029         HasComplained |= Complain;
11030         return false;
11031       }
11032 
11033       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11034         return false;
11035 
11036       // If we're in C, we need to support types that aren't exactly identical.
11037       if (!S.getLangOpts().CPlusPlus ||
11038           candidateHasExactlyCorrectType(FunDecl)) {
11039         Matches.push_back(std::make_pair(
11040             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11041         FoundNonTemplateFunction = true;
11042         return true;
11043       }
11044     }
11045 
11046     return false;
11047   }
11048 
11049   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11050     bool Ret = false;
11051 
11052     // If the overload expression doesn't have the form of a pointer to
11053     // member, don't try to convert it to a pointer-to-member type.
11054     if (IsInvalidFormOfPointerToMemberFunction())
11055       return false;
11056 
11057     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11058                                E = OvlExpr->decls_end();
11059          I != E; ++I) {
11060       // Look through any using declarations to find the underlying function.
11061       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11062 
11063       // C++ [over.over]p3:
11064       //   Non-member functions and static member functions match
11065       //   targets of type "pointer-to-function" or "reference-to-function."
11066       //   Nonstatic member functions match targets of
11067       //   type "pointer-to-member-function."
11068       // Note that according to DR 247, the containing class does not matter.
11069       if (FunctionTemplateDecl *FunctionTemplate
11070                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11071         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11072           Ret = true;
11073       }
11074       // If we have explicit template arguments supplied, skip non-templates.
11075       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11076                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11077         Ret = true;
11078     }
11079     assert(Ret || Matches.empty());
11080     return Ret;
11081   }
11082 
11083   void EliminateAllExceptMostSpecializedTemplate() {
11084     //   [...] and any given function template specialization F1 is
11085     //   eliminated if the set contains a second function template
11086     //   specialization whose function template is more specialized
11087     //   than the function template of F1 according to the partial
11088     //   ordering rules of 14.5.5.2.
11089 
11090     // The algorithm specified above is quadratic. We instead use a
11091     // two-pass algorithm (similar to the one used to identify the
11092     // best viable function in an overload set) that identifies the
11093     // best function template (if it exists).
11094 
11095     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11096     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11097       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11098 
11099     // TODO: It looks like FailedCandidates does not serve much purpose
11100     // here, since the no_viable diagnostic has index 0.
11101     UnresolvedSetIterator Result = S.getMostSpecialized(
11102         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11103         SourceExpr->getLocStart(), S.PDiag(),
11104         S.PDiag(diag::err_addr_ovl_ambiguous)
11105           << Matches[0].second->getDeclName(),
11106         S.PDiag(diag::note_ovl_candidate)
11107           << (unsigned)oc_function_template,
11108         Complain, TargetFunctionType);
11109 
11110     if (Result != MatchesCopy.end()) {
11111       // Make it the first and only element
11112       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11113       Matches[0].second = cast<FunctionDecl>(*Result);
11114       Matches.resize(1);
11115     } else
11116       HasComplained |= Complain;
11117   }
11118 
11119   void EliminateAllTemplateMatches() {
11120     //   [...] any function template specializations in the set are
11121     //   eliminated if the set also contains a non-template function, [...]
11122     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11123       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11124         ++I;
11125       else {
11126         Matches[I] = Matches[--N];
11127         Matches.resize(N);
11128       }
11129     }
11130   }
11131 
11132   void EliminateSuboptimalCudaMatches() {
11133     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11134   }
11135 
11136 public:
11137   void ComplainNoMatchesFound() const {
11138     assert(Matches.empty());
11139     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11140         << OvlExpr->getName() << TargetFunctionType
11141         << OvlExpr->getSourceRange();
11142     if (FailedCandidates.empty())
11143       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11144                                   /*TakingAddress=*/true);
11145     else {
11146       // We have some deduction failure messages. Use them to diagnose
11147       // the function templates, and diagnose the non-template candidates
11148       // normally.
11149       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11150                                  IEnd = OvlExpr->decls_end();
11151            I != IEnd; ++I)
11152         if (FunctionDecl *Fun =
11153                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11154           if (!functionHasPassObjectSizeParams(Fun))
11155             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11156                                     /*TakingAddress=*/true);
11157       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11158     }
11159   }
11160 
11161   bool IsInvalidFormOfPointerToMemberFunction() const {
11162     return TargetTypeIsNonStaticMemberFunction &&
11163       !OvlExprInfo.HasFormOfMemberPointer;
11164   }
11165 
11166   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11167       // TODO: Should we condition this on whether any functions might
11168       // have matched, or is it more appropriate to do that in callers?
11169       // TODO: a fixit wouldn't hurt.
11170       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11171         << TargetType << OvlExpr->getSourceRange();
11172   }
11173 
11174   bool IsStaticMemberFunctionFromBoundPointer() const {
11175     return StaticMemberFunctionFromBoundPointer;
11176   }
11177 
11178   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11179     S.Diag(OvlExpr->getLocStart(),
11180            diag::err_invalid_form_pointer_member_function)
11181       << OvlExpr->getSourceRange();
11182   }
11183 
11184   void ComplainOfInvalidConversion() const {
11185     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11186       << OvlExpr->getName() << TargetType;
11187   }
11188 
11189   void ComplainMultipleMatchesFound() const {
11190     assert(Matches.size() > 1);
11191     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11192       << OvlExpr->getName()
11193       << OvlExpr->getSourceRange();
11194     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11195                                 /*TakingAddress=*/true);
11196   }
11197 
11198   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11199 
11200   int getNumMatches() const { return Matches.size(); }
11201 
11202   FunctionDecl* getMatchingFunctionDecl() const {
11203     if (Matches.size() != 1) return nullptr;
11204     return Matches[0].second;
11205   }
11206 
11207   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11208     if (Matches.size() != 1) return nullptr;
11209     return &Matches[0].first;
11210   }
11211 };
11212 }
11213 
11214 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11215 /// an overloaded function (C++ [over.over]), where @p From is an
11216 /// expression with overloaded function type and @p ToType is the type
11217 /// we're trying to resolve to. For example:
11218 ///
11219 /// @code
11220 /// int f(double);
11221 /// int f(int);
11222 ///
11223 /// int (*pfd)(double) = f; // selects f(double)
11224 /// @endcode
11225 ///
11226 /// This routine returns the resulting FunctionDecl if it could be
11227 /// resolved, and NULL otherwise. When @p Complain is true, this
11228 /// routine will emit diagnostics if there is an error.
11229 FunctionDecl *
11230 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11231                                          QualType TargetType,
11232                                          bool Complain,
11233                                          DeclAccessPair &FoundResult,
11234                                          bool *pHadMultipleCandidates) {
11235   assert(AddressOfExpr->getType() == Context.OverloadTy);
11236 
11237   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11238                                      Complain);
11239   int NumMatches = Resolver.getNumMatches();
11240   FunctionDecl *Fn = nullptr;
11241   bool ShouldComplain = Complain && !Resolver.hasComplained();
11242   if (NumMatches == 0 && ShouldComplain) {
11243     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11244       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11245     else
11246       Resolver.ComplainNoMatchesFound();
11247   }
11248   else if (NumMatches > 1 && ShouldComplain)
11249     Resolver.ComplainMultipleMatchesFound();
11250   else if (NumMatches == 1) {
11251     Fn = Resolver.getMatchingFunctionDecl();
11252     assert(Fn);
11253     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11254       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11255     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11256     if (Complain) {
11257       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11258         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11259       else
11260         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11261     }
11262   }
11263 
11264   if (pHadMultipleCandidates)
11265     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11266   return Fn;
11267 }
11268 
11269 /// Given an expression that refers to an overloaded function, try to
11270 /// resolve that function to a single function that can have its address taken.
11271 /// This will modify `Pair` iff it returns non-null.
11272 ///
11273 /// This routine can only realistically succeed if all but one candidates in the
11274 /// overload set for SrcExpr cannot have their addresses taken.
11275 FunctionDecl *
11276 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11277                                                   DeclAccessPair &Pair) {
11278   OverloadExpr::FindResult R = OverloadExpr::find(E);
11279   OverloadExpr *Ovl = R.Expression;
11280   FunctionDecl *Result = nullptr;
11281   DeclAccessPair DAP;
11282   // Don't use the AddressOfResolver because we're specifically looking for
11283   // cases where we have one overload candidate that lacks
11284   // enable_if/pass_object_size/...
11285   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11286     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11287     if (!FD)
11288       return nullptr;
11289 
11290     if (!checkAddressOfFunctionIsAvailable(FD))
11291       continue;
11292 
11293     // We have more than one result; quit.
11294     if (Result)
11295       return nullptr;
11296     DAP = I.getPair();
11297     Result = FD;
11298   }
11299 
11300   if (Result)
11301     Pair = DAP;
11302   return Result;
11303 }
11304 
11305 /// Given an overloaded function, tries to turn it into a non-overloaded
11306 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11307 /// will perform access checks, diagnose the use of the resultant decl, and, if
11308 /// requested, potentially perform a function-to-pointer decay.
11309 ///
11310 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11311 /// Otherwise, returns true. This may emit diagnostics and return true.
11312 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11313     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11314   Expr *E = SrcExpr.get();
11315   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11316 
11317   DeclAccessPair DAP;
11318   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11319   if (!Found)
11320     return false;
11321 
11322   // Emitting multiple diagnostics for a function that is both inaccessible and
11323   // unavailable is consistent with our behavior elsewhere. So, always check
11324   // for both.
11325   DiagnoseUseOfDecl(Found, E->getExprLoc());
11326   CheckAddressOfMemberAccess(E, DAP);
11327   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11328   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11329     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11330   else
11331     SrcExpr = Fixed;
11332   return true;
11333 }
11334 
11335 /// Given an expression that refers to an overloaded function, try to
11336 /// resolve that overloaded function expression down to a single function.
11337 ///
11338 /// This routine can only resolve template-ids that refer to a single function
11339 /// template, where that template-id refers to a single template whose template
11340 /// arguments are either provided by the template-id or have defaults,
11341 /// as described in C++0x [temp.arg.explicit]p3.
11342 ///
11343 /// If no template-ids are found, no diagnostics are emitted and NULL is
11344 /// returned.
11345 FunctionDecl *
11346 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11347                                                   bool Complain,
11348                                                   DeclAccessPair *FoundResult) {
11349   // C++ [over.over]p1:
11350   //   [...] [Note: any redundant set of parentheses surrounding the
11351   //   overloaded function name is ignored (5.1). ]
11352   // C++ [over.over]p1:
11353   //   [...] The overloaded function name can be preceded by the &
11354   //   operator.
11355 
11356   // If we didn't actually find any template-ids, we're done.
11357   if (!ovl->hasExplicitTemplateArgs())
11358     return nullptr;
11359 
11360   TemplateArgumentListInfo ExplicitTemplateArgs;
11361   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11362   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11363 
11364   // Look through all of the overloaded functions, searching for one
11365   // whose type matches exactly.
11366   FunctionDecl *Matched = nullptr;
11367   for (UnresolvedSetIterator I = ovl->decls_begin(),
11368          E = ovl->decls_end(); I != E; ++I) {
11369     // C++0x [temp.arg.explicit]p3:
11370     //   [...] In contexts where deduction is done and fails, or in contexts
11371     //   where deduction is not done, if a template argument list is
11372     //   specified and it, along with any default template arguments,
11373     //   identifies a single function template specialization, then the
11374     //   template-id is an lvalue for the function template specialization.
11375     FunctionTemplateDecl *FunctionTemplate
11376       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11377 
11378     // C++ [over.over]p2:
11379     //   If the name is a function template, template argument deduction is
11380     //   done (14.8.2.2), and if the argument deduction succeeds, the
11381     //   resulting template argument list is used to generate a single
11382     //   function template specialization, which is added to the set of
11383     //   overloaded functions considered.
11384     FunctionDecl *Specialization = nullptr;
11385     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11386     if (TemplateDeductionResult Result
11387           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11388                                     Specialization, Info,
11389                                     /*IsAddressOfFunction*/true)) {
11390       // Make a note of the failed deduction for diagnostics.
11391       // TODO: Actually use the failed-deduction info?
11392       FailedCandidates.addCandidate()
11393           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11394                MakeDeductionFailureInfo(Context, Result, Info));
11395       continue;
11396     }
11397 
11398     assert(Specialization && "no specialization and no error?");
11399 
11400     // Multiple matches; we can't resolve to a single declaration.
11401     if (Matched) {
11402       if (Complain) {
11403         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11404           << ovl->getName();
11405         NoteAllOverloadCandidates(ovl);
11406       }
11407       return nullptr;
11408     }
11409 
11410     Matched = Specialization;
11411     if (FoundResult) *FoundResult = I.getPair();
11412   }
11413 
11414   if (Matched &&
11415       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11416     return nullptr;
11417 
11418   return Matched;
11419 }
11420 
11421 // Resolve and fix an overloaded expression that can be resolved
11422 // because it identifies a single function template specialization.
11423 //
11424 // Last three arguments should only be supplied if Complain = true
11425 //
11426 // Return true if it was logically possible to so resolve the
11427 // expression, regardless of whether or not it succeeded.  Always
11428 // returns true if 'complain' is set.
11429 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11430                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11431                       bool complain, SourceRange OpRangeForComplaining,
11432                                            QualType DestTypeForComplaining,
11433                                             unsigned DiagIDForComplaining) {
11434   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11435 
11436   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11437 
11438   DeclAccessPair found;
11439   ExprResult SingleFunctionExpression;
11440   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11441                            ovl.Expression, /*complain*/ false, &found)) {
11442     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11443       SrcExpr = ExprError();
11444       return true;
11445     }
11446 
11447     // It is only correct to resolve to an instance method if we're
11448     // resolving a form that's permitted to be a pointer to member.
11449     // Otherwise we'll end up making a bound member expression, which
11450     // is illegal in all the contexts we resolve like this.
11451     if (!ovl.HasFormOfMemberPointer &&
11452         isa<CXXMethodDecl>(fn) &&
11453         cast<CXXMethodDecl>(fn)->isInstance()) {
11454       if (!complain) return false;
11455 
11456       Diag(ovl.Expression->getExprLoc(),
11457            diag::err_bound_member_function)
11458         << 0 << ovl.Expression->getSourceRange();
11459 
11460       // TODO: I believe we only end up here if there's a mix of
11461       // static and non-static candidates (otherwise the expression
11462       // would have 'bound member' type, not 'overload' type).
11463       // Ideally we would note which candidate was chosen and why
11464       // the static candidates were rejected.
11465       SrcExpr = ExprError();
11466       return true;
11467     }
11468 
11469     // Fix the expression to refer to 'fn'.
11470     SingleFunctionExpression =
11471         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11472 
11473     // If desired, do function-to-pointer decay.
11474     if (doFunctionPointerConverion) {
11475       SingleFunctionExpression =
11476         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11477       if (SingleFunctionExpression.isInvalid()) {
11478         SrcExpr = ExprError();
11479         return true;
11480       }
11481     }
11482   }
11483 
11484   if (!SingleFunctionExpression.isUsable()) {
11485     if (complain) {
11486       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11487         << ovl.Expression->getName()
11488         << DestTypeForComplaining
11489         << OpRangeForComplaining
11490         << ovl.Expression->getQualifierLoc().getSourceRange();
11491       NoteAllOverloadCandidates(SrcExpr.get());
11492 
11493       SrcExpr = ExprError();
11494       return true;
11495     }
11496 
11497     return false;
11498   }
11499 
11500   SrcExpr = SingleFunctionExpression;
11501   return true;
11502 }
11503 
11504 /// Add a single candidate to the overload set.
11505 static void AddOverloadedCallCandidate(Sema &S,
11506                                        DeclAccessPair FoundDecl,
11507                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11508                                        ArrayRef<Expr *> Args,
11509                                        OverloadCandidateSet &CandidateSet,
11510                                        bool PartialOverloading,
11511                                        bool KnownValid) {
11512   NamedDecl *Callee = FoundDecl.getDecl();
11513   if (isa<UsingShadowDecl>(Callee))
11514     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11515 
11516   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11517     if (ExplicitTemplateArgs) {
11518       assert(!KnownValid && "Explicit template arguments?");
11519       return;
11520     }
11521     // Prevent ill-formed function decls to be added as overload candidates.
11522     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11523       return;
11524 
11525     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11526                            /*SuppressUsedConversions=*/false,
11527                            PartialOverloading);
11528     return;
11529   }
11530 
11531   if (FunctionTemplateDecl *FuncTemplate
11532       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11533     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11534                                    ExplicitTemplateArgs, Args, CandidateSet,
11535                                    /*SuppressUsedConversions=*/false,
11536                                    PartialOverloading);
11537     return;
11538   }
11539 
11540   assert(!KnownValid && "unhandled case in overloaded call candidate");
11541 }
11542 
11543 /// Add the overload candidates named by callee and/or found by argument
11544 /// dependent lookup to the given overload set.
11545 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11546                                        ArrayRef<Expr *> Args,
11547                                        OverloadCandidateSet &CandidateSet,
11548                                        bool PartialOverloading) {
11549 
11550 #ifndef NDEBUG
11551   // Verify that ArgumentDependentLookup is consistent with the rules
11552   // in C++0x [basic.lookup.argdep]p3:
11553   //
11554   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11555   //   and let Y be the lookup set produced by argument dependent
11556   //   lookup (defined as follows). If X contains
11557   //
11558   //     -- a declaration of a class member, or
11559   //
11560   //     -- a block-scope function declaration that is not a
11561   //        using-declaration, or
11562   //
11563   //     -- a declaration that is neither a function or a function
11564   //        template
11565   //
11566   //   then Y is empty.
11567 
11568   if (ULE->requiresADL()) {
11569     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11570            E = ULE->decls_end(); I != E; ++I) {
11571       assert(!(*I)->getDeclContext()->isRecord());
11572       assert(isa<UsingShadowDecl>(*I) ||
11573              !(*I)->getDeclContext()->isFunctionOrMethod());
11574       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11575     }
11576   }
11577 #endif
11578 
11579   // It would be nice to avoid this copy.
11580   TemplateArgumentListInfo TABuffer;
11581   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11582   if (ULE->hasExplicitTemplateArgs()) {
11583     ULE->copyTemplateArgumentsInto(TABuffer);
11584     ExplicitTemplateArgs = &TABuffer;
11585   }
11586 
11587   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11588          E = ULE->decls_end(); I != E; ++I)
11589     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11590                                CandidateSet, PartialOverloading,
11591                                /*KnownValid*/ true);
11592 
11593   if (ULE->requiresADL())
11594     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11595                                          Args, ExplicitTemplateArgs,
11596                                          CandidateSet, PartialOverloading);
11597 }
11598 
11599 /// Determine whether a declaration with the specified name could be moved into
11600 /// a different namespace.
11601 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11602   switch (Name.getCXXOverloadedOperator()) {
11603   case OO_New: case OO_Array_New:
11604   case OO_Delete: case OO_Array_Delete:
11605     return false;
11606 
11607   default:
11608     return true;
11609   }
11610 }
11611 
11612 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11613 /// template, where the non-dependent name was declared after the template
11614 /// was defined. This is common in code written for a compilers which do not
11615 /// correctly implement two-stage name lookup.
11616 ///
11617 /// Returns true if a viable candidate was found and a diagnostic was issued.
11618 static bool
11619 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11620                        const CXXScopeSpec &SS, LookupResult &R,
11621                        OverloadCandidateSet::CandidateSetKind CSK,
11622                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11623                        ArrayRef<Expr *> Args,
11624                        bool *DoDiagnoseEmptyLookup = nullptr) {
11625   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11626     return false;
11627 
11628   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11629     if (DC->isTransparentContext())
11630       continue;
11631 
11632     SemaRef.LookupQualifiedName(R, DC);
11633 
11634     if (!R.empty()) {
11635       R.suppressDiagnostics();
11636 
11637       if (isa<CXXRecordDecl>(DC)) {
11638         // Don't diagnose names we find in classes; we get much better
11639         // diagnostics for these from DiagnoseEmptyLookup.
11640         R.clear();
11641         if (DoDiagnoseEmptyLookup)
11642           *DoDiagnoseEmptyLookup = true;
11643         return false;
11644       }
11645 
11646       OverloadCandidateSet Candidates(FnLoc, CSK);
11647       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11648         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11649                                    ExplicitTemplateArgs, Args,
11650                                    Candidates, false, /*KnownValid*/ false);
11651 
11652       OverloadCandidateSet::iterator Best;
11653       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11654         // No viable functions. Don't bother the user with notes for functions
11655         // which don't work and shouldn't be found anyway.
11656         R.clear();
11657         return false;
11658       }
11659 
11660       // Find the namespaces where ADL would have looked, and suggest
11661       // declaring the function there instead.
11662       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11663       Sema::AssociatedClassSet AssociatedClasses;
11664       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11665                                                  AssociatedNamespaces,
11666                                                  AssociatedClasses);
11667       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11668       if (canBeDeclaredInNamespace(R.getLookupName())) {
11669         DeclContext *Std = SemaRef.getStdNamespace();
11670         for (Sema::AssociatedNamespaceSet::iterator
11671                it = AssociatedNamespaces.begin(),
11672                end = AssociatedNamespaces.end(); it != end; ++it) {
11673           // Never suggest declaring a function within namespace 'std'.
11674           if (Std && Std->Encloses(*it))
11675             continue;
11676 
11677           // Never suggest declaring a function within a namespace with a
11678           // reserved name, like __gnu_cxx.
11679           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11680           if (NS &&
11681               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11682             continue;
11683 
11684           SuggestedNamespaces.insert(*it);
11685         }
11686       }
11687 
11688       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11689         << R.getLookupName();
11690       if (SuggestedNamespaces.empty()) {
11691         SemaRef.Diag(Best->Function->getLocation(),
11692                      diag::note_not_found_by_two_phase_lookup)
11693           << R.getLookupName() << 0;
11694       } else if (SuggestedNamespaces.size() == 1) {
11695         SemaRef.Diag(Best->Function->getLocation(),
11696                      diag::note_not_found_by_two_phase_lookup)
11697           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11698       } else {
11699         // FIXME: It would be useful to list the associated namespaces here,
11700         // but the diagnostics infrastructure doesn't provide a way to produce
11701         // a localized representation of a list of items.
11702         SemaRef.Diag(Best->Function->getLocation(),
11703                      diag::note_not_found_by_two_phase_lookup)
11704           << R.getLookupName() << 2;
11705       }
11706 
11707       // Try to recover by calling this function.
11708       return true;
11709     }
11710 
11711     R.clear();
11712   }
11713 
11714   return false;
11715 }
11716 
11717 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11718 /// template, where the non-dependent operator was declared after the template
11719 /// was defined.
11720 ///
11721 /// Returns true if a viable candidate was found and a diagnostic was issued.
11722 static bool
11723 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11724                                SourceLocation OpLoc,
11725                                ArrayRef<Expr *> Args) {
11726   DeclarationName OpName =
11727     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11728   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11729   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11730                                 OverloadCandidateSet::CSK_Operator,
11731                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11732 }
11733 
11734 namespace {
11735 class BuildRecoveryCallExprRAII {
11736   Sema &SemaRef;
11737 public:
11738   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11739     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11740     SemaRef.IsBuildingRecoveryCallExpr = true;
11741   }
11742 
11743   ~BuildRecoveryCallExprRAII() {
11744     SemaRef.IsBuildingRecoveryCallExpr = false;
11745   }
11746 };
11747 
11748 }
11749 
11750 static std::unique_ptr<CorrectionCandidateCallback>
11751 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11752               bool HasTemplateArgs, bool AllowTypoCorrection) {
11753   if (!AllowTypoCorrection)
11754     return llvm::make_unique<NoTypoCorrectionCCC>();
11755   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11756                                                   HasTemplateArgs, ME);
11757 }
11758 
11759 /// Attempts to recover from a call where no functions were found.
11760 ///
11761 /// Returns true if new candidates were found.
11762 static ExprResult
11763 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11764                       UnresolvedLookupExpr *ULE,
11765                       SourceLocation LParenLoc,
11766                       MutableArrayRef<Expr *> Args,
11767                       SourceLocation RParenLoc,
11768                       bool EmptyLookup, bool AllowTypoCorrection) {
11769   // Do not try to recover if it is already building a recovery call.
11770   // This stops infinite loops for template instantiations like
11771   //
11772   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11773   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11774   //
11775   if (SemaRef.IsBuildingRecoveryCallExpr)
11776     return ExprError();
11777   BuildRecoveryCallExprRAII RCE(SemaRef);
11778 
11779   CXXScopeSpec SS;
11780   SS.Adopt(ULE->getQualifierLoc());
11781   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11782 
11783   TemplateArgumentListInfo TABuffer;
11784   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11785   if (ULE->hasExplicitTemplateArgs()) {
11786     ULE->copyTemplateArgumentsInto(TABuffer);
11787     ExplicitTemplateArgs = &TABuffer;
11788   }
11789 
11790   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11791                  Sema::LookupOrdinaryName);
11792   bool DoDiagnoseEmptyLookup = EmptyLookup;
11793   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11794                               OverloadCandidateSet::CSK_Normal,
11795                               ExplicitTemplateArgs, Args,
11796                               &DoDiagnoseEmptyLookup) &&
11797     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11798         S, SS, R,
11799         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11800                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11801         ExplicitTemplateArgs, Args)))
11802     return ExprError();
11803 
11804   assert(!R.empty() && "lookup results empty despite recovery");
11805 
11806   // If recovery created an ambiguity, just bail out.
11807   if (R.isAmbiguous()) {
11808     R.suppressDiagnostics();
11809     return ExprError();
11810   }
11811 
11812   // Build an implicit member call if appropriate.  Just drop the
11813   // casts and such from the call, we don't really care.
11814   ExprResult NewFn = ExprError();
11815   if ((*R.begin())->isCXXClassMember())
11816     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11817                                                     ExplicitTemplateArgs, S);
11818   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11819     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11820                                         ExplicitTemplateArgs);
11821   else
11822     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11823 
11824   if (NewFn.isInvalid())
11825     return ExprError();
11826 
11827   // This shouldn't cause an infinite loop because we're giving it
11828   // an expression with viable lookup results, which should never
11829   // end up here.
11830   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11831                                MultiExprArg(Args.data(), Args.size()),
11832                                RParenLoc);
11833 }
11834 
11835 /// Constructs and populates an OverloadedCandidateSet from
11836 /// the given function.
11837 /// \returns true when an the ExprResult output parameter has been set.
11838 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11839                                   UnresolvedLookupExpr *ULE,
11840                                   MultiExprArg Args,
11841                                   SourceLocation RParenLoc,
11842                                   OverloadCandidateSet *CandidateSet,
11843                                   ExprResult *Result) {
11844 #ifndef NDEBUG
11845   if (ULE->requiresADL()) {
11846     // To do ADL, we must have found an unqualified name.
11847     assert(!ULE->getQualifier() && "qualified name with ADL");
11848 
11849     // We don't perform ADL for implicit declarations of builtins.
11850     // Verify that this was correctly set up.
11851     FunctionDecl *F;
11852     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11853         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11854         F->getBuiltinID() && F->isImplicit())
11855       llvm_unreachable("performing ADL for builtin");
11856 
11857     // We don't perform ADL in C.
11858     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11859   }
11860 #endif
11861 
11862   UnbridgedCastsSet UnbridgedCasts;
11863   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11864     *Result = ExprError();
11865     return true;
11866   }
11867 
11868   // Add the functions denoted by the callee to the set of candidate
11869   // functions, including those from argument-dependent lookup.
11870   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11871 
11872   if (getLangOpts().MSVCCompat &&
11873       CurContext->isDependentContext() && !isSFINAEContext() &&
11874       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11875 
11876     OverloadCandidateSet::iterator Best;
11877     if (CandidateSet->empty() ||
11878         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11879             OR_No_Viable_Function) {
11880       // In Microsoft mode, if we are inside a template class member function then
11881       // create a type dependent CallExpr. The goal is to postpone name lookup
11882       // to instantiation time to be able to search into type dependent base
11883       // classes.
11884       CallExpr *CE = new (Context) CallExpr(
11885           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11886       CE->setTypeDependent(true);
11887       CE->setValueDependent(true);
11888       CE->setInstantiationDependent(true);
11889       *Result = CE;
11890       return true;
11891     }
11892   }
11893 
11894   if (CandidateSet->empty())
11895     return false;
11896 
11897   UnbridgedCasts.restore();
11898   return false;
11899 }
11900 
11901 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11902 /// the completed call expression. If overload resolution fails, emits
11903 /// diagnostics and returns ExprError()
11904 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11905                                            UnresolvedLookupExpr *ULE,
11906                                            SourceLocation LParenLoc,
11907                                            MultiExprArg Args,
11908                                            SourceLocation RParenLoc,
11909                                            Expr *ExecConfig,
11910                                            OverloadCandidateSet *CandidateSet,
11911                                            OverloadCandidateSet::iterator *Best,
11912                                            OverloadingResult OverloadResult,
11913                                            bool AllowTypoCorrection) {
11914   if (CandidateSet->empty())
11915     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11916                                  RParenLoc, /*EmptyLookup=*/true,
11917                                  AllowTypoCorrection);
11918 
11919   switch (OverloadResult) {
11920   case OR_Success: {
11921     FunctionDecl *FDecl = (*Best)->Function;
11922     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11923     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11924       return ExprError();
11925     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11926     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11927                                          ExecConfig);
11928   }
11929 
11930   case OR_No_Viable_Function: {
11931     // Try to recover by looking for viable functions which the user might
11932     // have meant to call.
11933     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11934                                                 Args, RParenLoc,
11935                                                 /*EmptyLookup=*/false,
11936                                                 AllowTypoCorrection);
11937     if (!Recovery.isInvalid())
11938       return Recovery;
11939 
11940     // If the user passes in a function that we can't take the address of, we
11941     // generally end up emitting really bad error messages. Here, we attempt to
11942     // emit better ones.
11943     for (const Expr *Arg : Args) {
11944       if (!Arg->getType()->isFunctionType())
11945         continue;
11946       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11947         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11948         if (FD &&
11949             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11950                                                        Arg->getExprLoc()))
11951           return ExprError();
11952       }
11953     }
11954 
11955     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11956         << ULE->getName() << Fn->getSourceRange();
11957     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11958     break;
11959   }
11960 
11961   case OR_Ambiguous:
11962     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11963       << ULE->getName() << Fn->getSourceRange();
11964     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11965     break;
11966 
11967   case OR_Deleted: {
11968     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11969       << (*Best)->Function->isDeleted()
11970       << ULE->getName()
11971       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11972       << Fn->getSourceRange();
11973     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11974 
11975     // We emitted an error for the unavailable/deleted function call but keep
11976     // the call in the AST.
11977     FunctionDecl *FDecl = (*Best)->Function;
11978     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11979     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11980                                          ExecConfig);
11981   }
11982   }
11983 
11984   // Overload resolution failed.
11985   return ExprError();
11986 }
11987 
11988 static void markUnaddressableCandidatesUnviable(Sema &S,
11989                                                 OverloadCandidateSet &CS) {
11990   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11991     if (I->Viable &&
11992         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11993       I->Viable = false;
11994       I->FailureKind = ovl_fail_addr_not_available;
11995     }
11996   }
11997 }
11998 
11999 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12000 /// (which eventually refers to the declaration Func) and the call
12001 /// arguments Args/NumArgs, attempt to resolve the function call down
12002 /// to a specific function. If overload resolution succeeds, returns
12003 /// the call expression produced by overload resolution.
12004 /// Otherwise, emits diagnostics and returns ExprError.
12005 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12006                                          UnresolvedLookupExpr *ULE,
12007                                          SourceLocation LParenLoc,
12008                                          MultiExprArg Args,
12009                                          SourceLocation RParenLoc,
12010                                          Expr *ExecConfig,
12011                                          bool AllowTypoCorrection,
12012                                          bool CalleesAddressIsTaken) {
12013   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12014                                     OverloadCandidateSet::CSK_Normal);
12015   ExprResult result;
12016 
12017   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12018                              &result))
12019     return result;
12020 
12021   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12022   // functions that aren't addressible are considered unviable.
12023   if (CalleesAddressIsTaken)
12024     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12025 
12026   OverloadCandidateSet::iterator Best;
12027   OverloadingResult OverloadResult =
12028       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
12029 
12030   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12031                                   RParenLoc, ExecConfig, &CandidateSet,
12032                                   &Best, OverloadResult,
12033                                   AllowTypoCorrection);
12034 }
12035 
12036 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12037   return Functions.size() > 1 ||
12038     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12039 }
12040 
12041 /// Create a unary operation that may resolve to an overloaded
12042 /// operator.
12043 ///
12044 /// \param OpLoc The location of the operator itself (e.g., '*').
12045 ///
12046 /// \param Opc The UnaryOperatorKind that describes this operator.
12047 ///
12048 /// \param Fns The set of non-member functions that will be
12049 /// considered by overload resolution. The caller needs to build this
12050 /// set based on the context using, e.g.,
12051 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12052 /// set should not contain any member functions; those will be added
12053 /// by CreateOverloadedUnaryOp().
12054 ///
12055 /// \param Input The input argument.
12056 ExprResult
12057 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12058                               const UnresolvedSetImpl &Fns,
12059                               Expr *Input, bool PerformADL) {
12060   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12061   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12062   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12063   // TODO: provide better source location info.
12064   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12065 
12066   if (checkPlaceholderForOverload(*this, Input))
12067     return ExprError();
12068 
12069   Expr *Args[2] = { Input, nullptr };
12070   unsigned NumArgs = 1;
12071 
12072   // For post-increment and post-decrement, add the implicit '0' as
12073   // the second argument, so that we know this is a post-increment or
12074   // post-decrement.
12075   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12076     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12077     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12078                                      SourceLocation());
12079     NumArgs = 2;
12080   }
12081 
12082   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12083 
12084   if (Input->isTypeDependent()) {
12085     if (Fns.empty())
12086       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12087                                          VK_RValue, OK_Ordinary, OpLoc, false);
12088 
12089     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12090     UnresolvedLookupExpr *Fn
12091       = UnresolvedLookupExpr::Create(Context, NamingClass,
12092                                      NestedNameSpecifierLoc(), OpNameInfo,
12093                                      /*ADL*/ true, IsOverloaded(Fns),
12094                                      Fns.begin(), Fns.end());
12095     return new (Context)
12096         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12097                             VK_RValue, OpLoc, FPOptions());
12098   }
12099 
12100   // Build an empty overload set.
12101   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12102 
12103   // Add the candidates from the given function set.
12104   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12105 
12106   // Add operator candidates that are member functions.
12107   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12108 
12109   // Add candidates from ADL.
12110   if (PerformADL) {
12111     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12112                                          /*ExplicitTemplateArgs*/nullptr,
12113                                          CandidateSet);
12114   }
12115 
12116   // Add builtin operator candidates.
12117   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12118 
12119   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12120 
12121   // Perform overload resolution.
12122   OverloadCandidateSet::iterator Best;
12123   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12124   case OR_Success: {
12125     // We found a built-in operator or an overloaded operator.
12126     FunctionDecl *FnDecl = Best->Function;
12127 
12128     if (FnDecl) {
12129       Expr *Base = nullptr;
12130       // We matched an overloaded operator. Build a call to that
12131       // operator.
12132 
12133       // Convert the arguments.
12134       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12135         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12136 
12137         ExprResult InputRes =
12138           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12139                                               Best->FoundDecl, Method);
12140         if (InputRes.isInvalid())
12141           return ExprError();
12142         Base = Input = InputRes.get();
12143       } else {
12144         // Convert the arguments.
12145         ExprResult InputInit
12146           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12147                                                       Context,
12148                                                       FnDecl->getParamDecl(0)),
12149                                       SourceLocation(),
12150                                       Input);
12151         if (InputInit.isInvalid())
12152           return ExprError();
12153         Input = InputInit.get();
12154       }
12155 
12156       // Build the actual expression node.
12157       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12158                                                 Base, HadMultipleCandidates,
12159                                                 OpLoc);
12160       if (FnExpr.isInvalid())
12161         return ExprError();
12162 
12163       // Determine the result type.
12164       QualType ResultTy = FnDecl->getReturnType();
12165       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12166       ResultTy = ResultTy.getNonLValueExprType(Context);
12167 
12168       Args[0] = Input;
12169       CallExpr *TheCall =
12170         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12171                                           ResultTy, VK, OpLoc, FPOptions());
12172 
12173       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12174         return ExprError();
12175 
12176       if (CheckFunctionCall(FnDecl, TheCall,
12177                             FnDecl->getType()->castAs<FunctionProtoType>()))
12178         return ExprError();
12179 
12180       return MaybeBindToTemporary(TheCall);
12181     } else {
12182       // We matched a built-in operator. Convert the arguments, then
12183       // break out so that we will build the appropriate built-in
12184       // operator node.
12185       ExprResult InputRes = PerformImplicitConversion(
12186           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12187       if (InputRes.isInvalid())
12188         return ExprError();
12189       Input = InputRes.get();
12190       break;
12191     }
12192   }
12193 
12194   case OR_No_Viable_Function:
12195     // This is an erroneous use of an operator which can be overloaded by
12196     // a non-member function. Check for non-member operators which were
12197     // defined too late to be candidates.
12198     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12199       // FIXME: Recover by calling the found function.
12200       return ExprError();
12201 
12202     // No viable function; fall through to handling this as a
12203     // built-in operator, which will produce an error message for us.
12204     break;
12205 
12206   case OR_Ambiguous:
12207     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12208         << UnaryOperator::getOpcodeStr(Opc)
12209         << Input->getType()
12210         << Input->getSourceRange();
12211     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12212                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12213     return ExprError();
12214 
12215   case OR_Deleted:
12216     Diag(OpLoc, diag::err_ovl_deleted_oper)
12217       << Best->Function->isDeleted()
12218       << UnaryOperator::getOpcodeStr(Opc)
12219       << getDeletedOrUnavailableSuffix(Best->Function)
12220       << Input->getSourceRange();
12221     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12222                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12223     return ExprError();
12224   }
12225 
12226   // Either we found no viable overloaded operator or we matched a
12227   // built-in operator. In either case, fall through to trying to
12228   // build a built-in operation.
12229   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12230 }
12231 
12232 /// Create a binary operation that may resolve to an overloaded
12233 /// operator.
12234 ///
12235 /// \param OpLoc The location of the operator itself (e.g., '+').
12236 ///
12237 /// \param Opc The BinaryOperatorKind that describes this operator.
12238 ///
12239 /// \param Fns The set of non-member functions that will be
12240 /// considered by overload resolution. The caller needs to build this
12241 /// set based on the context using, e.g.,
12242 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12243 /// set should not contain any member functions; those will be added
12244 /// by CreateOverloadedBinOp().
12245 ///
12246 /// \param LHS Left-hand argument.
12247 /// \param RHS Right-hand argument.
12248 ExprResult
12249 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12250                             BinaryOperatorKind Opc,
12251                             const UnresolvedSetImpl &Fns,
12252                             Expr *LHS, Expr *RHS, bool PerformADL) {
12253   Expr *Args[2] = { LHS, RHS };
12254   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12255 
12256   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12257   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12258 
12259   // If either side is type-dependent, create an appropriate dependent
12260   // expression.
12261   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12262     if (Fns.empty()) {
12263       // If there are no functions to store, just build a dependent
12264       // BinaryOperator or CompoundAssignment.
12265       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12266         return new (Context) BinaryOperator(
12267             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12268             OpLoc, FPFeatures);
12269 
12270       return new (Context) CompoundAssignOperator(
12271           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12272           Context.DependentTy, Context.DependentTy, OpLoc,
12273           FPFeatures);
12274     }
12275 
12276     // FIXME: save results of ADL from here?
12277     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12278     // TODO: provide better source location info in DNLoc component.
12279     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12280     UnresolvedLookupExpr *Fn
12281       = UnresolvedLookupExpr::Create(Context, NamingClass,
12282                                      NestedNameSpecifierLoc(), OpNameInfo,
12283                                      /*ADL*/PerformADL, IsOverloaded(Fns),
12284                                      Fns.begin(), Fns.end());
12285     return new (Context)
12286         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12287                             VK_RValue, OpLoc, FPFeatures);
12288   }
12289 
12290   // Always do placeholder-like conversions on the RHS.
12291   if (checkPlaceholderForOverload(*this, Args[1]))
12292     return ExprError();
12293 
12294   // Do placeholder-like conversion on the LHS; note that we should
12295   // not get here with a PseudoObject LHS.
12296   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12297   if (checkPlaceholderForOverload(*this, Args[0]))
12298     return ExprError();
12299 
12300   // If this is the assignment operator, we only perform overload resolution
12301   // if the left-hand side is a class or enumeration type. This is actually
12302   // a hack. The standard requires that we do overload resolution between the
12303   // various built-in candidates, but as DR507 points out, this can lead to
12304   // problems. So we do it this way, which pretty much follows what GCC does.
12305   // Note that we go the traditional code path for compound assignment forms.
12306   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12307     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12308 
12309   // If this is the .* operator, which is not overloadable, just
12310   // create a built-in binary operator.
12311   if (Opc == BO_PtrMemD)
12312     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12313 
12314   // Build an empty overload set.
12315   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12316 
12317   // Add the candidates from the given function set.
12318   AddFunctionCandidates(Fns, Args, CandidateSet);
12319 
12320   // Add operator candidates that are member functions.
12321   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12322 
12323   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12324   // performed for an assignment operator (nor for operator[] nor operator->,
12325   // which don't get here).
12326   if (Opc != BO_Assign && PerformADL)
12327     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12328                                          /*ExplicitTemplateArgs*/ nullptr,
12329                                          CandidateSet);
12330 
12331   // Add builtin operator candidates.
12332   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12333 
12334   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12335 
12336   // Perform overload resolution.
12337   OverloadCandidateSet::iterator Best;
12338   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12339     case OR_Success: {
12340       // We found a built-in operator or an overloaded operator.
12341       FunctionDecl *FnDecl = Best->Function;
12342 
12343       if (FnDecl) {
12344         Expr *Base = nullptr;
12345         // We matched an overloaded operator. Build a call to that
12346         // operator.
12347 
12348         // Convert the arguments.
12349         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12350           // Best->Access is only meaningful for class members.
12351           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12352 
12353           ExprResult Arg1 =
12354             PerformCopyInitialization(
12355               InitializedEntity::InitializeParameter(Context,
12356                                                      FnDecl->getParamDecl(0)),
12357               SourceLocation(), Args[1]);
12358           if (Arg1.isInvalid())
12359             return ExprError();
12360 
12361           ExprResult Arg0 =
12362             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12363                                                 Best->FoundDecl, Method);
12364           if (Arg0.isInvalid())
12365             return ExprError();
12366           Base = Args[0] = Arg0.getAs<Expr>();
12367           Args[1] = RHS = Arg1.getAs<Expr>();
12368         } else {
12369           // Convert the arguments.
12370           ExprResult Arg0 = PerformCopyInitialization(
12371             InitializedEntity::InitializeParameter(Context,
12372                                                    FnDecl->getParamDecl(0)),
12373             SourceLocation(), Args[0]);
12374           if (Arg0.isInvalid())
12375             return ExprError();
12376 
12377           ExprResult Arg1 =
12378             PerformCopyInitialization(
12379               InitializedEntity::InitializeParameter(Context,
12380                                                      FnDecl->getParamDecl(1)),
12381               SourceLocation(), Args[1]);
12382           if (Arg1.isInvalid())
12383             return ExprError();
12384           Args[0] = LHS = Arg0.getAs<Expr>();
12385           Args[1] = RHS = Arg1.getAs<Expr>();
12386         }
12387 
12388         // Build the actual expression node.
12389         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12390                                                   Best->FoundDecl, Base,
12391                                                   HadMultipleCandidates, OpLoc);
12392         if (FnExpr.isInvalid())
12393           return ExprError();
12394 
12395         // Determine the result type.
12396         QualType ResultTy = FnDecl->getReturnType();
12397         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12398         ResultTy = ResultTy.getNonLValueExprType(Context);
12399 
12400         CXXOperatorCallExpr *TheCall =
12401           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12402                                             Args, ResultTy, VK, OpLoc,
12403                                             FPFeatures);
12404 
12405         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12406                                 FnDecl))
12407           return ExprError();
12408 
12409         ArrayRef<const Expr *> ArgsArray(Args, 2);
12410         const Expr *ImplicitThis = nullptr;
12411         // Cut off the implicit 'this'.
12412         if (isa<CXXMethodDecl>(FnDecl)) {
12413           ImplicitThis = ArgsArray[0];
12414           ArgsArray = ArgsArray.slice(1);
12415         }
12416 
12417         // Check for a self move.
12418         if (Op == OO_Equal)
12419           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12420 
12421         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12422                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12423                   VariadicDoesNotApply);
12424 
12425         return MaybeBindToTemporary(TheCall);
12426       } else {
12427         // We matched a built-in operator. Convert the arguments, then
12428         // break out so that we will build the appropriate built-in
12429         // operator node.
12430         ExprResult ArgsRes0 =
12431             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12432                                       Best->Conversions[0], AA_Passing);
12433         if (ArgsRes0.isInvalid())
12434           return ExprError();
12435         Args[0] = ArgsRes0.get();
12436 
12437         ExprResult ArgsRes1 =
12438             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12439                                       Best->Conversions[1], AA_Passing);
12440         if (ArgsRes1.isInvalid())
12441           return ExprError();
12442         Args[1] = ArgsRes1.get();
12443         break;
12444       }
12445     }
12446 
12447     case OR_No_Viable_Function: {
12448       // C++ [over.match.oper]p9:
12449       //   If the operator is the operator , [...] and there are no
12450       //   viable functions, then the operator is assumed to be the
12451       //   built-in operator and interpreted according to clause 5.
12452       if (Opc == BO_Comma)
12453         break;
12454 
12455       // For class as left operand for assignment or compound assignment
12456       // operator do not fall through to handling in built-in, but report that
12457       // no overloaded assignment operator found
12458       ExprResult Result = ExprError();
12459       if (Args[0]->getType()->isRecordType() &&
12460           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12461         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12462              << BinaryOperator::getOpcodeStr(Opc)
12463              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12464         if (Args[0]->getType()->isIncompleteType()) {
12465           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12466             << Args[0]->getType()
12467             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12468         }
12469       } else {
12470         // This is an erroneous use of an operator which can be overloaded by
12471         // a non-member function. Check for non-member operators which were
12472         // defined too late to be candidates.
12473         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12474           // FIXME: Recover by calling the found function.
12475           return ExprError();
12476 
12477         // No viable function; try to create a built-in operation, which will
12478         // produce an error. Then, show the non-viable candidates.
12479         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12480       }
12481       assert(Result.isInvalid() &&
12482              "C++ binary operator overloading is missing candidates!");
12483       if (Result.isInvalid())
12484         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12485                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12486       return Result;
12487     }
12488 
12489     case OR_Ambiguous:
12490       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12491           << BinaryOperator::getOpcodeStr(Opc)
12492           << Args[0]->getType() << Args[1]->getType()
12493           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12494       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12495                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12496       return ExprError();
12497 
12498     case OR_Deleted:
12499       if (isImplicitlyDeleted(Best->Function)) {
12500         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12501         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12502           << Context.getRecordType(Method->getParent())
12503           << getSpecialMember(Method);
12504 
12505         // The user probably meant to call this special member. Just
12506         // explain why it's deleted.
12507         NoteDeletedFunction(Method);
12508         return ExprError();
12509       } else {
12510         Diag(OpLoc, diag::err_ovl_deleted_oper)
12511           << Best->Function->isDeleted()
12512           << BinaryOperator::getOpcodeStr(Opc)
12513           << getDeletedOrUnavailableSuffix(Best->Function)
12514           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12515       }
12516       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12517                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12518       return ExprError();
12519   }
12520 
12521   // We matched a built-in operator; build it.
12522   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12523 }
12524 
12525 ExprResult
12526 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12527                                          SourceLocation RLoc,
12528                                          Expr *Base, Expr *Idx) {
12529   Expr *Args[2] = { Base, Idx };
12530   DeclarationName OpName =
12531       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12532 
12533   // If either side is type-dependent, create an appropriate dependent
12534   // expression.
12535   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12536 
12537     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12538     // CHECKME: no 'operator' keyword?
12539     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12540     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12541     UnresolvedLookupExpr *Fn
12542       = UnresolvedLookupExpr::Create(Context, NamingClass,
12543                                      NestedNameSpecifierLoc(), OpNameInfo,
12544                                      /*ADL*/ true, /*Overloaded*/ false,
12545                                      UnresolvedSetIterator(),
12546                                      UnresolvedSetIterator());
12547     // Can't add any actual overloads yet
12548 
12549     return new (Context)
12550         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12551                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12552   }
12553 
12554   // Handle placeholders on both operands.
12555   if (checkPlaceholderForOverload(*this, Args[0]))
12556     return ExprError();
12557   if (checkPlaceholderForOverload(*this, Args[1]))
12558     return ExprError();
12559 
12560   // Build an empty overload set.
12561   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12562 
12563   // Subscript can only be overloaded as a member function.
12564 
12565   // Add operator candidates that are member functions.
12566   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12567 
12568   // Add builtin operator candidates.
12569   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12570 
12571   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12572 
12573   // Perform overload resolution.
12574   OverloadCandidateSet::iterator Best;
12575   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12576     case OR_Success: {
12577       // We found a built-in operator or an overloaded operator.
12578       FunctionDecl *FnDecl = Best->Function;
12579 
12580       if (FnDecl) {
12581         // We matched an overloaded operator. Build a call to that
12582         // operator.
12583 
12584         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12585 
12586         // Convert the arguments.
12587         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12588         ExprResult Arg0 =
12589           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12590                                               Best->FoundDecl, Method);
12591         if (Arg0.isInvalid())
12592           return ExprError();
12593         Args[0] = Arg0.get();
12594 
12595         // Convert the arguments.
12596         ExprResult InputInit
12597           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12598                                                       Context,
12599                                                       FnDecl->getParamDecl(0)),
12600                                       SourceLocation(),
12601                                       Args[1]);
12602         if (InputInit.isInvalid())
12603           return ExprError();
12604 
12605         Args[1] = InputInit.getAs<Expr>();
12606 
12607         // Build the actual expression node.
12608         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12609         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12610         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12611                                                   Best->FoundDecl,
12612                                                   Base,
12613                                                   HadMultipleCandidates,
12614                                                   OpLocInfo.getLoc(),
12615                                                   OpLocInfo.getInfo());
12616         if (FnExpr.isInvalid())
12617           return ExprError();
12618 
12619         // Determine the result type
12620         QualType ResultTy = FnDecl->getReturnType();
12621         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12622         ResultTy = ResultTy.getNonLValueExprType(Context);
12623 
12624         CXXOperatorCallExpr *TheCall =
12625           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12626                                             FnExpr.get(), Args,
12627                                             ResultTy, VK, RLoc,
12628                                             FPOptions());
12629 
12630         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12631           return ExprError();
12632 
12633         if (CheckFunctionCall(Method, TheCall,
12634                               Method->getType()->castAs<FunctionProtoType>()))
12635           return ExprError();
12636 
12637         return MaybeBindToTemporary(TheCall);
12638       } else {
12639         // We matched a built-in operator. Convert the arguments, then
12640         // break out so that we will build the appropriate built-in
12641         // operator node.
12642         ExprResult ArgsRes0 =
12643             PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12644                                       Best->Conversions[0], AA_Passing);
12645         if (ArgsRes0.isInvalid())
12646           return ExprError();
12647         Args[0] = ArgsRes0.get();
12648 
12649         ExprResult ArgsRes1 =
12650             PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12651                                       Best->Conversions[1], AA_Passing);
12652         if (ArgsRes1.isInvalid())
12653           return ExprError();
12654         Args[1] = ArgsRes1.get();
12655 
12656         break;
12657       }
12658     }
12659 
12660     case OR_No_Viable_Function: {
12661       if (CandidateSet.empty())
12662         Diag(LLoc, diag::err_ovl_no_oper)
12663           << Args[0]->getType() << /*subscript*/ 0
12664           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12665       else
12666         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12667           << Args[0]->getType()
12668           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12669       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12670                                   "[]", LLoc);
12671       return ExprError();
12672     }
12673 
12674     case OR_Ambiguous:
12675       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12676           << "[]"
12677           << Args[0]->getType() << Args[1]->getType()
12678           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12679       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12680                                   "[]", LLoc);
12681       return ExprError();
12682 
12683     case OR_Deleted:
12684       Diag(LLoc, diag::err_ovl_deleted_oper)
12685         << Best->Function->isDeleted() << "[]"
12686         << getDeletedOrUnavailableSuffix(Best->Function)
12687         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12688       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12689                                   "[]", LLoc);
12690       return ExprError();
12691     }
12692 
12693   // We matched a built-in operator; build it.
12694   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12695 }
12696 
12697 /// BuildCallToMemberFunction - Build a call to a member
12698 /// function. MemExpr is the expression that refers to the member
12699 /// function (and includes the object parameter), Args/NumArgs are the
12700 /// arguments to the function call (not including the object
12701 /// parameter). The caller needs to validate that the member
12702 /// expression refers to a non-static member function or an overloaded
12703 /// member function.
12704 ExprResult
12705 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12706                                 SourceLocation LParenLoc,
12707                                 MultiExprArg Args,
12708                                 SourceLocation RParenLoc) {
12709   assert(MemExprE->getType() == Context.BoundMemberTy ||
12710          MemExprE->getType() == Context.OverloadTy);
12711 
12712   // Dig out the member expression. This holds both the object
12713   // argument and the member function we're referring to.
12714   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12715 
12716   // Determine whether this is a call to a pointer-to-member function.
12717   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12718     assert(op->getType() == Context.BoundMemberTy);
12719     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12720 
12721     QualType fnType =
12722       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12723 
12724     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12725     QualType resultType = proto->getCallResultType(Context);
12726     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12727 
12728     // Check that the object type isn't more qualified than the
12729     // member function we're calling.
12730     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12731 
12732     QualType objectType = op->getLHS()->getType();
12733     if (op->getOpcode() == BO_PtrMemI)
12734       objectType = objectType->castAs<PointerType>()->getPointeeType();
12735     Qualifiers objectQuals = objectType.getQualifiers();
12736 
12737     Qualifiers difference = objectQuals - funcQuals;
12738     difference.removeObjCGCAttr();
12739     difference.removeAddressSpace();
12740     if (difference) {
12741       std::string qualsString = difference.getAsString();
12742       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12743         << fnType.getUnqualifiedType()
12744         << qualsString
12745         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12746     }
12747 
12748     CXXMemberCallExpr *call
12749       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12750                                         resultType, valueKind, RParenLoc);
12751 
12752     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12753                             call, nullptr))
12754       return ExprError();
12755 
12756     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12757       return ExprError();
12758 
12759     if (CheckOtherCall(call, proto))
12760       return ExprError();
12761 
12762     return MaybeBindToTemporary(call);
12763   }
12764 
12765   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12766     return new (Context)
12767         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12768 
12769   UnbridgedCastsSet UnbridgedCasts;
12770   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12771     return ExprError();
12772 
12773   MemberExpr *MemExpr;
12774   CXXMethodDecl *Method = nullptr;
12775   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12776   NestedNameSpecifier *Qualifier = nullptr;
12777   if (isa<MemberExpr>(NakedMemExpr)) {
12778     MemExpr = cast<MemberExpr>(NakedMemExpr);
12779     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12780     FoundDecl = MemExpr->getFoundDecl();
12781     Qualifier = MemExpr->getQualifier();
12782     UnbridgedCasts.restore();
12783   } else {
12784     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12785     Qualifier = UnresExpr->getQualifier();
12786 
12787     QualType ObjectType = UnresExpr->getBaseType();
12788     Expr::Classification ObjectClassification
12789       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12790                             : UnresExpr->getBase()->Classify(Context);
12791 
12792     // Add overload candidates
12793     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12794                                       OverloadCandidateSet::CSK_Normal);
12795 
12796     // FIXME: avoid copy.
12797     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12798     if (UnresExpr->hasExplicitTemplateArgs()) {
12799       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12800       TemplateArgs = &TemplateArgsBuffer;
12801     }
12802 
12803     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12804            E = UnresExpr->decls_end(); I != E; ++I) {
12805 
12806       NamedDecl *Func = *I;
12807       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12808       if (isa<UsingShadowDecl>(Func))
12809         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12810 
12811 
12812       // Microsoft supports direct constructor calls.
12813       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12814         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12815                              Args, CandidateSet);
12816       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12817         // If explicit template arguments were provided, we can't call a
12818         // non-template member function.
12819         if (TemplateArgs)
12820           continue;
12821 
12822         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12823                            ObjectClassification, Args, CandidateSet,
12824                            /*SuppressUserConversions=*/false);
12825       } else {
12826         AddMethodTemplateCandidate(
12827             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12828             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12829             /*SuppressUsedConversions=*/false);
12830       }
12831     }
12832 
12833     DeclarationName DeclName = UnresExpr->getMemberName();
12834 
12835     UnbridgedCasts.restore();
12836 
12837     OverloadCandidateSet::iterator Best;
12838     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12839                                             Best)) {
12840     case OR_Success:
12841       Method = cast<CXXMethodDecl>(Best->Function);
12842       FoundDecl = Best->FoundDecl;
12843       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12844       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12845         return ExprError();
12846       // If FoundDecl is different from Method (such as if one is a template
12847       // and the other a specialization), make sure DiagnoseUseOfDecl is
12848       // called on both.
12849       // FIXME: This would be more comprehensively addressed by modifying
12850       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12851       // being used.
12852       if (Method != FoundDecl.getDecl() &&
12853                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12854         return ExprError();
12855       break;
12856 
12857     case OR_No_Viable_Function:
12858       Diag(UnresExpr->getMemberLoc(),
12859            diag::err_ovl_no_viable_member_function_in_call)
12860         << DeclName << MemExprE->getSourceRange();
12861       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12862       // FIXME: Leaking incoming expressions!
12863       return ExprError();
12864 
12865     case OR_Ambiguous:
12866       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12867         << DeclName << MemExprE->getSourceRange();
12868       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12869       // FIXME: Leaking incoming expressions!
12870       return ExprError();
12871 
12872     case OR_Deleted:
12873       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12874         << Best->Function->isDeleted()
12875         << DeclName
12876         << getDeletedOrUnavailableSuffix(Best->Function)
12877         << MemExprE->getSourceRange();
12878       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12879       // FIXME: Leaking incoming expressions!
12880       return ExprError();
12881     }
12882 
12883     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12884 
12885     // If overload resolution picked a static member, build a
12886     // non-member call based on that function.
12887     if (Method->isStatic()) {
12888       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12889                                    RParenLoc);
12890     }
12891 
12892     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12893   }
12894 
12895   QualType ResultType = Method->getReturnType();
12896   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12897   ResultType = ResultType.getNonLValueExprType(Context);
12898 
12899   assert(Method && "Member call to something that isn't a method?");
12900   CXXMemberCallExpr *TheCall =
12901     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12902                                     ResultType, VK, RParenLoc);
12903 
12904   // Check for a valid return type.
12905   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12906                           TheCall, Method))
12907     return ExprError();
12908 
12909   // Convert the object argument (for a non-static member function call).
12910   // We only need to do this if there was actually an overload; otherwise
12911   // it was done at lookup.
12912   if (!Method->isStatic()) {
12913     ExprResult ObjectArg =
12914       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12915                                           FoundDecl, Method);
12916     if (ObjectArg.isInvalid())
12917       return ExprError();
12918     MemExpr->setBase(ObjectArg.get());
12919   }
12920 
12921   // Convert the rest of the arguments
12922   const FunctionProtoType *Proto =
12923     Method->getType()->getAs<FunctionProtoType>();
12924   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12925                               RParenLoc))
12926     return ExprError();
12927 
12928   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12929 
12930   if (CheckFunctionCall(Method, TheCall, Proto))
12931     return ExprError();
12932 
12933   // In the case the method to call was not selected by the overloading
12934   // resolution process, we still need to handle the enable_if attribute. Do
12935   // that here, so it will not hide previous -- and more relevant -- errors.
12936   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12937     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12938       Diag(MemE->getMemberLoc(),
12939            diag::err_ovl_no_viable_member_function_in_call)
12940           << Method << Method->getSourceRange();
12941       Diag(Method->getLocation(),
12942            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12943           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12944       return ExprError();
12945     }
12946   }
12947 
12948   if ((isa<CXXConstructorDecl>(CurContext) ||
12949        isa<CXXDestructorDecl>(CurContext)) &&
12950       TheCall->getMethodDecl()->isPure()) {
12951     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12952 
12953     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12954         MemExpr->performsVirtualDispatch(getLangOpts())) {
12955       Diag(MemExpr->getLocStart(),
12956            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12957         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12958         << MD->getParent()->getDeclName();
12959 
12960       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12961       if (getLangOpts().AppleKext)
12962         Diag(MemExpr->getLocStart(),
12963              diag::note_pure_qualified_call_kext)
12964              << MD->getParent()->getDeclName()
12965              << MD->getDeclName();
12966     }
12967   }
12968 
12969   if (CXXDestructorDecl *DD =
12970           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12971     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12972     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12973     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12974                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12975                          MemExpr->getMemberLoc());
12976   }
12977 
12978   return MaybeBindToTemporary(TheCall);
12979 }
12980 
12981 /// BuildCallToObjectOfClassType - Build a call to an object of class
12982 /// type (C++ [over.call.object]), which can end up invoking an
12983 /// overloaded function call operator (@c operator()) or performing a
12984 /// user-defined conversion on the object argument.
12985 ExprResult
12986 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12987                                    SourceLocation LParenLoc,
12988                                    MultiExprArg Args,
12989                                    SourceLocation RParenLoc) {
12990   if (checkPlaceholderForOverload(*this, Obj))
12991     return ExprError();
12992   ExprResult Object = Obj;
12993 
12994   UnbridgedCastsSet UnbridgedCasts;
12995   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12996     return ExprError();
12997 
12998   assert(Object.get()->getType()->isRecordType() &&
12999          "Requires object type argument");
13000   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13001 
13002   // C++ [over.call.object]p1:
13003   //  If the primary-expression E in the function call syntax
13004   //  evaluates to a class object of type "cv T", then the set of
13005   //  candidate functions includes at least the function call
13006   //  operators of T. The function call operators of T are obtained by
13007   //  ordinary lookup of the name operator() in the context of
13008   //  (E).operator().
13009   OverloadCandidateSet CandidateSet(LParenLoc,
13010                                     OverloadCandidateSet::CSK_Operator);
13011   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13012 
13013   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13014                           diag::err_incomplete_object_call, Object.get()))
13015     return true;
13016 
13017   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13018   LookupQualifiedName(R, Record->getDecl());
13019   R.suppressDiagnostics();
13020 
13021   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13022        Oper != OperEnd; ++Oper) {
13023     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13024                        Object.get()->Classify(Context), Args, CandidateSet,
13025                        /*SuppressUserConversions=*/false);
13026   }
13027 
13028   // C++ [over.call.object]p2:
13029   //   In addition, for each (non-explicit in C++0x) conversion function
13030   //   declared in T of the form
13031   //
13032   //        operator conversion-type-id () cv-qualifier;
13033   //
13034   //   where cv-qualifier is the same cv-qualification as, or a
13035   //   greater cv-qualification than, cv, and where conversion-type-id
13036   //   denotes the type "pointer to function of (P1,...,Pn) returning
13037   //   R", or the type "reference to pointer to function of
13038   //   (P1,...,Pn) returning R", or the type "reference to function
13039   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13040   //   is also considered as a candidate function. Similarly,
13041   //   surrogate call functions are added to the set of candidate
13042   //   functions for each conversion function declared in an
13043   //   accessible base class provided the function is not hidden
13044   //   within T by another intervening declaration.
13045   const auto &Conversions =
13046       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13047   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13048     NamedDecl *D = *I;
13049     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13050     if (isa<UsingShadowDecl>(D))
13051       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13052 
13053     // Skip over templated conversion functions; they aren't
13054     // surrogates.
13055     if (isa<FunctionTemplateDecl>(D))
13056       continue;
13057 
13058     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13059     if (!Conv->isExplicit()) {
13060       // Strip the reference type (if any) and then the pointer type (if
13061       // any) to get down to what might be a function type.
13062       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13063       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13064         ConvType = ConvPtrType->getPointeeType();
13065 
13066       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13067       {
13068         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13069                               Object.get(), Args, CandidateSet);
13070       }
13071     }
13072   }
13073 
13074   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13075 
13076   // Perform overload resolution.
13077   OverloadCandidateSet::iterator Best;
13078   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13079                                           Best)) {
13080   case OR_Success:
13081     // Overload resolution succeeded; we'll build the appropriate call
13082     // below.
13083     break;
13084 
13085   case OR_No_Viable_Function:
13086     if (CandidateSet.empty())
13087       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13088         << Object.get()->getType() << /*call*/ 1
13089         << Object.get()->getSourceRange();
13090     else
13091       Diag(Object.get()->getLocStart(),
13092            diag::err_ovl_no_viable_object_call)
13093         << Object.get()->getType() << Object.get()->getSourceRange();
13094     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13095     break;
13096 
13097   case OR_Ambiguous:
13098     Diag(Object.get()->getLocStart(),
13099          diag::err_ovl_ambiguous_object_call)
13100       << Object.get()->getType() << Object.get()->getSourceRange();
13101     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13102     break;
13103 
13104   case OR_Deleted:
13105     Diag(Object.get()->getLocStart(),
13106          diag::err_ovl_deleted_object_call)
13107       << Best->Function->isDeleted()
13108       << Object.get()->getType()
13109       << getDeletedOrUnavailableSuffix(Best->Function)
13110       << Object.get()->getSourceRange();
13111     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13112     break;
13113   }
13114 
13115   if (Best == CandidateSet.end())
13116     return true;
13117 
13118   UnbridgedCasts.restore();
13119 
13120   if (Best->Function == nullptr) {
13121     // Since there is no function declaration, this is one of the
13122     // surrogate candidates. Dig out the conversion function.
13123     CXXConversionDecl *Conv
13124       = cast<CXXConversionDecl>(
13125                          Best->Conversions[0].UserDefined.ConversionFunction);
13126 
13127     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13128                               Best->FoundDecl);
13129     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13130       return ExprError();
13131     assert(Conv == Best->FoundDecl.getDecl() &&
13132              "Found Decl & conversion-to-functionptr should be same, right?!");
13133     // We selected one of the surrogate functions that converts the
13134     // object parameter to a function pointer. Perform the conversion
13135     // on the object argument, then let ActOnCallExpr finish the job.
13136 
13137     // Create an implicit member expr to refer to the conversion operator.
13138     // and then call it.
13139     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13140                                              Conv, HadMultipleCandidates);
13141     if (Call.isInvalid())
13142       return ExprError();
13143     // Record usage of conversion in an implicit cast.
13144     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13145                                     CK_UserDefinedConversion, Call.get(),
13146                                     nullptr, VK_RValue);
13147 
13148     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13149   }
13150 
13151   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13152 
13153   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13154   // that calls this method, using Object for the implicit object
13155   // parameter and passing along the remaining arguments.
13156   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13157 
13158   // An error diagnostic has already been printed when parsing the declaration.
13159   if (Method->isInvalidDecl())
13160     return ExprError();
13161 
13162   const FunctionProtoType *Proto =
13163     Method->getType()->getAs<FunctionProtoType>();
13164 
13165   unsigned NumParams = Proto->getNumParams();
13166 
13167   DeclarationNameInfo OpLocInfo(
13168                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13169   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13170   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13171                                            Obj, HadMultipleCandidates,
13172                                            OpLocInfo.getLoc(),
13173                                            OpLocInfo.getInfo());
13174   if (NewFn.isInvalid())
13175     return true;
13176 
13177   // Build the full argument list for the method call (the implicit object
13178   // parameter is placed at the beginning of the list).
13179   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13180   MethodArgs[0] = Object.get();
13181   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13182 
13183   // Once we've built TheCall, all of the expressions are properly
13184   // owned.
13185   QualType ResultTy = Method->getReturnType();
13186   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13187   ResultTy = ResultTy.getNonLValueExprType(Context);
13188 
13189   CXXOperatorCallExpr *TheCall = new (Context)
13190       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13191                           VK, RParenLoc, FPOptions());
13192 
13193   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13194     return true;
13195 
13196   // We may have default arguments. If so, we need to allocate more
13197   // slots in the call for them.
13198   if (Args.size() < NumParams)
13199     TheCall->setNumArgs(Context, NumParams + 1);
13200 
13201   bool IsError = false;
13202 
13203   // Initialize the implicit object parameter.
13204   ExprResult ObjRes =
13205     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13206                                         Best->FoundDecl, Method);
13207   if (ObjRes.isInvalid())
13208     IsError = true;
13209   else
13210     Object = ObjRes;
13211   TheCall->setArg(0, Object.get());
13212 
13213   // Check the argument types.
13214   for (unsigned i = 0; i != NumParams; i++) {
13215     Expr *Arg;
13216     if (i < Args.size()) {
13217       Arg = Args[i];
13218 
13219       // Pass the argument.
13220 
13221       ExprResult InputInit
13222         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13223                                                     Context,
13224                                                     Method->getParamDecl(i)),
13225                                     SourceLocation(), Arg);
13226 
13227       IsError |= InputInit.isInvalid();
13228       Arg = InputInit.getAs<Expr>();
13229     } else {
13230       ExprResult DefArg
13231         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13232       if (DefArg.isInvalid()) {
13233         IsError = true;
13234         break;
13235       }
13236 
13237       Arg = DefArg.getAs<Expr>();
13238     }
13239 
13240     TheCall->setArg(i + 1, Arg);
13241   }
13242 
13243   // If this is a variadic call, handle args passed through "...".
13244   if (Proto->isVariadic()) {
13245     // Promote the arguments (C99 6.5.2.2p7).
13246     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13247       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13248                                                         nullptr);
13249       IsError |= Arg.isInvalid();
13250       TheCall->setArg(i + 1, Arg.get());
13251     }
13252   }
13253 
13254   if (IsError) return true;
13255 
13256   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13257 
13258   if (CheckFunctionCall(Method, TheCall, Proto))
13259     return true;
13260 
13261   return MaybeBindToTemporary(TheCall);
13262 }
13263 
13264 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13265 ///  (if one exists), where @c Base is an expression of class type and
13266 /// @c Member is the name of the member we're trying to find.
13267 ExprResult
13268 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13269                                bool *NoArrowOperatorFound) {
13270   assert(Base->getType()->isRecordType() &&
13271          "left-hand side must have class type");
13272 
13273   if (checkPlaceholderForOverload(*this, Base))
13274     return ExprError();
13275 
13276   SourceLocation Loc = Base->getExprLoc();
13277 
13278   // C++ [over.ref]p1:
13279   //
13280   //   [...] An expression x->m is interpreted as (x.operator->())->m
13281   //   for a class object x of type T if T::operator->() exists and if
13282   //   the operator is selected as the best match function by the
13283   //   overload resolution mechanism (13.3).
13284   DeclarationName OpName =
13285     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13286   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13287   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13288 
13289   if (RequireCompleteType(Loc, Base->getType(),
13290                           diag::err_typecheck_incomplete_tag, Base))
13291     return ExprError();
13292 
13293   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13294   LookupQualifiedName(R, BaseRecord->getDecl());
13295   R.suppressDiagnostics();
13296 
13297   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13298        Oper != OperEnd; ++Oper) {
13299     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13300                        None, CandidateSet, /*SuppressUserConversions=*/false);
13301   }
13302 
13303   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13304 
13305   // Perform overload resolution.
13306   OverloadCandidateSet::iterator Best;
13307   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13308   case OR_Success:
13309     // Overload resolution succeeded; we'll build the call below.
13310     break;
13311 
13312   case OR_No_Viable_Function:
13313     if (CandidateSet.empty()) {
13314       QualType BaseType = Base->getType();
13315       if (NoArrowOperatorFound) {
13316         // Report this specific error to the caller instead of emitting a
13317         // diagnostic, as requested.
13318         *NoArrowOperatorFound = true;
13319         return ExprError();
13320       }
13321       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13322         << BaseType << Base->getSourceRange();
13323       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13324         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13325           << FixItHint::CreateReplacement(OpLoc, ".");
13326       }
13327     } else
13328       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13329         << "operator->" << Base->getSourceRange();
13330     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13331     return ExprError();
13332 
13333   case OR_Ambiguous:
13334     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13335       << "->" << Base->getType() << Base->getSourceRange();
13336     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13337     return ExprError();
13338 
13339   case OR_Deleted:
13340     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13341       << Best->Function->isDeleted()
13342       << "->"
13343       << getDeletedOrUnavailableSuffix(Best->Function)
13344       << Base->getSourceRange();
13345     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13346     return ExprError();
13347   }
13348 
13349   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13350 
13351   // Convert the object parameter.
13352   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13353   ExprResult BaseResult =
13354     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13355                                         Best->FoundDecl, Method);
13356   if (BaseResult.isInvalid())
13357     return ExprError();
13358   Base = BaseResult.get();
13359 
13360   // Build the operator call.
13361   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13362                                             Base, HadMultipleCandidates, OpLoc);
13363   if (FnExpr.isInvalid())
13364     return ExprError();
13365 
13366   QualType ResultTy = Method->getReturnType();
13367   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13368   ResultTy = ResultTy.getNonLValueExprType(Context);
13369   CXXOperatorCallExpr *TheCall =
13370     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13371                                       Base, ResultTy, VK, OpLoc, FPOptions());
13372 
13373   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13374     return ExprError();
13375 
13376   if (CheckFunctionCall(Method, TheCall,
13377                         Method->getType()->castAs<FunctionProtoType>()))
13378     return ExprError();
13379 
13380   return MaybeBindToTemporary(TheCall);
13381 }
13382 
13383 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13384 /// a literal operator described by the provided lookup results.
13385 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13386                                           DeclarationNameInfo &SuffixInfo,
13387                                           ArrayRef<Expr*> Args,
13388                                           SourceLocation LitEndLoc,
13389                                        TemplateArgumentListInfo *TemplateArgs) {
13390   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13391 
13392   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13393                                     OverloadCandidateSet::CSK_Normal);
13394   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13395                         /*SuppressUserConversions=*/true);
13396 
13397   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13398 
13399   // Perform overload resolution. This will usually be trivial, but might need
13400   // to perform substitutions for a literal operator template.
13401   OverloadCandidateSet::iterator Best;
13402   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13403   case OR_Success:
13404   case OR_Deleted:
13405     break;
13406 
13407   case OR_No_Viable_Function:
13408     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13409       << R.getLookupName();
13410     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13411     return ExprError();
13412 
13413   case OR_Ambiguous:
13414     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13415     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13416     return ExprError();
13417   }
13418 
13419   FunctionDecl *FD = Best->Function;
13420   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13421                                         nullptr, HadMultipleCandidates,
13422                                         SuffixInfo.getLoc(),
13423                                         SuffixInfo.getInfo());
13424   if (Fn.isInvalid())
13425     return true;
13426 
13427   // Check the argument types. This should almost always be a no-op, except
13428   // that array-to-pointer decay is applied to string literals.
13429   Expr *ConvArgs[2];
13430   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13431     ExprResult InputInit = PerformCopyInitialization(
13432       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13433       SourceLocation(), Args[ArgIdx]);
13434     if (InputInit.isInvalid())
13435       return true;
13436     ConvArgs[ArgIdx] = InputInit.get();
13437   }
13438 
13439   QualType ResultTy = FD->getReturnType();
13440   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13441   ResultTy = ResultTy.getNonLValueExprType(Context);
13442 
13443   UserDefinedLiteral *UDL =
13444     new (Context) UserDefinedLiteral(Context, Fn.get(),
13445                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13446                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13447 
13448   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13449     return ExprError();
13450 
13451   if (CheckFunctionCall(FD, UDL, nullptr))
13452     return ExprError();
13453 
13454   return MaybeBindToTemporary(UDL);
13455 }
13456 
13457 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13458 /// given LookupResult is non-empty, it is assumed to describe a member which
13459 /// will be invoked. Otherwise, the function will be found via argument
13460 /// dependent lookup.
13461 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13462 /// otherwise CallExpr is set to ExprError() and some non-success value
13463 /// is returned.
13464 Sema::ForRangeStatus
13465 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13466                                 SourceLocation RangeLoc,
13467                                 const DeclarationNameInfo &NameInfo,
13468                                 LookupResult &MemberLookup,
13469                                 OverloadCandidateSet *CandidateSet,
13470                                 Expr *Range, ExprResult *CallExpr) {
13471   Scope *S = nullptr;
13472 
13473   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13474   if (!MemberLookup.empty()) {
13475     ExprResult MemberRef =
13476         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13477                                  /*IsPtr=*/false, CXXScopeSpec(),
13478                                  /*TemplateKWLoc=*/SourceLocation(),
13479                                  /*FirstQualifierInScope=*/nullptr,
13480                                  MemberLookup,
13481                                  /*TemplateArgs=*/nullptr, S);
13482     if (MemberRef.isInvalid()) {
13483       *CallExpr = ExprError();
13484       return FRS_DiagnosticIssued;
13485     }
13486     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13487     if (CallExpr->isInvalid()) {
13488       *CallExpr = ExprError();
13489       return FRS_DiagnosticIssued;
13490     }
13491   } else {
13492     UnresolvedSet<0> FoundNames;
13493     UnresolvedLookupExpr *Fn =
13494       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13495                                    NestedNameSpecifierLoc(), NameInfo,
13496                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13497                                    FoundNames.begin(), FoundNames.end());
13498 
13499     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13500                                                     CandidateSet, CallExpr);
13501     if (CandidateSet->empty() || CandidateSetError) {
13502       *CallExpr = ExprError();
13503       return FRS_NoViableFunction;
13504     }
13505     OverloadCandidateSet::iterator Best;
13506     OverloadingResult OverloadResult =
13507         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13508 
13509     if (OverloadResult == OR_No_Viable_Function) {
13510       *CallExpr = ExprError();
13511       return FRS_NoViableFunction;
13512     }
13513     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13514                                          Loc, nullptr, CandidateSet, &Best,
13515                                          OverloadResult,
13516                                          /*AllowTypoCorrection=*/false);
13517     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13518       *CallExpr = ExprError();
13519       return FRS_DiagnosticIssued;
13520     }
13521   }
13522   return FRS_Success;
13523 }
13524 
13525 
13526 /// FixOverloadedFunctionReference - E is an expression that refers to
13527 /// a C++ overloaded function (possibly with some parentheses and
13528 /// perhaps a '&' around it). We have resolved the overloaded function
13529 /// to the function declaration Fn, so patch up the expression E to
13530 /// refer (possibly indirectly) to Fn. Returns the new expr.
13531 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13532                                            FunctionDecl *Fn) {
13533   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13534     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13535                                                    Found, Fn);
13536     if (SubExpr == PE->getSubExpr())
13537       return PE;
13538 
13539     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13540   }
13541 
13542   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13543     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13544                                                    Found, Fn);
13545     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13546                                SubExpr->getType()) &&
13547            "Implicit cast type cannot be determined from overload");
13548     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13549     if (SubExpr == ICE->getSubExpr())
13550       return ICE;
13551 
13552     return ImplicitCastExpr::Create(Context, ICE->getType(),
13553                                     ICE->getCastKind(),
13554                                     SubExpr, nullptr,
13555                                     ICE->getValueKind());
13556   }
13557 
13558   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13559     if (!GSE->isResultDependent()) {
13560       Expr *SubExpr =
13561           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13562       if (SubExpr == GSE->getResultExpr())
13563         return GSE;
13564 
13565       // Replace the resulting type information before rebuilding the generic
13566       // selection expression.
13567       ArrayRef<Expr *> A = GSE->getAssocExprs();
13568       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13569       unsigned ResultIdx = GSE->getResultIndex();
13570       AssocExprs[ResultIdx] = SubExpr;
13571 
13572       return new (Context) GenericSelectionExpr(
13573           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13574           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13575           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13576           ResultIdx);
13577     }
13578     // Rather than fall through to the unreachable, return the original generic
13579     // selection expression.
13580     return GSE;
13581   }
13582 
13583   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13584     assert(UnOp->getOpcode() == UO_AddrOf &&
13585            "Can only take the address of an overloaded function");
13586     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13587       if (Method->isStatic()) {
13588         // Do nothing: static member functions aren't any different
13589         // from non-member functions.
13590       } else {
13591         // Fix the subexpression, which really has to be an
13592         // UnresolvedLookupExpr holding an overloaded member function
13593         // or template.
13594         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13595                                                        Found, Fn);
13596         if (SubExpr == UnOp->getSubExpr())
13597           return UnOp;
13598 
13599         assert(isa<DeclRefExpr>(SubExpr)
13600                && "fixed to something other than a decl ref");
13601         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13602                && "fixed to a member ref with no nested name qualifier");
13603 
13604         // We have taken the address of a pointer to member
13605         // function. Perform the computation here so that we get the
13606         // appropriate pointer to member type.
13607         QualType ClassType
13608           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13609         QualType MemPtrType
13610           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13611         // Under the MS ABI, lock down the inheritance model now.
13612         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13613           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13614 
13615         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13616                                            VK_RValue, OK_Ordinary,
13617                                            UnOp->getOperatorLoc(), false);
13618       }
13619     }
13620     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13621                                                    Found, Fn);
13622     if (SubExpr == UnOp->getSubExpr())
13623       return UnOp;
13624 
13625     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13626                                      Context.getPointerType(SubExpr->getType()),
13627                                        VK_RValue, OK_Ordinary,
13628                                        UnOp->getOperatorLoc(), false);
13629   }
13630 
13631   // C++ [except.spec]p17:
13632   //   An exception-specification is considered to be needed when:
13633   //   - in an expression the function is the unique lookup result or the
13634   //     selected member of a set of overloaded functions
13635   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13636     ResolveExceptionSpec(E->getExprLoc(), FPT);
13637 
13638   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13639     // FIXME: avoid copy.
13640     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13641     if (ULE->hasExplicitTemplateArgs()) {
13642       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13643       TemplateArgs = &TemplateArgsBuffer;
13644     }
13645 
13646     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13647                                            ULE->getQualifierLoc(),
13648                                            ULE->getTemplateKeywordLoc(),
13649                                            Fn,
13650                                            /*enclosing*/ false, // FIXME?
13651                                            ULE->getNameLoc(),
13652                                            Fn->getType(),
13653                                            VK_LValue,
13654                                            Found.getDecl(),
13655                                            TemplateArgs);
13656     MarkDeclRefReferenced(DRE);
13657     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13658     return DRE;
13659   }
13660 
13661   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13662     // FIXME: avoid copy.
13663     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13664     if (MemExpr->hasExplicitTemplateArgs()) {
13665       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13666       TemplateArgs = &TemplateArgsBuffer;
13667     }
13668 
13669     Expr *Base;
13670 
13671     // If we're filling in a static method where we used to have an
13672     // implicit member access, rewrite to a simple decl ref.
13673     if (MemExpr->isImplicitAccess()) {
13674       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13675         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13676                                                MemExpr->getQualifierLoc(),
13677                                                MemExpr->getTemplateKeywordLoc(),
13678                                                Fn,
13679                                                /*enclosing*/ false,
13680                                                MemExpr->getMemberLoc(),
13681                                                Fn->getType(),
13682                                                VK_LValue,
13683                                                Found.getDecl(),
13684                                                TemplateArgs);
13685         MarkDeclRefReferenced(DRE);
13686         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13687         return DRE;
13688       } else {
13689         SourceLocation Loc = MemExpr->getMemberLoc();
13690         if (MemExpr->getQualifier())
13691           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13692         CheckCXXThisCapture(Loc);
13693         Base = new (Context) CXXThisExpr(Loc,
13694                                          MemExpr->getBaseType(),
13695                                          /*isImplicit=*/true);
13696       }
13697     } else
13698       Base = MemExpr->getBase();
13699 
13700     ExprValueKind valueKind;
13701     QualType type;
13702     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13703       valueKind = VK_LValue;
13704       type = Fn->getType();
13705     } else {
13706       valueKind = VK_RValue;
13707       type = Context.BoundMemberTy;
13708     }
13709 
13710     MemberExpr *ME = MemberExpr::Create(
13711         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13712         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13713         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13714         OK_Ordinary);
13715     ME->setHadMultipleCandidates(true);
13716     MarkMemberReferenced(ME);
13717     return ME;
13718   }
13719 
13720   llvm_unreachable("Invalid reference to overloaded function");
13721 }
13722 
13723 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13724                                                 DeclAccessPair Found,
13725                                                 FunctionDecl *Fn) {
13726   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13727 }
13728