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                       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);
72   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73                              CK_FunctionToPointerDecay);
74 }
75 
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77                                  bool InOverloadResolution,
78                                  StandardConversionSequence &SCS,
79                                  bool CStyle,
80                                  bool AllowObjCWritebackConversion);
81 
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83                                                  QualType &ToType,
84                                                  bool InOverloadResolution,
85                                                  StandardConversionSequence &SCS,
86                                                  bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89                         UserDefinedConversionSequence& User,
90                         OverloadCandidateSet& Conversions,
91                         bool AllowExplicit,
92                         bool AllowObjCConversionOnExplicit);
93 
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97                                    const StandardConversionSequence& SCS1,
98                                    const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109 
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113   static const ImplicitConversionRank
114     Rank[(int)ICK_Num_Conversion_Kinds] = {
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Promotion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_OCL_Scalar_Widening,
135     ICR_Complex_Real_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Writeback_Conversion,
139     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140                      // it was omitted by the patch that added
141                      // ICK_Zero_Event_Conversion
142     ICR_C_Conversion,
143     ICR_C_Conversion_Extension
144   };
145   return Rank[(int)Kind];
146 }
147 
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152     "No conversion",
153     "Lvalue-to-rvalue",
154     "Array-to-pointer",
155     "Function-to-pointer",
156     "Function pointer conversion",
157     "Qualification",
158     "Integral promotion",
159     "Floating point promotion",
160     "Complex promotion",
161     "Integral conversion",
162     "Floating conversion",
163     "Complex conversion",
164     "Floating-integral conversion",
165     "Pointer conversion",
166     "Pointer-to-member conversion",
167     "Boolean conversion",
168     "Compatible-types conversion",
169     "Derived-to-base conversion",
170     "Vector conversion",
171     "Vector splat",
172     "Complex-real conversion",
173     "Block Pointer conversion",
174     "Transparent Union Conversion",
175     "Writeback conversion",
176     "OpenCL Zero Event Conversion",
177     "C specific type conversion",
178     "Incompatible pointer conversion"
179   };
180   return Name[Kind];
181 }
182 
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186   First = ICK_Identity;
187   Second = ICK_Identity;
188   Third = ICK_Identity;
189   DeprecatedStringLiteralToCharPtr = false;
190   QualificationIncludesObjCLifetime = false;
191   ReferenceBinding = false;
192   DirectBinding = false;
193   IsLvalueReference = true;
194   BindsToFunctionLvalue = false;
195   BindsToRvalue = false;
196   BindsImplicitObjectArgumentWithoutRefQualifier = false;
197   ObjCLifetimeConversionBinding = false;
198   CopyConstructor = nullptr;
199 }
200 
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205   ImplicitConversionRank Rank = ICR_Exact_Match;
206   if  (GetConversionRank(First) > Rank)
207     Rank = GetConversionRank(First);
208   if  (GetConversionRank(Second) > Rank)
209     Rank = GetConversionRank(Second);
210   if  (GetConversionRank(Third) > Rank)
211     Rank = GetConversionRank(Third);
212   return Rank;
213 }
214 
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220   // Note that FromType has not necessarily been transformed by the
221   // array-to-pointer or function-to-pointer implicit conversions, so
222   // check for their presence as well as checking whether FromType is
223   // a pointer.
224   if (getToType(1)->isBooleanType() &&
225       (getFromType()->isPointerType() ||
226        getFromType()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231 
232   return false;
233 }
234 
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244 
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250 
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254 
255   return false;
256 }
257 
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262     switch (ICE->getCastKind()) {
263     case CK_NoOp:
264     case CK_IntegralCast:
265     case CK_IntegralToBoolean:
266     case CK_IntegralToFloating:
267     case CK_BooleanToSignedIntegral:
268     case CK_FloatingToIntegral:
269     case CK_FloatingToBoolean:
270     case CK_FloatingCast:
271       Converted = ICE->getSubExpr();
272       continue;
273 
274     default:
275       return Converted;
276     }
277   }
278 
279   return Converted;
280 }
281 
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
284 ///
285 /// \param Ctx  The AST context.
286 /// \param Converted  The result of applying this standard conversion sequence.
287 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288 ///        value of the expression prior to the narrowing conversion.
289 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290 ///        type of the expression prior to the narrowing conversion.
291 NarrowingKind
292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293                                              const Expr *Converted,
294                                              APValue &ConstantValue,
295                                              QualType &ConstantType) const {
296   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297 
298   // C++11 [dcl.init.list]p7:
299   //   A narrowing conversion is an implicit conversion ...
300   QualType FromType = getToType(0);
301   QualType ToType = getToType(1);
302 
303   // A conversion to an enumeration type is narrowing if the conversion to
304   // the underlying type is narrowing. This only arises for expressions of
305   // the form 'Enum{init}'.
306   if (auto *ET = ToType->getAs<EnumType>())
307     ToType = ET->getDecl()->getIntegerType();
308 
309   switch (Second) {
310   // 'bool' is an integral type; dispatch to the right place to handle it.
311   case ICK_Boolean_Conversion:
312     if (FromType->isRealFloatingType())
313       goto FloatingIntegralConversion;
314     if (FromType->isIntegralOrUnscopedEnumerationType())
315       goto IntegralConversion;
316     // Boolean conversions can be from pointers and pointers to members
317     // [conv.bool], and those aren't considered narrowing conversions.
318     return NK_Not_Narrowing;
319 
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327   FloatingIntegralConversion:
328     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329       return NK_Type_Narrowing;
330     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331       llvm::APSInt IntConstantValue;
332       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333 
334       // If it's value-dependent, we can't tell whether it's narrowing.
335       if (Initializer->isValueDependent())
336         return NK_Dependent_Narrowing;
337 
338       if (Initializer &&
339           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340         // Convert the integer to the floating type.
341         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343                                 llvm::APFloat::rmNearestTiesToEven);
344         // And back.
345         llvm::APSInt ConvertedValue = IntConstantValue;
346         bool ignored;
347         Result.convertToInteger(ConvertedValue,
348                                 llvm::APFloat::rmTowardZero, &ignored);
349         // If the resulting value is different, this was a narrowing conversion.
350         if (IntConstantValue != ConvertedValue) {
351           ConstantValue = APValue(IntConstantValue);
352           ConstantType = Initializer->getType();
353           return NK_Constant_Narrowing;
354         }
355       } else {
356         // Variables are always narrowings.
357         return NK_Variable_Narrowing;
358       }
359     }
360     return NK_Not_Narrowing;
361 
362   // -- from long double to double or float, or from double to float, except
363   //    where the source is a constant expression and the actual value after
364   //    conversion is within the range of values that can be represented (even
365   //    if it cannot be represented exactly), or
366   case ICK_Floating_Conversion:
367     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369       // FromType is larger than ToType.
370       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
371 
372       // If it's value-dependent, we can't tell whether it's narrowing.
373       if (Initializer->isValueDependent())
374         return NK_Dependent_Narrowing;
375 
376       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377         // Constant!
378         assert(ConstantValue.isFloat());
379         llvm::APFloat FloatVal = ConstantValue.getFloat();
380         // Convert the source value into the target type.
381         bool ignored;
382         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383           Ctx.getFloatTypeSemantics(ToType),
384           llvm::APFloat::rmNearestTiesToEven, &ignored);
385         // If there was no overflow, the source value is within the range of
386         // values that can be represented.
387         if (ConvertStatus & llvm::APFloat::opOverflow) {
388           ConstantType = Initializer->getType();
389           return NK_Constant_Narrowing;
390         }
391       } else {
392         return NK_Variable_Narrowing;
393       }
394     }
395     return NK_Not_Narrowing;
396 
397   // -- from an integer type or unscoped enumeration type to an integer type
398   //    that cannot represent all the values of the original type, except where
399   //    the source is a constant expression and the actual value after
400   //    conversion will fit into the target type and will produce the original
401   //    value when converted back to the original type.
402   case ICK_Integral_Conversion:
403   IntegralConversion: {
404     assert(FromType->isIntegralOrUnscopedEnumerationType());
405     assert(ToType->isIntegralOrUnscopedEnumerationType());
406     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407     const unsigned FromWidth = Ctx.getIntWidth(FromType);
408     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409     const unsigned ToWidth = Ctx.getIntWidth(ToType);
410 
411     if (FromWidth > ToWidth ||
412         (FromWidth == ToWidth && FromSigned != ToSigned) ||
413         (FromSigned && !ToSigned)) {
414       // Not all values of FromType can be represented in ToType.
415       llvm::APSInt InitializerValue;
416       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
417 
418       // If it's value-dependent, we can't tell whether it's narrowing.
419       if (Initializer->isValueDependent())
420         return NK_Dependent_Narrowing;
421 
422       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423         // Such conversions on variables are always narrowing.
424         return NK_Variable_Narrowing;
425       }
426       bool Narrowing = false;
427       if (FromWidth < ToWidth) {
428         // Negative -> unsigned is narrowing. Otherwise, more bits is never
429         // narrowing.
430         if (InitializerValue.isSigned() && InitializerValue.isNegative())
431           Narrowing = true;
432       } else {
433         // Add a bit to the InitializerValue so we don't have to worry about
434         // signed vs. unsigned comparisons.
435         InitializerValue = InitializerValue.extend(
436           InitializerValue.getBitWidth() + 1);
437         // Convert the initializer to and from the target width and signed-ness.
438         llvm::APSInt ConvertedValue = InitializerValue;
439         ConvertedValue = ConvertedValue.trunc(ToWidth);
440         ConvertedValue.setIsSigned(ToSigned);
441         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442         ConvertedValue.setIsSigned(InitializerValue.isSigned());
443         // If the result is different, this was a narrowing conversion.
444         if (ConvertedValue != InitializerValue)
445           Narrowing = true;
446       }
447       if (Narrowing) {
448         ConstantType = Initializer->getType();
449         ConstantValue = APValue(InitializerValue);
450         return NK_Constant_Narrowing;
451       }
452     }
453     return NK_Not_Narrowing;
454   }
455 
456   default:
457     // Other kinds of conversions are not narrowings.
458     return NK_Not_Narrowing;
459   }
460 }
461 
462 /// dump - Print this standard conversion sequence to standard
463 /// error. Useful for debugging overloading issues.
464 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
465   raw_ostream &OS = llvm::errs();
466   bool PrintedSomething = false;
467   if (First != ICK_Identity) {
468     OS << GetImplicitConversionName(First);
469     PrintedSomething = true;
470   }
471 
472   if (Second != ICK_Identity) {
473     if (PrintedSomething) {
474       OS << " -> ";
475     }
476     OS << GetImplicitConversionName(Second);
477 
478     if (CopyConstructor) {
479       OS << " (by copy constructor)";
480     } else if (DirectBinding) {
481       OS << " (direct reference binding)";
482     } else if (ReferenceBinding) {
483       OS << " (reference binding)";
484     }
485     PrintedSomething = true;
486   }
487 
488   if (Third != ICK_Identity) {
489     if (PrintedSomething) {
490       OS << " -> ";
491     }
492     OS << GetImplicitConversionName(Third);
493     PrintedSomething = true;
494   }
495 
496   if (!PrintedSomething) {
497     OS << "No conversions required";
498   }
499 }
500 
501 /// dump - Print this user-defined conversion sequence to standard
502 /// error. Useful for debugging overloading issues.
503 void UserDefinedConversionSequence::dump() const {
504   raw_ostream &OS = llvm::errs();
505   if (Before.First || Before.Second || Before.Third) {
506     Before.dump();
507     OS << " -> ";
508   }
509   if (ConversionFunction)
510     OS << '\'' << *ConversionFunction << '\'';
511   else
512     OS << "aggregate initialization";
513   if (After.First || After.Second || After.Third) {
514     OS << " -> ";
515     After.dump();
516   }
517 }
518 
519 /// dump - Print this implicit conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void ImplicitConversionSequence::dump() const {
522   raw_ostream &OS = llvm::errs();
523   if (isStdInitializerListElement())
524     OS << "Worst std::initializer_list element conversion: ";
525   switch (ConversionKind) {
526   case StandardConversion:
527     OS << "Standard conversion: ";
528     Standard.dump();
529     break;
530   case UserDefinedConversion:
531     OS << "User-defined conversion: ";
532     UserDefined.dump();
533     break;
534   case EllipsisConversion:
535     OS << "Ellipsis conversion";
536     break;
537   case AmbiguousConversion:
538     OS << "Ambiguous conversion";
539     break;
540   case BadConversion:
541     OS << "Bad conversion";
542     break;
543   }
544 
545   OS << "\n";
546 }
547 
548 void AmbiguousConversionSequence::construct() {
549   new (&conversions()) ConversionSet();
550 }
551 
552 void AmbiguousConversionSequence::destruct() {
553   conversions().~ConversionSet();
554 }
555 
556 void
557 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558   FromTypePtr = O.FromTypePtr;
559   ToTypePtr = O.ToTypePtr;
560   new (&conversions()) ConversionSet(O.conversions());
561 }
562 
563 namespace {
564   // Structure used by DeductionFailureInfo to store
565   // template argument information.
566   struct DFIArguments {
567     TemplateArgument FirstArg;
568     TemplateArgument SecondArg;
569   };
570   // Structure used by DeductionFailureInfo to store
571   // template parameter and template argument information.
572   struct DFIParamWithArguments : DFIArguments {
573     TemplateParameter Param;
574   };
575   // Structure used by DeductionFailureInfo to store template argument
576   // information and the index of the problematic call argument.
577   struct DFIDeducedMismatchArgs : DFIArguments {
578     TemplateArgumentList *TemplateArgs;
579     unsigned CallArgIndex;
580   };
581 }
582 
583 /// \brief Convert from Sema's representation of template deduction information
584 /// to the form used in overload-candidate information.
585 DeductionFailureInfo
586 clang::MakeDeductionFailureInfo(ASTContext &Context,
587                                 Sema::TemplateDeductionResult TDK,
588                                 TemplateDeductionInfo &Info) {
589   DeductionFailureInfo Result;
590   Result.Result = static_cast<unsigned>(TDK);
591   Result.HasDiagnostic = false;
592   switch (TDK) {
593   case Sema::TDK_Invalid:
594   case Sema::TDK_InstantiationDepth:
595   case Sema::TDK_TooManyArguments:
596   case Sema::TDK_TooFewArguments:
597   case Sema::TDK_MiscellaneousDeductionFailure:
598   case Sema::TDK_CUDATargetMismatch:
599     Result.Data = nullptr;
600     break;
601 
602   case Sema::TDK_Incomplete:
603   case Sema::TDK_InvalidExplicitArguments:
604     Result.Data = Info.Param.getOpaqueValue();
605     break;
606 
607   case Sema::TDK_DeducedMismatch:
608   case Sema::TDK_DeducedMismatchNested: {
609     // FIXME: Should allocate from normal heap so that we can free this later.
610     auto *Saved = new (Context) DFIDeducedMismatchArgs;
611     Saved->FirstArg = Info.FirstArg;
612     Saved->SecondArg = Info.SecondArg;
613     Saved->TemplateArgs = Info.take();
614     Saved->CallArgIndex = Info.CallArgIndex;
615     Result.Data = Saved;
616     break;
617   }
618 
619   case Sema::TDK_NonDeducedMismatch: {
620     // FIXME: Should allocate from normal heap so that we can free this later.
621     DFIArguments *Saved = new (Context) DFIArguments;
622     Saved->FirstArg = Info.FirstArg;
623     Saved->SecondArg = Info.SecondArg;
624     Result.Data = Saved;
625     break;
626   }
627 
628   case Sema::TDK_Inconsistent:
629   case Sema::TDK_Underqualified: {
630     // FIXME: Should allocate from normal heap so that we can free this later.
631     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
632     Saved->Param = Info.Param;
633     Saved->FirstArg = Info.FirstArg;
634     Saved->SecondArg = Info.SecondArg;
635     Result.Data = Saved;
636     break;
637   }
638 
639   case Sema::TDK_SubstitutionFailure:
640     Result.Data = Info.take();
641     if (Info.hasSFINAEDiagnostic()) {
642       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643           SourceLocation(), PartialDiagnostic::NullDiagnostic());
644       Info.takeSFINAEDiagnostic(*Diag);
645       Result.HasDiagnostic = true;
646     }
647     break;
648 
649   case Sema::TDK_Success:
650   case Sema::TDK_NonDependentConversionFailure:
651     llvm_unreachable("not a deduction failure");
652   }
653 
654   return Result;
655 }
656 
657 void DeductionFailureInfo::Destroy() {
658   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659   case Sema::TDK_Success:
660   case Sema::TDK_Invalid:
661   case Sema::TDK_InstantiationDepth:
662   case Sema::TDK_Incomplete:
663   case Sema::TDK_TooManyArguments:
664   case Sema::TDK_TooFewArguments:
665   case Sema::TDK_InvalidExplicitArguments:
666   case Sema::TDK_CUDATargetMismatch:
667   case Sema::TDK_NonDependentConversionFailure:
668     break;
669 
670   case Sema::TDK_Inconsistent:
671   case Sema::TDK_Underqualified:
672   case Sema::TDK_DeducedMismatch:
673   case Sema::TDK_DeducedMismatchNested:
674   case Sema::TDK_NonDeducedMismatch:
675     // FIXME: Destroy the data?
676     Data = nullptr;
677     break;
678 
679   case Sema::TDK_SubstitutionFailure:
680     // FIXME: Destroy the template argument list?
681     Data = nullptr;
682     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683       Diag->~PartialDiagnosticAt();
684       HasDiagnostic = false;
685     }
686     break;
687 
688   // Unhandled
689   case Sema::TDK_MiscellaneousDeductionFailure:
690     break;
691   }
692 }
693 
694 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
695   if (HasDiagnostic)
696     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
697   return nullptr;
698 }
699 
700 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
701   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702   case Sema::TDK_Success:
703   case Sema::TDK_Invalid:
704   case Sema::TDK_InstantiationDepth:
705   case Sema::TDK_TooManyArguments:
706   case Sema::TDK_TooFewArguments:
707   case Sema::TDK_SubstitutionFailure:
708   case Sema::TDK_DeducedMismatch:
709   case Sema::TDK_DeducedMismatchNested:
710   case Sema::TDK_NonDeducedMismatch:
711   case Sema::TDK_CUDATargetMismatch:
712   case Sema::TDK_NonDependentConversionFailure:
713     return TemplateParameter();
714 
715   case Sema::TDK_Incomplete:
716   case Sema::TDK_InvalidExplicitArguments:
717     return TemplateParameter::getFromOpaqueValue(Data);
718 
719   case Sema::TDK_Inconsistent:
720   case Sema::TDK_Underqualified:
721     return static_cast<DFIParamWithArguments*>(Data)->Param;
722 
723   // Unhandled
724   case Sema::TDK_MiscellaneousDeductionFailure:
725     break;
726   }
727 
728   return TemplateParameter();
729 }
730 
731 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
732   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733   case Sema::TDK_Success:
734   case Sema::TDK_Invalid:
735   case Sema::TDK_InstantiationDepth:
736   case Sema::TDK_TooManyArguments:
737   case Sema::TDK_TooFewArguments:
738   case Sema::TDK_Incomplete:
739   case Sema::TDK_InvalidExplicitArguments:
740   case Sema::TDK_Inconsistent:
741   case Sema::TDK_Underqualified:
742   case Sema::TDK_NonDeducedMismatch:
743   case Sema::TDK_CUDATargetMismatch:
744   case Sema::TDK_NonDependentConversionFailure:
745     return nullptr;
746 
747   case Sema::TDK_DeducedMismatch:
748   case Sema::TDK_DeducedMismatchNested:
749     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750 
751   case Sema::TDK_SubstitutionFailure:
752     return static_cast<TemplateArgumentList*>(Data);
753 
754   // Unhandled
755   case Sema::TDK_MiscellaneousDeductionFailure:
756     break;
757   }
758 
759   return nullptr;
760 }
761 
762 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
763   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764   case Sema::TDK_Success:
765   case Sema::TDK_Invalid:
766   case Sema::TDK_InstantiationDepth:
767   case Sema::TDK_Incomplete:
768   case Sema::TDK_TooManyArguments:
769   case Sema::TDK_TooFewArguments:
770   case Sema::TDK_InvalidExplicitArguments:
771   case Sema::TDK_SubstitutionFailure:
772   case Sema::TDK_CUDATargetMismatch:
773   case Sema::TDK_NonDependentConversionFailure:
774     return nullptr;
775 
776   case Sema::TDK_Inconsistent:
777   case Sema::TDK_Underqualified:
778   case Sema::TDK_DeducedMismatch:
779   case Sema::TDK_DeducedMismatchNested:
780   case Sema::TDK_NonDeducedMismatch:
781     return &static_cast<DFIArguments*>(Data)->FirstArg;
782 
783   // Unhandled
784   case Sema::TDK_MiscellaneousDeductionFailure:
785     break;
786   }
787 
788   return nullptr;
789 }
790 
791 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
792   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793   case Sema::TDK_Success:
794   case Sema::TDK_Invalid:
795   case Sema::TDK_InstantiationDepth:
796   case Sema::TDK_Incomplete:
797   case Sema::TDK_TooManyArguments:
798   case Sema::TDK_TooFewArguments:
799   case Sema::TDK_InvalidExplicitArguments:
800   case Sema::TDK_SubstitutionFailure:
801   case Sema::TDK_CUDATargetMismatch:
802   case Sema::TDK_NonDependentConversionFailure:
803     return nullptr;
804 
805   case Sema::TDK_Inconsistent:
806   case Sema::TDK_Underqualified:
807   case Sema::TDK_DeducedMismatch:
808   case Sema::TDK_DeducedMismatchNested:
809   case Sema::TDK_NonDeducedMismatch:
810     return &static_cast<DFIArguments*>(Data)->SecondArg;
811 
812   // Unhandled
813   case Sema::TDK_MiscellaneousDeductionFailure:
814     break;
815   }
816 
817   return nullptr;
818 }
819 
820 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
821   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822   case Sema::TDK_DeducedMismatch:
823   case Sema::TDK_DeducedMismatchNested:
824     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825 
826   default:
827     return llvm::None;
828   }
829 }
830 
831 void OverloadCandidateSet::destroyCandidates() {
832   for (iterator i = begin(), e = end(); i != e; ++i) {
833     for (auto &C : i->Conversions)
834       C.~ImplicitConversionSequence();
835     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836       i->DeductionFailure.Destroy();
837   }
838 }
839 
840 void OverloadCandidateSet::clear() {
841   destroyCandidates();
842   SlabAllocator.Reset();
843   NumInlineBytesUsed = 0;
844   Candidates.clear();
845   Functions.clear();
846 }
847 
848 namespace {
849   class UnbridgedCastsSet {
850     struct Entry {
851       Expr **Addr;
852       Expr *Saved;
853     };
854     SmallVector<Entry, 2> Entries;
855 
856   public:
857     void save(Sema &S, Expr *&E) {
858       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
859       Entry entry = { &E, E };
860       Entries.push_back(entry);
861       E = S.stripARCUnbridgedCast(E);
862     }
863 
864     void restore() {
865       for (SmallVectorImpl<Entry>::iterator
866              i = Entries.begin(), e = Entries.end(); i != e; ++i)
867         *i->Addr = i->Saved;
868     }
869   };
870 }
871 
872 /// checkPlaceholderForOverload - Do any interesting placeholder-like
873 /// preprocessing on the given expression.
874 ///
875 /// \param unbridgedCasts a collection to which to add unbridged casts;
876 ///   without this, they will be immediately diagnosed as errors
877 ///
878 /// Return true on unrecoverable error.
879 static bool
880 checkPlaceholderForOverload(Sema &S, Expr *&E,
881                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
882   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
883     // We can't handle overloaded expressions here because overload
884     // resolution might reasonably tweak them.
885     if (placeholder->getKind() == BuiltinType::Overload) return false;
886 
887     // If the context potentially accepts unbridged ARC casts, strip
888     // the unbridged cast and add it to the collection for later restoration.
889     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
890         unbridgedCasts) {
891       unbridgedCasts->save(S, E);
892       return false;
893     }
894 
895     // Go ahead and check everything else.
896     ExprResult result = S.CheckPlaceholderExpr(E);
897     if (result.isInvalid())
898       return true;
899 
900     E = result.get();
901     return false;
902   }
903 
904   // Nothing to do.
905   return false;
906 }
907 
908 /// checkArgPlaceholdersForOverload - Check a set of call operands for
909 /// placeholders.
910 static bool checkArgPlaceholdersForOverload(Sema &S,
911                                             MultiExprArg Args,
912                                             UnbridgedCastsSet &unbridged) {
913   for (unsigned i = 0, e = Args.size(); i != e; ++i)
914     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
915       return true;
916 
917   return false;
918 }
919 
920 // IsOverload - Determine whether the given New declaration is an
921 // overload of the declarations in Old. This routine returns false if
922 // New and Old cannot be overloaded, e.g., if New has the same
923 // signature as some function in Old (C++ 1.3.10) or if the Old
924 // declarations aren't functions (or function templates) at all. When
925 // it does return false, MatchedDecl will point to the decl that New
926 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
927 // top of the underlying declaration.
928 //
929 // Example: Given the following input:
930 //
931 //   void f(int, float); // #1
932 //   void f(int, int); // #2
933 //   int f(int, int); // #3
934 //
935 // When we process #1, there is no previous declaration of "f",
936 // so IsOverload will not be used.
937 //
938 // When we process #2, Old contains only the FunctionDecl for #1.  By
939 // comparing the parameter types, we see that #1 and #2 are overloaded
940 // (since they have different signatures), so this routine returns
941 // false; MatchedDecl is unchanged.
942 //
943 // When we process #3, Old is an overload set containing #1 and #2. We
944 // compare the signatures of #3 to #1 (they're overloaded, so we do
945 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
946 // identical (return types of functions are not part of the
947 // signature), IsOverload returns false and MatchedDecl will be set to
948 // point to the FunctionDecl for #2.
949 //
950 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
951 // into a class by a using declaration.  The rules for whether to hide
952 // shadow declarations ignore some properties which otherwise figure
953 // into a function template's signature.
954 Sema::OverloadKind
955 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
956                     NamedDecl *&Match, bool NewIsUsingDecl) {
957   for (LookupResult::iterator I = Old.begin(), E = Old.end();
958          I != E; ++I) {
959     NamedDecl *OldD = *I;
960 
961     bool OldIsUsingDecl = false;
962     if (isa<UsingShadowDecl>(OldD)) {
963       OldIsUsingDecl = true;
964 
965       // We can always introduce two using declarations into the same
966       // context, even if they have identical signatures.
967       if (NewIsUsingDecl) continue;
968 
969       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
970     }
971 
972     // A using-declaration does not conflict with another declaration
973     // if one of them is hidden.
974     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
975       continue;
976 
977     // If either declaration was introduced by a using declaration,
978     // we'll need to use slightly different rules for matching.
979     // Essentially, these rules are the normal rules, except that
980     // function templates hide function templates with different
981     // return types or template parameter lists.
982     bool UseMemberUsingDeclRules =
983       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
984       !New->getFriendObjectKind();
985 
986     if (FunctionDecl *OldF = OldD->getAsFunction()) {
987       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
988         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
989           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
990           continue;
991         }
992 
993         if (!isa<FunctionTemplateDecl>(OldD) &&
994             !shouldLinkPossiblyHiddenDecl(*I, New))
995           continue;
996 
997         Match = *I;
998         return Ovl_Match;
999       }
1000     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1001       // We can overload with these, which can show up when doing
1002       // redeclaration checks for UsingDecls.
1003       assert(Old.getLookupKind() == LookupUsingDeclName);
1004     } else if (isa<TagDecl>(OldD)) {
1005       // We can always overload with tags by hiding them.
1006     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1007       // Optimistically assume that an unresolved using decl will
1008       // overload; if it doesn't, we'll have to diagnose during
1009       // template instantiation.
1010       //
1011       // Exception: if the scope is dependent and this is not a class
1012       // member, the using declaration can only introduce an enumerator.
1013       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1014         Match = *I;
1015         return Ovl_NonFunction;
1016       }
1017     } else {
1018       // (C++ 13p1):
1019       //   Only function declarations can be overloaded; object and type
1020       //   declarations cannot be overloaded.
1021       Match = *I;
1022       return Ovl_NonFunction;
1023     }
1024   }
1025 
1026   return Ovl_Overload;
1027 }
1028 
1029 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1030                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1031   // C++ [basic.start.main]p2: This function shall not be overloaded.
1032   if (New->isMain())
1033     return false;
1034 
1035   // MSVCRT user defined entry points cannot be overloaded.
1036   if (New->isMSVCRTEntryPoint())
1037     return false;
1038 
1039   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1040   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1041 
1042   // C++ [temp.fct]p2:
1043   //   A function template can be overloaded with other function templates
1044   //   and with normal (non-template) functions.
1045   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1046     return true;
1047 
1048   // Is the function New an overload of the function Old?
1049   QualType OldQType = Context.getCanonicalType(Old->getType());
1050   QualType NewQType = Context.getCanonicalType(New->getType());
1051 
1052   // Compare the signatures (C++ 1.3.10) of the two functions to
1053   // determine whether they are overloads. If we find any mismatch
1054   // in the signature, they are overloads.
1055 
1056   // If either of these functions is a K&R-style function (no
1057   // prototype), then we consider them to have matching signatures.
1058   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1059       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1060     return false;
1061 
1062   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1063   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1064 
1065   // The signature of a function includes the types of its
1066   // parameters (C++ 1.3.10), which includes the presence or absence
1067   // of the ellipsis; see C++ DR 357).
1068   if (OldQType != NewQType &&
1069       (OldType->getNumParams() != NewType->getNumParams() ||
1070        OldType->isVariadic() != NewType->isVariadic() ||
1071        !FunctionParamTypesAreEqual(OldType, NewType)))
1072     return true;
1073 
1074   // C++ [temp.over.link]p4:
1075   //   The signature of a function template consists of its function
1076   //   signature, its return type and its template parameter list. The names
1077   //   of the template parameters are significant only for establishing the
1078   //   relationship between the template parameters and the rest of the
1079   //   signature.
1080   //
1081   // We check the return type and template parameter lists for function
1082   // templates first; the remaining checks follow.
1083   //
1084   // However, we don't consider either of these when deciding whether
1085   // a member introduced by a shadow declaration is hidden.
1086   if (!UseMemberUsingDeclRules && NewTemplate &&
1087       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1088                                        OldTemplate->getTemplateParameters(),
1089                                        false, TPL_TemplateMatch) ||
1090        OldType->getReturnType() != NewType->getReturnType()))
1091     return true;
1092 
1093   // If the function is a class member, its signature includes the
1094   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1095   //
1096   // As part of this, also check whether one of the member functions
1097   // is static, in which case they are not overloads (C++
1098   // 13.1p2). While not part of the definition of the signature,
1099   // this check is important to determine whether these functions
1100   // can be overloaded.
1101   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1102   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1103   if (OldMethod && NewMethod &&
1104       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1105     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1106       if (!UseMemberUsingDeclRules &&
1107           (OldMethod->getRefQualifier() == RQ_None ||
1108            NewMethod->getRefQualifier() == RQ_None)) {
1109         // C++0x [over.load]p2:
1110         //   - Member function declarations with the same name and the same
1111         //     parameter-type-list as well as member function template
1112         //     declarations with the same name, the same parameter-type-list, and
1113         //     the same template parameter lists cannot be overloaded if any of
1114         //     them, but not all, have a ref-qualifier (8.3.5).
1115         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1116           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1117         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1118       }
1119       return true;
1120     }
1121 
1122     // We may not have applied the implicit const for a constexpr member
1123     // function yet (because we haven't yet resolved whether this is a static
1124     // or non-static member function). Add it now, on the assumption that this
1125     // is a redeclaration of OldMethod.
1126     unsigned OldQuals = OldMethod->getTypeQualifiers();
1127     unsigned NewQuals = NewMethod->getTypeQualifiers();
1128     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1129         !isa<CXXConstructorDecl>(NewMethod))
1130       NewQuals |= Qualifiers::Const;
1131 
1132     // We do not allow overloading based off of '__restrict'.
1133     OldQuals &= ~Qualifiers::Restrict;
1134     NewQuals &= ~Qualifiers::Restrict;
1135     if (OldQuals != NewQuals)
1136       return true;
1137   }
1138 
1139   // Though pass_object_size is placed on parameters and takes an argument, we
1140   // consider it to be a function-level modifier for the sake of function
1141   // identity. Either the function has one or more parameters with
1142   // pass_object_size or it doesn't.
1143   if (functionHasPassObjectSizeParams(New) !=
1144       functionHasPassObjectSizeParams(Old))
1145     return true;
1146 
1147   // enable_if attributes are an order-sensitive part of the signature.
1148   for (specific_attr_iterator<EnableIfAttr>
1149          NewI = New->specific_attr_begin<EnableIfAttr>(),
1150          NewE = New->specific_attr_end<EnableIfAttr>(),
1151          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1152          OldE = Old->specific_attr_end<EnableIfAttr>();
1153        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1154     if (NewI == NewE || OldI == OldE)
1155       return true;
1156     llvm::FoldingSetNodeID NewID, OldID;
1157     NewI->getCond()->Profile(NewID, Context, true);
1158     OldI->getCond()->Profile(OldID, Context, true);
1159     if (NewID != OldID)
1160       return true;
1161   }
1162 
1163   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1164     // Don't allow overloading of destructors.  (In theory we could, but it
1165     // would be a giant change to clang.)
1166     if (isa<CXXDestructorDecl>(New))
1167       return false;
1168 
1169     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1170                        OldTarget = IdentifyCUDATarget(Old);
1171     if (NewTarget == CFT_InvalidTarget)
1172       return false;
1173 
1174     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1175 
1176     // Allow overloading of functions with same signature and different CUDA
1177     // target attributes.
1178     return NewTarget != OldTarget;
1179   }
1180 
1181   // The signatures match; this is not an overload.
1182   return false;
1183 }
1184 
1185 /// \brief Checks availability of the function depending on the current
1186 /// function context. Inside an unavailable function, unavailability is ignored.
1187 ///
1188 /// \returns true if \arg FD is unavailable and current context is inside
1189 /// an available function, false otherwise.
1190 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1191   if (!FD->isUnavailable())
1192     return false;
1193 
1194   // Walk up the context of the caller.
1195   Decl *C = cast<Decl>(CurContext);
1196   do {
1197     if (C->isUnavailable())
1198       return false;
1199   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1200   return true;
1201 }
1202 
1203 /// \brief Tries a user-defined conversion from From to ToType.
1204 ///
1205 /// Produces an implicit conversion sequence for when a standard conversion
1206 /// is not an option. See TryImplicitConversion for more information.
1207 static ImplicitConversionSequence
1208 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1209                          bool SuppressUserConversions,
1210                          bool AllowExplicit,
1211                          bool InOverloadResolution,
1212                          bool CStyle,
1213                          bool AllowObjCWritebackConversion,
1214                          bool AllowObjCConversionOnExplicit) {
1215   ImplicitConversionSequence ICS;
1216 
1217   if (SuppressUserConversions) {
1218     // We're not in the case above, so there is no conversion that
1219     // we can perform.
1220     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1221     return ICS;
1222   }
1223 
1224   // Attempt user-defined conversion.
1225   OverloadCandidateSet Conversions(From->getExprLoc(),
1226                                    OverloadCandidateSet::CSK_Normal);
1227   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1228                                   Conversions, AllowExplicit,
1229                                   AllowObjCConversionOnExplicit)) {
1230   case OR_Success:
1231   case OR_Deleted:
1232     ICS.setUserDefined();
1233     // C++ [over.ics.user]p4:
1234     //   A conversion of an expression of class type to the same class
1235     //   type is given Exact Match rank, and a conversion of an
1236     //   expression of class type to a base class of that type is
1237     //   given Conversion rank, in spite of the fact that a copy
1238     //   constructor (i.e., a user-defined conversion function) is
1239     //   called for those cases.
1240     if (CXXConstructorDecl *Constructor
1241           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1242       QualType FromCanon
1243         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1244       QualType ToCanon
1245         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1246       if (Constructor->isCopyConstructor() &&
1247           (FromCanon == ToCanon ||
1248            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1249         // Turn this into a "standard" conversion sequence, so that it
1250         // gets ranked with standard conversion sequences.
1251         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1252         ICS.setStandard();
1253         ICS.Standard.setAsIdentityConversion();
1254         ICS.Standard.setFromType(From->getType());
1255         ICS.Standard.setAllToTypes(ToType);
1256         ICS.Standard.CopyConstructor = Constructor;
1257         ICS.Standard.FoundCopyConstructor = Found;
1258         if (ToCanon != FromCanon)
1259           ICS.Standard.Second = ICK_Derived_To_Base;
1260       }
1261     }
1262     break;
1263 
1264   case OR_Ambiguous:
1265     ICS.setAmbiguous();
1266     ICS.Ambiguous.setFromType(From->getType());
1267     ICS.Ambiguous.setToType(ToType);
1268     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1269          Cand != Conversions.end(); ++Cand)
1270       if (Cand->Viable)
1271         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1272     break;
1273 
1274     // Fall through.
1275   case OR_No_Viable_Function:
1276     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1277     break;
1278   }
1279 
1280   return ICS;
1281 }
1282 
1283 /// TryImplicitConversion - Attempt to perform an implicit conversion
1284 /// from the given expression (Expr) to the given type (ToType). This
1285 /// function returns an implicit conversion sequence that can be used
1286 /// to perform the initialization. Given
1287 ///
1288 ///   void f(float f);
1289 ///   void g(int i) { f(i); }
1290 ///
1291 /// this routine would produce an implicit conversion sequence to
1292 /// describe the initialization of f from i, which will be a standard
1293 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1294 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1295 //
1296 /// Note that this routine only determines how the conversion can be
1297 /// performed; it does not actually perform the conversion. As such,
1298 /// it will not produce any diagnostics if no conversion is available,
1299 /// but will instead return an implicit conversion sequence of kind
1300 /// "BadConversion".
1301 ///
1302 /// If @p SuppressUserConversions, then user-defined conversions are
1303 /// not permitted.
1304 /// If @p AllowExplicit, then explicit user-defined conversions are
1305 /// permitted.
1306 ///
1307 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1308 /// writeback conversion, which allows __autoreleasing id* parameters to
1309 /// be initialized with __strong id* or __weak id* arguments.
1310 static ImplicitConversionSequence
1311 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1312                       bool SuppressUserConversions,
1313                       bool AllowExplicit,
1314                       bool InOverloadResolution,
1315                       bool CStyle,
1316                       bool AllowObjCWritebackConversion,
1317                       bool AllowObjCConversionOnExplicit) {
1318   ImplicitConversionSequence ICS;
1319   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1320                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1321     ICS.setStandard();
1322     return ICS;
1323   }
1324 
1325   if (!S.getLangOpts().CPlusPlus) {
1326     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1327     return ICS;
1328   }
1329 
1330   // C++ [over.ics.user]p4:
1331   //   A conversion of an expression of class type to the same class
1332   //   type is given Exact Match rank, and a conversion of an
1333   //   expression of class type to a base class of that type is
1334   //   given Conversion rank, in spite of the fact that a copy/move
1335   //   constructor (i.e., a user-defined conversion function) is
1336   //   called for those cases.
1337   QualType FromType = From->getType();
1338   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1339       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1340        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1341     ICS.setStandard();
1342     ICS.Standard.setAsIdentityConversion();
1343     ICS.Standard.setFromType(FromType);
1344     ICS.Standard.setAllToTypes(ToType);
1345 
1346     // We don't actually check at this point whether there is a valid
1347     // copy/move constructor, since overloading just assumes that it
1348     // exists. When we actually perform initialization, we'll find the
1349     // appropriate constructor to copy the returned object, if needed.
1350     ICS.Standard.CopyConstructor = nullptr;
1351 
1352     // Determine whether this is considered a derived-to-base conversion.
1353     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1354       ICS.Standard.Second = ICK_Derived_To_Base;
1355 
1356     return ICS;
1357   }
1358 
1359   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1360                                   AllowExplicit, InOverloadResolution, CStyle,
1361                                   AllowObjCWritebackConversion,
1362                                   AllowObjCConversionOnExplicit);
1363 }
1364 
1365 ImplicitConversionSequence
1366 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1367                             bool SuppressUserConversions,
1368                             bool AllowExplicit,
1369                             bool InOverloadResolution,
1370                             bool CStyle,
1371                             bool AllowObjCWritebackConversion) {
1372   return ::TryImplicitConversion(*this, From, ToType,
1373                                  SuppressUserConversions, AllowExplicit,
1374                                  InOverloadResolution, CStyle,
1375                                  AllowObjCWritebackConversion,
1376                                  /*AllowObjCConversionOnExplicit=*/false);
1377 }
1378 
1379 /// PerformImplicitConversion - Perform an implicit conversion of the
1380 /// expression From to the type ToType. Returns the
1381 /// converted expression. Flavor is the kind of conversion we're
1382 /// performing, used in the error message. If @p AllowExplicit,
1383 /// explicit user-defined conversions are permitted.
1384 ExprResult
1385 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1386                                 AssignmentAction Action, bool AllowExplicit) {
1387   ImplicitConversionSequence ICS;
1388   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1389 }
1390 
1391 ExprResult
1392 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1393                                 AssignmentAction Action, bool AllowExplicit,
1394                                 ImplicitConversionSequence& ICS) {
1395   if (checkPlaceholderForOverload(*this, From))
1396     return ExprError();
1397 
1398   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1399   bool AllowObjCWritebackConversion
1400     = getLangOpts().ObjCAutoRefCount &&
1401       (Action == AA_Passing || Action == AA_Sending);
1402   if (getLangOpts().ObjC1)
1403     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1404                                       ToType, From->getType(), From);
1405   ICS = ::TryImplicitConversion(*this, From, ToType,
1406                                 /*SuppressUserConversions=*/false,
1407                                 AllowExplicit,
1408                                 /*InOverloadResolution=*/false,
1409                                 /*CStyle=*/false,
1410                                 AllowObjCWritebackConversion,
1411                                 /*AllowObjCConversionOnExplicit=*/false);
1412   return PerformImplicitConversion(From, ToType, ICS, Action);
1413 }
1414 
1415 /// \brief Determine whether the conversion from FromType to ToType is a valid
1416 /// conversion that strips "noexcept" or "noreturn" off the nested function
1417 /// type.
1418 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1419                                 QualType &ResultTy) {
1420   if (Context.hasSameUnqualifiedType(FromType, ToType))
1421     return false;
1422 
1423   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1424   //                    or F(t noexcept) -> F(t)
1425   // where F adds one of the following at most once:
1426   //   - a pointer
1427   //   - a member pointer
1428   //   - a block pointer
1429   // Changes here need matching changes in FindCompositePointerType.
1430   CanQualType CanTo = Context.getCanonicalType(ToType);
1431   CanQualType CanFrom = Context.getCanonicalType(FromType);
1432   Type::TypeClass TyClass = CanTo->getTypeClass();
1433   if (TyClass != CanFrom->getTypeClass()) return false;
1434   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1435     if (TyClass == Type::Pointer) {
1436       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1437       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1438     } else if (TyClass == Type::BlockPointer) {
1439       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1440       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1441     } else if (TyClass == Type::MemberPointer) {
1442       auto ToMPT = CanTo.getAs<MemberPointerType>();
1443       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1444       // A function pointer conversion cannot change the class of the function.
1445       if (ToMPT->getClass() != FromMPT->getClass())
1446         return false;
1447       CanTo = ToMPT->getPointeeType();
1448       CanFrom = FromMPT->getPointeeType();
1449     } else {
1450       return false;
1451     }
1452 
1453     TyClass = CanTo->getTypeClass();
1454     if (TyClass != CanFrom->getTypeClass()) return false;
1455     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1456       return false;
1457   }
1458 
1459   const auto *FromFn = cast<FunctionType>(CanFrom);
1460   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1461 
1462   const auto *ToFn = cast<FunctionType>(CanTo);
1463   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1464 
1465   bool Changed = false;
1466 
1467   // Drop 'noreturn' if not present in target type.
1468   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1469     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1470     Changed = true;
1471   }
1472 
1473   // Drop 'noexcept' if not present in target type.
1474   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1475     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1476     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1477       FromFn = cast<FunctionType>(
1478           Context.getFunctionType(FromFPT->getReturnType(),
1479                                   FromFPT->getParamTypes(),
1480                                   FromFPT->getExtProtoInfo().withExceptionSpec(
1481                                       FunctionProtoType::ExceptionSpecInfo()))
1482                  .getTypePtr());
1483       Changed = true;
1484     }
1485   }
1486 
1487   if (!Changed)
1488     return false;
1489 
1490   assert(QualType(FromFn, 0).isCanonical());
1491   if (QualType(FromFn, 0) != CanTo) return false;
1492 
1493   ResultTy = ToType;
1494   return true;
1495 }
1496 
1497 /// \brief Determine whether the conversion from FromType to ToType is a valid
1498 /// vector conversion.
1499 ///
1500 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1501 /// conversion.
1502 static bool IsVectorConversion(Sema &S, QualType FromType,
1503                                QualType ToType, ImplicitConversionKind &ICK) {
1504   // We need at least one of these types to be a vector type to have a vector
1505   // conversion.
1506   if (!ToType->isVectorType() && !FromType->isVectorType())
1507     return false;
1508 
1509   // Identical types require no conversions.
1510   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1511     return false;
1512 
1513   // There are no conversions between extended vector types, only identity.
1514   if (ToType->isExtVectorType()) {
1515     // There are no conversions between extended vector types other than the
1516     // identity conversion.
1517     if (FromType->isExtVectorType())
1518       return false;
1519 
1520     // Vector splat from any arithmetic type to a vector.
1521     if (FromType->isArithmeticType()) {
1522       ICK = ICK_Vector_Splat;
1523       return true;
1524     }
1525   }
1526 
1527   // We can perform the conversion between vector types in the following cases:
1528   // 1)vector types are equivalent AltiVec and GCC vector types
1529   // 2)lax vector conversions are permitted and the vector types are of the
1530   //   same size
1531   if (ToType->isVectorType() && FromType->isVectorType()) {
1532     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1533         S.isLaxVectorConversion(FromType, ToType)) {
1534       ICK = ICK_Vector_Conversion;
1535       return true;
1536     }
1537   }
1538 
1539   return false;
1540 }
1541 
1542 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1543                                 bool InOverloadResolution,
1544                                 StandardConversionSequence &SCS,
1545                                 bool CStyle);
1546 
1547 /// IsStandardConversion - Determines whether there is a standard
1548 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1549 /// expression From to the type ToType. Standard conversion sequences
1550 /// only consider non-class types; for conversions that involve class
1551 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1552 /// contain the standard conversion sequence required to perform this
1553 /// conversion and this routine will return true. Otherwise, this
1554 /// routine will return false and the value of SCS is unspecified.
1555 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1556                                  bool InOverloadResolution,
1557                                  StandardConversionSequence &SCS,
1558                                  bool CStyle,
1559                                  bool AllowObjCWritebackConversion) {
1560   QualType FromType = From->getType();
1561 
1562   // Standard conversions (C++ [conv])
1563   SCS.setAsIdentityConversion();
1564   SCS.IncompatibleObjC = false;
1565   SCS.setFromType(FromType);
1566   SCS.CopyConstructor = nullptr;
1567 
1568   // There are no standard conversions for class types in C++, so
1569   // abort early. When overloading in C, however, we do permit them.
1570   if (S.getLangOpts().CPlusPlus &&
1571       (FromType->isRecordType() || ToType->isRecordType()))
1572     return false;
1573 
1574   // The first conversion can be an lvalue-to-rvalue conversion,
1575   // array-to-pointer conversion, or function-to-pointer conversion
1576   // (C++ 4p1).
1577 
1578   if (FromType == S.Context.OverloadTy) {
1579     DeclAccessPair AccessPair;
1580     if (FunctionDecl *Fn
1581           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1582                                                  AccessPair)) {
1583       // We were able to resolve the address of the overloaded function,
1584       // so we can convert to the type of that function.
1585       FromType = Fn->getType();
1586       SCS.setFromType(FromType);
1587 
1588       // we can sometimes resolve &foo<int> regardless of ToType, so check
1589       // if the type matches (identity) or we are converting to bool
1590       if (!S.Context.hasSameUnqualifiedType(
1591                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1592         QualType resultTy;
1593         // if the function type matches except for [[noreturn]], it's ok
1594         if (!S.IsFunctionConversion(FromType,
1595               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1596           // otherwise, only a boolean conversion is standard
1597           if (!ToType->isBooleanType())
1598             return false;
1599       }
1600 
1601       // Check if the "from" expression is taking the address of an overloaded
1602       // function and recompute the FromType accordingly. Take advantage of the
1603       // fact that non-static member functions *must* have such an address-of
1604       // expression.
1605       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1606       if (Method && !Method->isStatic()) {
1607         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1608                "Non-unary operator on non-static member address");
1609         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1610                == UO_AddrOf &&
1611                "Non-address-of operator on non-static member address");
1612         const Type *ClassType
1613           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1614         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1615       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1616         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1617                UO_AddrOf &&
1618                "Non-address-of operator for overloaded function expression");
1619         FromType = S.Context.getPointerType(FromType);
1620       }
1621 
1622       // Check that we've computed the proper type after overload resolution.
1623       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1624       // be calling it from within an NDEBUG block.
1625       assert(S.Context.hasSameType(
1626         FromType,
1627         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1628     } else {
1629       return false;
1630     }
1631   }
1632   // Lvalue-to-rvalue conversion (C++11 4.1):
1633   //   A glvalue (3.10) of a non-function, non-array type T can
1634   //   be converted to a prvalue.
1635   bool argIsLValue = From->isGLValue();
1636   if (argIsLValue &&
1637       !FromType->isFunctionType() && !FromType->isArrayType() &&
1638       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1639     SCS.First = ICK_Lvalue_To_Rvalue;
1640 
1641     // C11 6.3.2.1p2:
1642     //   ... if the lvalue has atomic type, the value has the non-atomic version
1643     //   of the type of the lvalue ...
1644     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1645       FromType = Atomic->getValueType();
1646 
1647     // If T is a non-class type, the type of the rvalue is the
1648     // cv-unqualified version of T. Otherwise, the type of the rvalue
1649     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1650     // just strip the qualifiers because they don't matter.
1651     FromType = FromType.getUnqualifiedType();
1652   } else if (FromType->isArrayType()) {
1653     // Array-to-pointer conversion (C++ 4.2)
1654     SCS.First = ICK_Array_To_Pointer;
1655 
1656     // An lvalue or rvalue of type "array of N T" or "array of unknown
1657     // bound of T" can be converted to an rvalue of type "pointer to
1658     // T" (C++ 4.2p1).
1659     FromType = S.Context.getArrayDecayedType(FromType);
1660 
1661     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1662       // This conversion is deprecated in C++03 (D.4)
1663       SCS.DeprecatedStringLiteralToCharPtr = true;
1664 
1665       // For the purpose of ranking in overload resolution
1666       // (13.3.3.1.1), this conversion is considered an
1667       // array-to-pointer conversion followed by a qualification
1668       // conversion (4.4). (C++ 4.2p2)
1669       SCS.Second = ICK_Identity;
1670       SCS.Third = ICK_Qualification;
1671       SCS.QualificationIncludesObjCLifetime = false;
1672       SCS.setAllToTypes(FromType);
1673       return true;
1674     }
1675   } else if (FromType->isFunctionType() && argIsLValue) {
1676     // Function-to-pointer conversion (C++ 4.3).
1677     SCS.First = ICK_Function_To_Pointer;
1678 
1679     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1680       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1681         if (!S.checkAddressOfFunctionIsAvailable(FD))
1682           return false;
1683 
1684     // An lvalue of function type T can be converted to an rvalue of
1685     // type "pointer to T." The result is a pointer to the
1686     // function. (C++ 4.3p1).
1687     FromType = S.Context.getPointerType(FromType);
1688   } else {
1689     // We don't require any conversions for the first step.
1690     SCS.First = ICK_Identity;
1691   }
1692   SCS.setToType(0, FromType);
1693 
1694   // The second conversion can be an integral promotion, floating
1695   // point promotion, integral conversion, floating point conversion,
1696   // floating-integral conversion, pointer conversion,
1697   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1698   // For overloading in C, this can also be a "compatible-type"
1699   // conversion.
1700   bool IncompatibleObjC = false;
1701   ImplicitConversionKind SecondICK = ICK_Identity;
1702   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1703     // The unqualified versions of the types are the same: there's no
1704     // conversion to do.
1705     SCS.Second = ICK_Identity;
1706   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1707     // Integral promotion (C++ 4.5).
1708     SCS.Second = ICK_Integral_Promotion;
1709     FromType = ToType.getUnqualifiedType();
1710   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1711     // Floating point promotion (C++ 4.6).
1712     SCS.Second = ICK_Floating_Promotion;
1713     FromType = ToType.getUnqualifiedType();
1714   } else if (S.IsComplexPromotion(FromType, ToType)) {
1715     // Complex promotion (Clang extension)
1716     SCS.Second = ICK_Complex_Promotion;
1717     FromType = ToType.getUnqualifiedType();
1718   } else if (ToType->isBooleanType() &&
1719              (FromType->isArithmeticType() ||
1720               FromType->isAnyPointerType() ||
1721               FromType->isBlockPointerType() ||
1722               FromType->isMemberPointerType() ||
1723               FromType->isNullPtrType())) {
1724     // Boolean conversions (C++ 4.12).
1725     SCS.Second = ICK_Boolean_Conversion;
1726     FromType = S.Context.BoolTy;
1727   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1728              ToType->isIntegralType(S.Context)) {
1729     // Integral conversions (C++ 4.7).
1730     SCS.Second = ICK_Integral_Conversion;
1731     FromType = ToType.getUnqualifiedType();
1732   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1733     // Complex conversions (C99 6.3.1.6)
1734     SCS.Second = ICK_Complex_Conversion;
1735     FromType = ToType.getUnqualifiedType();
1736   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1737              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1738     // Complex-real conversions (C99 6.3.1.7)
1739     SCS.Second = ICK_Complex_Real;
1740     FromType = ToType.getUnqualifiedType();
1741   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1742     // FIXME: disable conversions between long double and __float128 if
1743     // their representation is different until there is back end support
1744     // We of course allow this conversion if long double is really double.
1745     if (&S.Context.getFloatTypeSemantics(FromType) !=
1746         &S.Context.getFloatTypeSemantics(ToType)) {
1747       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1748                                     ToType == S.Context.LongDoubleTy) ||
1749                                    (FromType == S.Context.LongDoubleTy &&
1750                                     ToType == S.Context.Float128Ty));
1751       if (Float128AndLongDouble &&
1752           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1753            &llvm::APFloat::IEEEdouble()))
1754         return false;
1755     }
1756     // Floating point conversions (C++ 4.8).
1757     SCS.Second = ICK_Floating_Conversion;
1758     FromType = ToType.getUnqualifiedType();
1759   } else if ((FromType->isRealFloatingType() &&
1760               ToType->isIntegralType(S.Context)) ||
1761              (FromType->isIntegralOrUnscopedEnumerationType() &&
1762               ToType->isRealFloatingType())) {
1763     // Floating-integral conversions (C++ 4.9).
1764     SCS.Second = ICK_Floating_Integral;
1765     FromType = ToType.getUnqualifiedType();
1766   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1767     SCS.Second = ICK_Block_Pointer_Conversion;
1768   } else if (AllowObjCWritebackConversion &&
1769              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1770     SCS.Second = ICK_Writeback_Conversion;
1771   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1772                                    FromType, IncompatibleObjC)) {
1773     // Pointer conversions (C++ 4.10).
1774     SCS.Second = ICK_Pointer_Conversion;
1775     SCS.IncompatibleObjC = IncompatibleObjC;
1776     FromType = FromType.getUnqualifiedType();
1777   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1778                                          InOverloadResolution, FromType)) {
1779     // Pointer to member conversions (4.11).
1780     SCS.Second = ICK_Pointer_Member;
1781   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1782     SCS.Second = SecondICK;
1783     FromType = ToType.getUnqualifiedType();
1784   } else if (!S.getLangOpts().CPlusPlus &&
1785              S.Context.typesAreCompatible(ToType, FromType)) {
1786     // Compatible conversions (Clang extension for C function overloading)
1787     SCS.Second = ICK_Compatible_Conversion;
1788     FromType = ToType.getUnqualifiedType();
1789   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1790                                              InOverloadResolution,
1791                                              SCS, CStyle)) {
1792     SCS.Second = ICK_TransparentUnionConversion;
1793     FromType = ToType;
1794   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1795                                  CStyle)) {
1796     // tryAtomicConversion has updated the standard conversion sequence
1797     // appropriately.
1798     return true;
1799   } else if (ToType->isEventT() &&
1800              From->isIntegerConstantExpr(S.getASTContext()) &&
1801              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1802     SCS.Second = ICK_Zero_Event_Conversion;
1803     FromType = ToType;
1804   } else if (ToType->isQueueT() &&
1805              From->isIntegerConstantExpr(S.getASTContext()) &&
1806              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1807     SCS.Second = ICK_Zero_Queue_Conversion;
1808     FromType = ToType;
1809   } else {
1810     // No second conversion required.
1811     SCS.Second = ICK_Identity;
1812   }
1813   SCS.setToType(1, FromType);
1814 
1815   // The third conversion can be a function pointer conversion or a
1816   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1817   bool ObjCLifetimeConversion;
1818   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1819     // Function pointer conversions (removing 'noexcept') including removal of
1820     // 'noreturn' (Clang extension).
1821     SCS.Third = ICK_Function_Conversion;
1822   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1823                                          ObjCLifetimeConversion)) {
1824     SCS.Third = ICK_Qualification;
1825     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1826     FromType = ToType;
1827   } else {
1828     // No conversion required
1829     SCS.Third = ICK_Identity;
1830   }
1831 
1832   // C++ [over.best.ics]p6:
1833   //   [...] Any difference in top-level cv-qualification is
1834   //   subsumed by the initialization itself and does not constitute
1835   //   a conversion. [...]
1836   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1837   QualType CanonTo = S.Context.getCanonicalType(ToType);
1838   if (CanonFrom.getLocalUnqualifiedType()
1839                                      == CanonTo.getLocalUnqualifiedType() &&
1840       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1841     FromType = ToType;
1842     CanonFrom = CanonTo;
1843   }
1844 
1845   SCS.setToType(2, FromType);
1846 
1847   if (CanonFrom == CanonTo)
1848     return true;
1849 
1850   // If we have not converted the argument type to the parameter type,
1851   // this is a bad conversion sequence, unless we're resolving an overload in C.
1852   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1853     return false;
1854 
1855   ExprResult ER = ExprResult{From};
1856   Sema::AssignConvertType Conv =
1857       S.CheckSingleAssignmentConstraints(ToType, ER,
1858                                          /*Diagnose=*/false,
1859                                          /*DiagnoseCFAudited=*/false,
1860                                          /*ConvertRHS=*/false);
1861   ImplicitConversionKind SecondConv;
1862   switch (Conv) {
1863   case Sema::Compatible:
1864     SecondConv = ICK_C_Only_Conversion;
1865     break;
1866   // For our purposes, discarding qualifiers is just as bad as using an
1867   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1868   // qualifiers, as well.
1869   case Sema::CompatiblePointerDiscardsQualifiers:
1870   case Sema::IncompatiblePointer:
1871   case Sema::IncompatiblePointerSign:
1872     SecondConv = ICK_Incompatible_Pointer_Conversion;
1873     break;
1874   default:
1875     return false;
1876   }
1877 
1878   // First can only be an lvalue conversion, so we pretend that this was the
1879   // second conversion. First should already be valid from earlier in the
1880   // function.
1881   SCS.Second = SecondConv;
1882   SCS.setToType(1, ToType);
1883 
1884   // Third is Identity, because Second should rank us worse than any other
1885   // conversion. This could also be ICK_Qualification, but it's simpler to just
1886   // lump everything in with the second conversion, and we don't gain anything
1887   // from making this ICK_Qualification.
1888   SCS.Third = ICK_Identity;
1889   SCS.setToType(2, ToType);
1890   return true;
1891 }
1892 
1893 static bool
1894 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1895                                      QualType &ToType,
1896                                      bool InOverloadResolution,
1897                                      StandardConversionSequence &SCS,
1898                                      bool CStyle) {
1899 
1900   const RecordType *UT = ToType->getAsUnionType();
1901   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1902     return false;
1903   // The field to initialize within the transparent union.
1904   RecordDecl *UD = UT->getDecl();
1905   // It's compatible if the expression matches any of the fields.
1906   for (const auto *it : UD->fields()) {
1907     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1908                              CStyle, /*ObjCWritebackConversion=*/false)) {
1909       ToType = it->getType();
1910       return true;
1911     }
1912   }
1913   return false;
1914 }
1915 
1916 /// IsIntegralPromotion - Determines whether the conversion from the
1917 /// expression From (whose potentially-adjusted type is FromType) to
1918 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1919 /// sets PromotedType to the promoted type.
1920 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1921   const BuiltinType *To = ToType->getAs<BuiltinType>();
1922   // All integers are built-in.
1923   if (!To) {
1924     return false;
1925   }
1926 
1927   // An rvalue of type char, signed char, unsigned char, short int, or
1928   // unsigned short int can be converted to an rvalue of type int if
1929   // int can represent all the values of the source type; otherwise,
1930   // the source rvalue can be converted to an rvalue of type unsigned
1931   // int (C++ 4.5p1).
1932   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1933       !FromType->isEnumeralType()) {
1934     if (// We can promote any signed, promotable integer type to an int
1935         (FromType->isSignedIntegerType() ||
1936          // We can promote any unsigned integer type whose size is
1937          // less than int to an int.
1938          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1939       return To->getKind() == BuiltinType::Int;
1940     }
1941 
1942     return To->getKind() == BuiltinType::UInt;
1943   }
1944 
1945   // C++11 [conv.prom]p3:
1946   //   A prvalue of an unscoped enumeration type whose underlying type is not
1947   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1948   //   following types that can represent all the values of the enumeration
1949   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1950   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1951   //   long long int. If none of the types in that list can represent all the
1952   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1953   //   type can be converted to an rvalue a prvalue of the extended integer type
1954   //   with lowest integer conversion rank (4.13) greater than the rank of long
1955   //   long in which all the values of the enumeration can be represented. If
1956   //   there are two such extended types, the signed one is chosen.
1957   // C++11 [conv.prom]p4:
1958   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1959   //   can be converted to a prvalue of its underlying type. Moreover, if
1960   //   integral promotion can be applied to its underlying type, a prvalue of an
1961   //   unscoped enumeration type whose underlying type is fixed can also be
1962   //   converted to a prvalue of the promoted underlying type.
1963   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1964     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1965     // provided for a scoped enumeration.
1966     if (FromEnumType->getDecl()->isScoped())
1967       return false;
1968 
1969     // We can perform an integral promotion to the underlying type of the enum,
1970     // even if that's not the promoted type. Note that the check for promoting
1971     // the underlying type is based on the type alone, and does not consider
1972     // the bitfield-ness of the actual source expression.
1973     if (FromEnumType->getDecl()->isFixed()) {
1974       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1975       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1976              IsIntegralPromotion(nullptr, Underlying, ToType);
1977     }
1978 
1979     // We have already pre-calculated the promotion type, so this is trivial.
1980     if (ToType->isIntegerType() &&
1981         isCompleteType(From->getLocStart(), FromType))
1982       return Context.hasSameUnqualifiedType(
1983           ToType, FromEnumType->getDecl()->getPromotionType());
1984   }
1985 
1986   // C++0x [conv.prom]p2:
1987   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1988   //   to an rvalue a prvalue of the first of the following types that can
1989   //   represent all the values of its underlying type: int, unsigned int,
1990   //   long int, unsigned long int, long long int, or unsigned long long int.
1991   //   If none of the types in that list can represent all the values of its
1992   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1993   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1994   //   type.
1995   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1996       ToType->isIntegerType()) {
1997     // Determine whether the type we're converting from is signed or
1998     // unsigned.
1999     bool FromIsSigned = FromType->isSignedIntegerType();
2000     uint64_t FromSize = Context.getTypeSize(FromType);
2001 
2002     // The types we'll try to promote to, in the appropriate
2003     // order. Try each of these types.
2004     QualType PromoteTypes[6] = {
2005       Context.IntTy, Context.UnsignedIntTy,
2006       Context.LongTy, Context.UnsignedLongTy ,
2007       Context.LongLongTy, Context.UnsignedLongLongTy
2008     };
2009     for (int Idx = 0; Idx < 6; ++Idx) {
2010       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2011       if (FromSize < ToSize ||
2012           (FromSize == ToSize &&
2013            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2014         // We found the type that we can promote to. If this is the
2015         // type we wanted, we have a promotion. Otherwise, no
2016         // promotion.
2017         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2018       }
2019     }
2020   }
2021 
2022   // An rvalue for an integral bit-field (9.6) can be converted to an
2023   // rvalue of type int if int can represent all the values of the
2024   // bit-field; otherwise, it can be converted to unsigned int if
2025   // unsigned int can represent all the values of the bit-field. If
2026   // the bit-field is larger yet, no integral promotion applies to
2027   // it. If the bit-field has an enumerated type, it is treated as any
2028   // other value of that type for promotion purposes (C++ 4.5p3).
2029   // FIXME: We should delay checking of bit-fields until we actually perform the
2030   // conversion.
2031   if (From) {
2032     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2033       llvm::APSInt BitWidth;
2034       if (FromType->isIntegralType(Context) &&
2035           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2036         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2037         ToSize = Context.getTypeSize(ToType);
2038 
2039         // Are we promoting to an int from a bitfield that fits in an int?
2040         if (BitWidth < ToSize ||
2041             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2042           return To->getKind() == BuiltinType::Int;
2043         }
2044 
2045         // Are we promoting to an unsigned int from an unsigned bitfield
2046         // that fits into an unsigned int?
2047         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2048           return To->getKind() == BuiltinType::UInt;
2049         }
2050 
2051         return false;
2052       }
2053     }
2054   }
2055 
2056   // An rvalue of type bool can be converted to an rvalue of type int,
2057   // with false becoming zero and true becoming one (C++ 4.5p4).
2058   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2059     return true;
2060   }
2061 
2062   return false;
2063 }
2064 
2065 /// IsFloatingPointPromotion - Determines whether the conversion from
2066 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2067 /// returns true and sets PromotedType to the promoted type.
2068 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2069   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2070     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2071       /// An rvalue of type float can be converted to an rvalue of type
2072       /// double. (C++ 4.6p1).
2073       if (FromBuiltin->getKind() == BuiltinType::Float &&
2074           ToBuiltin->getKind() == BuiltinType::Double)
2075         return true;
2076 
2077       // C99 6.3.1.5p1:
2078       //   When a float is promoted to double or long double, or a
2079       //   double is promoted to long double [...].
2080       if (!getLangOpts().CPlusPlus &&
2081           (FromBuiltin->getKind() == BuiltinType::Float ||
2082            FromBuiltin->getKind() == BuiltinType::Double) &&
2083           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2084            ToBuiltin->getKind() == BuiltinType::Float128))
2085         return true;
2086 
2087       // Half can be promoted to float.
2088       if (!getLangOpts().NativeHalfType &&
2089            FromBuiltin->getKind() == BuiltinType::Half &&
2090           ToBuiltin->getKind() == BuiltinType::Float)
2091         return true;
2092     }
2093 
2094   return false;
2095 }
2096 
2097 /// \brief Determine if a conversion is a complex promotion.
2098 ///
2099 /// A complex promotion is defined as a complex -> complex conversion
2100 /// where the conversion between the underlying real types is a
2101 /// floating-point or integral promotion.
2102 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2103   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2104   if (!FromComplex)
2105     return false;
2106 
2107   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2108   if (!ToComplex)
2109     return false;
2110 
2111   return IsFloatingPointPromotion(FromComplex->getElementType(),
2112                                   ToComplex->getElementType()) ||
2113     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2114                         ToComplex->getElementType());
2115 }
2116 
2117 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2118 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2119 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2120 /// if non-empty, will be a pointer to ToType that may or may not have
2121 /// the right set of qualifiers on its pointee.
2122 ///
2123 static QualType
2124 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2125                                    QualType ToPointee, QualType ToType,
2126                                    ASTContext &Context,
2127                                    bool StripObjCLifetime = false) {
2128   assert((FromPtr->getTypeClass() == Type::Pointer ||
2129           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2130          "Invalid similarly-qualified pointer type");
2131 
2132   /// Conversions to 'id' subsume cv-qualifier conversions.
2133   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2134     return ToType.getUnqualifiedType();
2135 
2136   QualType CanonFromPointee
2137     = Context.getCanonicalType(FromPtr->getPointeeType());
2138   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2139   Qualifiers Quals = CanonFromPointee.getQualifiers();
2140 
2141   if (StripObjCLifetime)
2142     Quals.removeObjCLifetime();
2143 
2144   // Exact qualifier match -> return the pointer type we're converting to.
2145   if (CanonToPointee.getLocalQualifiers() == Quals) {
2146     // ToType is exactly what we need. Return it.
2147     if (!ToType.isNull())
2148       return ToType.getUnqualifiedType();
2149 
2150     // Build a pointer to ToPointee. It has the right qualifiers
2151     // already.
2152     if (isa<ObjCObjectPointerType>(ToType))
2153       return Context.getObjCObjectPointerType(ToPointee);
2154     return Context.getPointerType(ToPointee);
2155   }
2156 
2157   // Just build a canonical type that has the right qualifiers.
2158   QualType QualifiedCanonToPointee
2159     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2160 
2161   if (isa<ObjCObjectPointerType>(ToType))
2162     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2163   return Context.getPointerType(QualifiedCanonToPointee);
2164 }
2165 
2166 static bool isNullPointerConstantForConversion(Expr *Expr,
2167                                                bool InOverloadResolution,
2168                                                ASTContext &Context) {
2169   // Handle value-dependent integral null pointer constants correctly.
2170   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2171   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2172       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2173     return !InOverloadResolution;
2174 
2175   return Expr->isNullPointerConstant(Context,
2176                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2177                                         : Expr::NPC_ValueDependentIsNull);
2178 }
2179 
2180 /// IsPointerConversion - Determines whether the conversion of the
2181 /// expression From, which has the (possibly adjusted) type FromType,
2182 /// can be converted to the type ToType via a pointer conversion (C++
2183 /// 4.10). If so, returns true and places the converted type (that
2184 /// might differ from ToType in its cv-qualifiers at some level) into
2185 /// ConvertedType.
2186 ///
2187 /// This routine also supports conversions to and from block pointers
2188 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2189 /// pointers to interfaces. FIXME: Once we've determined the
2190 /// appropriate overloading rules for Objective-C, we may want to
2191 /// split the Objective-C checks into a different routine; however,
2192 /// GCC seems to consider all of these conversions to be pointer
2193 /// conversions, so for now they live here. IncompatibleObjC will be
2194 /// set if the conversion is an allowed Objective-C conversion that
2195 /// should result in a warning.
2196 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2197                                bool InOverloadResolution,
2198                                QualType& ConvertedType,
2199                                bool &IncompatibleObjC) {
2200   IncompatibleObjC = false;
2201   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2202                               IncompatibleObjC))
2203     return true;
2204 
2205   // Conversion from a null pointer constant to any Objective-C pointer type.
2206   if (ToType->isObjCObjectPointerType() &&
2207       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2208     ConvertedType = ToType;
2209     return true;
2210   }
2211 
2212   // Blocks: Block pointers can be converted to void*.
2213   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2214       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2215     ConvertedType = ToType;
2216     return true;
2217   }
2218   // Blocks: A null pointer constant can be converted to a block
2219   // pointer type.
2220   if (ToType->isBlockPointerType() &&
2221       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2222     ConvertedType = ToType;
2223     return true;
2224   }
2225 
2226   // If the left-hand-side is nullptr_t, the right side can be a null
2227   // pointer constant.
2228   if (ToType->isNullPtrType() &&
2229       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2230     ConvertedType = ToType;
2231     return true;
2232   }
2233 
2234   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2235   if (!ToTypePtr)
2236     return false;
2237 
2238   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2239   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2240     ConvertedType = ToType;
2241     return true;
2242   }
2243 
2244   // Beyond this point, both types need to be pointers
2245   // , including objective-c pointers.
2246   QualType ToPointeeType = ToTypePtr->getPointeeType();
2247   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2248       !getLangOpts().ObjCAutoRefCount) {
2249     ConvertedType = BuildSimilarlyQualifiedPointerType(
2250                                       FromType->getAs<ObjCObjectPointerType>(),
2251                                                        ToPointeeType,
2252                                                        ToType, Context);
2253     return true;
2254   }
2255   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2256   if (!FromTypePtr)
2257     return false;
2258 
2259   QualType FromPointeeType = FromTypePtr->getPointeeType();
2260 
2261   // If the unqualified pointee types are the same, this can't be a
2262   // pointer conversion, so don't do all of the work below.
2263   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2264     return false;
2265 
2266   // An rvalue of type "pointer to cv T," where T is an object type,
2267   // can be converted to an rvalue of type "pointer to cv void" (C++
2268   // 4.10p2).
2269   if (FromPointeeType->isIncompleteOrObjectType() &&
2270       ToPointeeType->isVoidType()) {
2271     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2272                                                        ToPointeeType,
2273                                                        ToType, Context,
2274                                                    /*StripObjCLifetime=*/true);
2275     return true;
2276   }
2277 
2278   // MSVC allows implicit function to void* type conversion.
2279   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2280       ToPointeeType->isVoidType()) {
2281     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2282                                                        ToPointeeType,
2283                                                        ToType, Context);
2284     return true;
2285   }
2286 
2287   // When we're overloading in C, we allow a special kind of pointer
2288   // conversion for compatible-but-not-identical pointee types.
2289   if (!getLangOpts().CPlusPlus &&
2290       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2291     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2292                                                        ToPointeeType,
2293                                                        ToType, Context);
2294     return true;
2295   }
2296 
2297   // C++ [conv.ptr]p3:
2298   //
2299   //   An rvalue of type "pointer to cv D," where D is a class type,
2300   //   can be converted to an rvalue of type "pointer to cv B," where
2301   //   B is a base class (clause 10) of D. If B is an inaccessible
2302   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2303   //   necessitates this conversion is ill-formed. The result of the
2304   //   conversion is a pointer to the base class sub-object of the
2305   //   derived class object. The null pointer value is converted to
2306   //   the null pointer value of the destination type.
2307   //
2308   // Note that we do not check for ambiguity or inaccessibility
2309   // here. That is handled by CheckPointerConversion.
2310   if (getLangOpts().CPlusPlus &&
2311       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2312       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2313       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2314     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2315                                                        ToPointeeType,
2316                                                        ToType, Context);
2317     return true;
2318   }
2319 
2320   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2321       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2322     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2323                                                        ToPointeeType,
2324                                                        ToType, Context);
2325     return true;
2326   }
2327 
2328   return false;
2329 }
2330 
2331 /// \brief Adopt the given qualifiers for the given type.
2332 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2333   Qualifiers TQs = T.getQualifiers();
2334 
2335   // Check whether qualifiers already match.
2336   if (TQs == Qs)
2337     return T;
2338 
2339   if (Qs.compatiblyIncludes(TQs))
2340     return Context.getQualifiedType(T, Qs);
2341 
2342   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2343 }
2344 
2345 /// isObjCPointerConversion - Determines whether this is an
2346 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2347 /// with the same arguments and return values.
2348 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2349                                    QualType& ConvertedType,
2350                                    bool &IncompatibleObjC) {
2351   if (!getLangOpts().ObjC1)
2352     return false;
2353 
2354   // The set of qualifiers on the type we're converting from.
2355   Qualifiers FromQualifiers = FromType.getQualifiers();
2356 
2357   // First, we handle all conversions on ObjC object pointer types.
2358   const ObjCObjectPointerType* ToObjCPtr =
2359     ToType->getAs<ObjCObjectPointerType>();
2360   const ObjCObjectPointerType *FromObjCPtr =
2361     FromType->getAs<ObjCObjectPointerType>();
2362 
2363   if (ToObjCPtr && FromObjCPtr) {
2364     // If the pointee types are the same (ignoring qualifications),
2365     // then this is not a pointer conversion.
2366     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2367                                        FromObjCPtr->getPointeeType()))
2368       return false;
2369 
2370     // Conversion between Objective-C pointers.
2371     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2372       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2373       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2374       if (getLangOpts().CPlusPlus && LHS && RHS &&
2375           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2376                                                 FromObjCPtr->getPointeeType()))
2377         return false;
2378       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2379                                                    ToObjCPtr->getPointeeType(),
2380                                                          ToType, Context);
2381       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2382       return true;
2383     }
2384 
2385     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2386       // Okay: this is some kind of implicit downcast of Objective-C
2387       // interfaces, which is permitted. However, we're going to
2388       // complain about it.
2389       IncompatibleObjC = true;
2390       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2391                                                    ToObjCPtr->getPointeeType(),
2392                                                          ToType, Context);
2393       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2394       return true;
2395     }
2396   }
2397   // Beyond this point, both types need to be C pointers or block pointers.
2398   QualType ToPointeeType;
2399   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2400     ToPointeeType = ToCPtr->getPointeeType();
2401   else if (const BlockPointerType *ToBlockPtr =
2402             ToType->getAs<BlockPointerType>()) {
2403     // Objective C++: We're able to convert from a pointer to any object
2404     // to a block pointer type.
2405     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2406       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2407       return true;
2408     }
2409     ToPointeeType = ToBlockPtr->getPointeeType();
2410   }
2411   else if (FromType->getAs<BlockPointerType>() &&
2412            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2413     // Objective C++: We're able to convert from a block pointer type to a
2414     // pointer to any object.
2415     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2416     return true;
2417   }
2418   else
2419     return false;
2420 
2421   QualType FromPointeeType;
2422   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2423     FromPointeeType = FromCPtr->getPointeeType();
2424   else if (const BlockPointerType *FromBlockPtr =
2425            FromType->getAs<BlockPointerType>())
2426     FromPointeeType = FromBlockPtr->getPointeeType();
2427   else
2428     return false;
2429 
2430   // If we have pointers to pointers, recursively check whether this
2431   // is an Objective-C conversion.
2432   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2433       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2434                               IncompatibleObjC)) {
2435     // We always complain about this conversion.
2436     IncompatibleObjC = true;
2437     ConvertedType = Context.getPointerType(ConvertedType);
2438     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2439     return true;
2440   }
2441   // Allow conversion of pointee being objective-c pointer to another one;
2442   // as in I* to id.
2443   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2444       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2445       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2446                               IncompatibleObjC)) {
2447 
2448     ConvertedType = Context.getPointerType(ConvertedType);
2449     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2450     return true;
2451   }
2452 
2453   // If we have pointers to functions or blocks, check whether the only
2454   // differences in the argument and result types are in Objective-C
2455   // pointer conversions. If so, we permit the conversion (but
2456   // complain about it).
2457   const FunctionProtoType *FromFunctionType
2458     = FromPointeeType->getAs<FunctionProtoType>();
2459   const FunctionProtoType *ToFunctionType
2460     = ToPointeeType->getAs<FunctionProtoType>();
2461   if (FromFunctionType && ToFunctionType) {
2462     // If the function types are exactly the same, this isn't an
2463     // Objective-C pointer conversion.
2464     if (Context.getCanonicalType(FromPointeeType)
2465           == Context.getCanonicalType(ToPointeeType))
2466       return false;
2467 
2468     // Perform the quick checks that will tell us whether these
2469     // function types are obviously different.
2470     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2471         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2472         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2473       return false;
2474 
2475     bool HasObjCConversion = false;
2476     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2477         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2478       // Okay, the types match exactly. Nothing to do.
2479     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2480                                        ToFunctionType->getReturnType(),
2481                                        ConvertedType, IncompatibleObjC)) {
2482       // Okay, we have an Objective-C pointer conversion.
2483       HasObjCConversion = true;
2484     } else {
2485       // Function types are too different. Abort.
2486       return false;
2487     }
2488 
2489     // Check argument types.
2490     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2491          ArgIdx != NumArgs; ++ArgIdx) {
2492       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2493       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2494       if (Context.getCanonicalType(FromArgType)
2495             == Context.getCanonicalType(ToArgType)) {
2496         // Okay, the types match exactly. Nothing to do.
2497       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2498                                          ConvertedType, IncompatibleObjC)) {
2499         // Okay, we have an Objective-C pointer conversion.
2500         HasObjCConversion = true;
2501       } else {
2502         // Argument types are too different. Abort.
2503         return false;
2504       }
2505     }
2506 
2507     if (HasObjCConversion) {
2508       // We had an Objective-C conversion. Allow this pointer
2509       // conversion, but complain about it.
2510       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2511       IncompatibleObjC = true;
2512       return true;
2513     }
2514   }
2515 
2516   return false;
2517 }
2518 
2519 /// \brief Determine whether this is an Objective-C writeback conversion,
2520 /// used for parameter passing when performing automatic reference counting.
2521 ///
2522 /// \param FromType The type we're converting form.
2523 ///
2524 /// \param ToType The type we're converting to.
2525 ///
2526 /// \param ConvertedType The type that will be produced after applying
2527 /// this conversion.
2528 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2529                                      QualType &ConvertedType) {
2530   if (!getLangOpts().ObjCAutoRefCount ||
2531       Context.hasSameUnqualifiedType(FromType, ToType))
2532     return false;
2533 
2534   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2535   QualType ToPointee;
2536   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2537     ToPointee = ToPointer->getPointeeType();
2538   else
2539     return false;
2540 
2541   Qualifiers ToQuals = ToPointee.getQualifiers();
2542   if (!ToPointee->isObjCLifetimeType() ||
2543       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2544       !ToQuals.withoutObjCLifetime().empty())
2545     return false;
2546 
2547   // Argument must be a pointer to __strong to __weak.
2548   QualType FromPointee;
2549   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2550     FromPointee = FromPointer->getPointeeType();
2551   else
2552     return false;
2553 
2554   Qualifiers FromQuals = FromPointee.getQualifiers();
2555   if (!FromPointee->isObjCLifetimeType() ||
2556       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2557        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2558     return false;
2559 
2560   // Make sure that we have compatible qualifiers.
2561   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2562   if (!ToQuals.compatiblyIncludes(FromQuals))
2563     return false;
2564 
2565   // Remove qualifiers from the pointee type we're converting from; they
2566   // aren't used in the compatibility check belong, and we'll be adding back
2567   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2568   FromPointee = FromPointee.getUnqualifiedType();
2569 
2570   // The unqualified form of the pointee types must be compatible.
2571   ToPointee = ToPointee.getUnqualifiedType();
2572   bool IncompatibleObjC;
2573   if (Context.typesAreCompatible(FromPointee, ToPointee))
2574     FromPointee = ToPointee;
2575   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2576                                     IncompatibleObjC))
2577     return false;
2578 
2579   /// \brief Construct the type we're converting to, which is a pointer to
2580   /// __autoreleasing pointee.
2581   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2582   ConvertedType = Context.getPointerType(FromPointee);
2583   return true;
2584 }
2585 
2586 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2587                                     QualType& ConvertedType) {
2588   QualType ToPointeeType;
2589   if (const BlockPointerType *ToBlockPtr =
2590         ToType->getAs<BlockPointerType>())
2591     ToPointeeType = ToBlockPtr->getPointeeType();
2592   else
2593     return false;
2594 
2595   QualType FromPointeeType;
2596   if (const BlockPointerType *FromBlockPtr =
2597       FromType->getAs<BlockPointerType>())
2598     FromPointeeType = FromBlockPtr->getPointeeType();
2599   else
2600     return false;
2601   // We have pointer to blocks, check whether the only
2602   // differences in the argument and result types are in Objective-C
2603   // pointer conversions. If so, we permit the conversion.
2604 
2605   const FunctionProtoType *FromFunctionType
2606     = FromPointeeType->getAs<FunctionProtoType>();
2607   const FunctionProtoType *ToFunctionType
2608     = ToPointeeType->getAs<FunctionProtoType>();
2609 
2610   if (!FromFunctionType || !ToFunctionType)
2611     return false;
2612 
2613   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2614     return true;
2615 
2616   // Perform the quick checks that will tell us whether these
2617   // function types are obviously different.
2618   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2619       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2620     return false;
2621 
2622   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2623   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2624   if (FromEInfo != ToEInfo)
2625     return false;
2626 
2627   bool IncompatibleObjC = false;
2628   if (Context.hasSameType(FromFunctionType->getReturnType(),
2629                           ToFunctionType->getReturnType())) {
2630     // Okay, the types match exactly. Nothing to do.
2631   } else {
2632     QualType RHS = FromFunctionType->getReturnType();
2633     QualType LHS = ToFunctionType->getReturnType();
2634     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2635         !RHS.hasQualifiers() && LHS.hasQualifiers())
2636        LHS = LHS.getUnqualifiedType();
2637 
2638      if (Context.hasSameType(RHS,LHS)) {
2639        // OK exact match.
2640      } else if (isObjCPointerConversion(RHS, LHS,
2641                                         ConvertedType, IncompatibleObjC)) {
2642      if (IncompatibleObjC)
2643        return false;
2644      // Okay, we have an Objective-C pointer conversion.
2645      }
2646      else
2647        return false;
2648    }
2649 
2650    // Check argument types.
2651    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2652         ArgIdx != NumArgs; ++ArgIdx) {
2653      IncompatibleObjC = false;
2654      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2655      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2656      if (Context.hasSameType(FromArgType, ToArgType)) {
2657        // Okay, the types match exactly. Nothing to do.
2658      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2659                                         ConvertedType, IncompatibleObjC)) {
2660        if (IncompatibleObjC)
2661          return false;
2662        // Okay, we have an Objective-C pointer conversion.
2663      } else
2664        // Argument types are too different. Abort.
2665        return false;
2666    }
2667    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2668                                                         ToFunctionType))
2669      return false;
2670 
2671    ConvertedType = ToType;
2672    return true;
2673 }
2674 
2675 enum {
2676   ft_default,
2677   ft_different_class,
2678   ft_parameter_arity,
2679   ft_parameter_mismatch,
2680   ft_return_type,
2681   ft_qualifer_mismatch,
2682   ft_noexcept
2683 };
2684 
2685 /// Attempts to get the FunctionProtoType from a Type. Handles
2686 /// MemberFunctionPointers properly.
2687 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2688   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2689     return FPT;
2690 
2691   if (auto *MPT = FromType->getAs<MemberPointerType>())
2692     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2693 
2694   return nullptr;
2695 }
2696 
2697 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2698 /// function types.  Catches different number of parameter, mismatch in
2699 /// parameter types, and different return types.
2700 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2701                                       QualType FromType, QualType ToType) {
2702   // If either type is not valid, include no extra info.
2703   if (FromType.isNull() || ToType.isNull()) {
2704     PDiag << ft_default;
2705     return;
2706   }
2707 
2708   // Get the function type from the pointers.
2709   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2710     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2711                             *ToMember = ToType->getAs<MemberPointerType>();
2712     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2713       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2714             << QualType(FromMember->getClass(), 0);
2715       return;
2716     }
2717     FromType = FromMember->getPointeeType();
2718     ToType = ToMember->getPointeeType();
2719   }
2720 
2721   if (FromType->isPointerType())
2722     FromType = FromType->getPointeeType();
2723   if (ToType->isPointerType())
2724     ToType = ToType->getPointeeType();
2725 
2726   // Remove references.
2727   FromType = FromType.getNonReferenceType();
2728   ToType = ToType.getNonReferenceType();
2729 
2730   // Don't print extra info for non-specialized template functions.
2731   if (FromType->isInstantiationDependentType() &&
2732       !FromType->getAs<TemplateSpecializationType>()) {
2733     PDiag << ft_default;
2734     return;
2735   }
2736 
2737   // No extra info for same types.
2738   if (Context.hasSameType(FromType, ToType)) {
2739     PDiag << ft_default;
2740     return;
2741   }
2742 
2743   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2744                           *ToFunction = tryGetFunctionProtoType(ToType);
2745 
2746   // Both types need to be function types.
2747   if (!FromFunction || !ToFunction) {
2748     PDiag << ft_default;
2749     return;
2750   }
2751 
2752   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2753     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2754           << FromFunction->getNumParams();
2755     return;
2756   }
2757 
2758   // Handle different parameter types.
2759   unsigned ArgPos;
2760   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2761     PDiag << ft_parameter_mismatch << ArgPos + 1
2762           << ToFunction->getParamType(ArgPos)
2763           << FromFunction->getParamType(ArgPos);
2764     return;
2765   }
2766 
2767   // Handle different return type.
2768   if (!Context.hasSameType(FromFunction->getReturnType(),
2769                            ToFunction->getReturnType())) {
2770     PDiag << ft_return_type << ToFunction->getReturnType()
2771           << FromFunction->getReturnType();
2772     return;
2773   }
2774 
2775   unsigned FromQuals = FromFunction->getTypeQuals(),
2776            ToQuals = ToFunction->getTypeQuals();
2777   if (FromQuals != ToQuals) {
2778     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2779     return;
2780   }
2781 
2782   // Handle exception specification differences on canonical type (in C++17
2783   // onwards).
2784   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2785           ->isNothrow(Context) !=
2786       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2787           ->isNothrow(Context)) {
2788     PDiag << ft_noexcept;
2789     return;
2790   }
2791 
2792   // Unable to find a difference, so add no extra info.
2793   PDiag << ft_default;
2794 }
2795 
2796 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2797 /// for equality of their argument types. Caller has already checked that
2798 /// they have same number of arguments.  If the parameters are different,
2799 /// ArgPos will have the parameter index of the first different parameter.
2800 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2801                                       const FunctionProtoType *NewType,
2802                                       unsigned *ArgPos) {
2803   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2804                                               N = NewType->param_type_begin(),
2805                                               E = OldType->param_type_end();
2806        O && (O != E); ++O, ++N) {
2807     if (!Context.hasSameType(O->getUnqualifiedType(),
2808                              N->getUnqualifiedType())) {
2809       if (ArgPos)
2810         *ArgPos = O - OldType->param_type_begin();
2811       return false;
2812     }
2813   }
2814   return true;
2815 }
2816 
2817 /// CheckPointerConversion - Check the pointer conversion from the
2818 /// expression From to the type ToType. This routine checks for
2819 /// ambiguous or inaccessible derived-to-base pointer
2820 /// conversions for which IsPointerConversion has already returned
2821 /// true. It returns true and produces a diagnostic if there was an
2822 /// error, or returns false otherwise.
2823 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2824                                   CastKind &Kind,
2825                                   CXXCastPath& BasePath,
2826                                   bool IgnoreBaseAccess,
2827                                   bool Diagnose) {
2828   QualType FromType = From->getType();
2829   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2830 
2831   Kind = CK_BitCast;
2832 
2833   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2834       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2835           Expr::NPCK_ZeroExpression) {
2836     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2837       DiagRuntimeBehavior(From->getExprLoc(), From,
2838                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2839                             << ToType << From->getSourceRange());
2840     else if (!isUnevaluatedContext())
2841       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2842         << ToType << From->getSourceRange();
2843   }
2844   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2845     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2846       QualType FromPointeeType = FromPtrType->getPointeeType(),
2847                ToPointeeType   = ToPtrType->getPointeeType();
2848 
2849       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2850           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2851         // We must have a derived-to-base conversion. Check an
2852         // ambiguous or inaccessible conversion.
2853         unsigned InaccessibleID = 0;
2854         unsigned AmbigiousID = 0;
2855         if (Diagnose) {
2856           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2857           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2858         }
2859         if (CheckDerivedToBaseConversion(
2860                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2861                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2862                 &BasePath, IgnoreBaseAccess))
2863           return true;
2864 
2865         // The conversion was successful.
2866         Kind = CK_DerivedToBase;
2867       }
2868 
2869       if (Diagnose && !IsCStyleOrFunctionalCast &&
2870           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2871         assert(getLangOpts().MSVCCompat &&
2872                "this should only be possible with MSVCCompat!");
2873         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2874             << From->getSourceRange();
2875       }
2876     }
2877   } else if (const ObjCObjectPointerType *ToPtrType =
2878                ToType->getAs<ObjCObjectPointerType>()) {
2879     if (const ObjCObjectPointerType *FromPtrType =
2880           FromType->getAs<ObjCObjectPointerType>()) {
2881       // Objective-C++ conversions are always okay.
2882       // FIXME: We should have a different class of conversions for the
2883       // Objective-C++ implicit conversions.
2884       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2885         return false;
2886     } else if (FromType->isBlockPointerType()) {
2887       Kind = CK_BlockPointerToObjCPointerCast;
2888     } else {
2889       Kind = CK_CPointerToObjCPointerCast;
2890     }
2891   } else if (ToType->isBlockPointerType()) {
2892     if (!FromType->isBlockPointerType())
2893       Kind = CK_AnyPointerToBlockPointerCast;
2894   }
2895 
2896   // We shouldn't fall into this case unless it's valid for other
2897   // reasons.
2898   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2899     Kind = CK_NullToPointer;
2900 
2901   return false;
2902 }
2903 
2904 /// IsMemberPointerConversion - Determines whether the conversion of the
2905 /// expression From, which has the (possibly adjusted) type FromType, can be
2906 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2907 /// If so, returns true and places the converted type (that might differ from
2908 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2909 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2910                                      QualType ToType,
2911                                      bool InOverloadResolution,
2912                                      QualType &ConvertedType) {
2913   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2914   if (!ToTypePtr)
2915     return false;
2916 
2917   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2918   if (From->isNullPointerConstant(Context,
2919                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2920                                         : Expr::NPC_ValueDependentIsNull)) {
2921     ConvertedType = ToType;
2922     return true;
2923   }
2924 
2925   // Otherwise, both types have to be member pointers.
2926   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2927   if (!FromTypePtr)
2928     return false;
2929 
2930   // A pointer to member of B can be converted to a pointer to member of D,
2931   // where D is derived from B (C++ 4.11p2).
2932   QualType FromClass(FromTypePtr->getClass(), 0);
2933   QualType ToClass(ToTypePtr->getClass(), 0);
2934 
2935   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2936       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2937     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2938                                                  ToClass.getTypePtr());
2939     return true;
2940   }
2941 
2942   return false;
2943 }
2944 
2945 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2946 /// expression From to the type ToType. This routine checks for ambiguous or
2947 /// virtual or inaccessible base-to-derived member pointer conversions
2948 /// for which IsMemberPointerConversion has already returned true. It returns
2949 /// true and produces a diagnostic if there was an error, or returns false
2950 /// otherwise.
2951 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2952                                         CastKind &Kind,
2953                                         CXXCastPath &BasePath,
2954                                         bool IgnoreBaseAccess) {
2955   QualType FromType = From->getType();
2956   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2957   if (!FromPtrType) {
2958     // This must be a null pointer to member pointer conversion
2959     assert(From->isNullPointerConstant(Context,
2960                                        Expr::NPC_ValueDependentIsNull) &&
2961            "Expr must be null pointer constant!");
2962     Kind = CK_NullToMemberPointer;
2963     return false;
2964   }
2965 
2966   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2967   assert(ToPtrType && "No member pointer cast has a target type "
2968                       "that is not a member pointer.");
2969 
2970   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2971   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2972 
2973   // FIXME: What about dependent types?
2974   assert(FromClass->isRecordType() && "Pointer into non-class.");
2975   assert(ToClass->isRecordType() && "Pointer into non-class.");
2976 
2977   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2978                      /*DetectVirtual=*/true);
2979   bool DerivationOkay =
2980       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2981   assert(DerivationOkay &&
2982          "Should not have been called if derivation isn't OK.");
2983   (void)DerivationOkay;
2984 
2985   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2986                                   getUnqualifiedType())) {
2987     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2988     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2989       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2990     return true;
2991   }
2992 
2993   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2994     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2995       << FromClass << ToClass << QualType(VBase, 0)
2996       << From->getSourceRange();
2997     return true;
2998   }
2999 
3000   if (!IgnoreBaseAccess)
3001     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3002                          Paths.front(),
3003                          diag::err_downcast_from_inaccessible_base);
3004 
3005   // Must be a base to derived member conversion.
3006   BuildBasePathArray(Paths, BasePath);
3007   Kind = CK_BaseToDerivedMemberPointer;
3008   return false;
3009 }
3010 
3011 /// Determine whether the lifetime conversion between the two given
3012 /// qualifiers sets is nontrivial.
3013 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3014                                                Qualifiers ToQuals) {
3015   // Converting anything to const __unsafe_unretained is trivial.
3016   if (ToQuals.hasConst() &&
3017       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3018     return false;
3019 
3020   return true;
3021 }
3022 
3023 /// IsQualificationConversion - Determines whether the conversion from
3024 /// an rvalue of type FromType to ToType is a qualification conversion
3025 /// (C++ 4.4).
3026 ///
3027 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3028 /// when the qualification conversion involves a change in the Objective-C
3029 /// object lifetime.
3030 bool
3031 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3032                                 bool CStyle, bool &ObjCLifetimeConversion) {
3033   FromType = Context.getCanonicalType(FromType);
3034   ToType = Context.getCanonicalType(ToType);
3035   ObjCLifetimeConversion = false;
3036 
3037   // If FromType and ToType are the same type, this is not a
3038   // qualification conversion.
3039   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3040     return false;
3041 
3042   // (C++ 4.4p4):
3043   //   A conversion can add cv-qualifiers at levels other than the first
3044   //   in multi-level pointers, subject to the following rules: [...]
3045   bool PreviousToQualsIncludeConst = true;
3046   bool UnwrappedAnyPointer = false;
3047   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3048     // Within each iteration of the loop, we check the qualifiers to
3049     // determine if this still looks like a qualification
3050     // conversion. Then, if all is well, we unwrap one more level of
3051     // pointers or pointers-to-members and do it all again
3052     // until there are no more pointers or pointers-to-members left to
3053     // unwrap.
3054     UnwrappedAnyPointer = true;
3055 
3056     Qualifiers FromQuals = FromType.getQualifiers();
3057     Qualifiers ToQuals = ToType.getQualifiers();
3058 
3059     // Ignore __unaligned qualifier if this type is void.
3060     if (ToType.getUnqualifiedType()->isVoidType())
3061       FromQuals.removeUnaligned();
3062 
3063     // Objective-C ARC:
3064     //   Check Objective-C lifetime conversions.
3065     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3066         UnwrappedAnyPointer) {
3067       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3068         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3069           ObjCLifetimeConversion = true;
3070         FromQuals.removeObjCLifetime();
3071         ToQuals.removeObjCLifetime();
3072       } else {
3073         // Qualification conversions cannot cast between different
3074         // Objective-C lifetime qualifiers.
3075         return false;
3076       }
3077     }
3078 
3079     // Allow addition/removal of GC attributes but not changing GC attributes.
3080     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3081         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3082       FromQuals.removeObjCGCAttr();
3083       ToQuals.removeObjCGCAttr();
3084     }
3085 
3086     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3087     //      2,j, and similarly for volatile.
3088     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3089       return false;
3090 
3091     //   -- if the cv 1,j and cv 2,j are different, then const is in
3092     //      every cv for 0 < k < j.
3093     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3094         && !PreviousToQualsIncludeConst)
3095       return false;
3096 
3097     // Keep track of whether all prior cv-qualifiers in the "to" type
3098     // include const.
3099     PreviousToQualsIncludeConst
3100       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3101   }
3102 
3103   // We are left with FromType and ToType being the pointee types
3104   // after unwrapping the original FromType and ToType the same number
3105   // of types. If we unwrapped any pointers, and if FromType and
3106   // ToType have the same unqualified type (since we checked
3107   // qualifiers above), then this is a qualification conversion.
3108   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3109 }
3110 
3111 /// \brief - Determine whether this is a conversion from a scalar type to an
3112 /// atomic type.
3113 ///
3114 /// If successful, updates \c SCS's second and third steps in the conversion
3115 /// sequence to finish the conversion.
3116 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3117                                 bool InOverloadResolution,
3118                                 StandardConversionSequence &SCS,
3119                                 bool CStyle) {
3120   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3121   if (!ToAtomic)
3122     return false;
3123 
3124   StandardConversionSequence InnerSCS;
3125   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3126                             InOverloadResolution, InnerSCS,
3127                             CStyle, /*AllowObjCWritebackConversion=*/false))
3128     return false;
3129 
3130   SCS.Second = InnerSCS.Second;
3131   SCS.setToType(1, InnerSCS.getToType(1));
3132   SCS.Third = InnerSCS.Third;
3133   SCS.QualificationIncludesObjCLifetime
3134     = InnerSCS.QualificationIncludesObjCLifetime;
3135   SCS.setToType(2, InnerSCS.getToType(2));
3136   return true;
3137 }
3138 
3139 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3140                                               CXXConstructorDecl *Constructor,
3141                                               QualType Type) {
3142   const FunctionProtoType *CtorType =
3143       Constructor->getType()->getAs<FunctionProtoType>();
3144   if (CtorType->getNumParams() > 0) {
3145     QualType FirstArg = CtorType->getParamType(0);
3146     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3147       return true;
3148   }
3149   return false;
3150 }
3151 
3152 static OverloadingResult
3153 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3154                                        CXXRecordDecl *To,
3155                                        UserDefinedConversionSequence &User,
3156                                        OverloadCandidateSet &CandidateSet,
3157                                        bool AllowExplicit) {
3158   for (auto *D : S.LookupConstructors(To)) {
3159     auto Info = getConstructorInfo(D);
3160     if (!Info)
3161       continue;
3162 
3163     bool Usable = !Info.Constructor->isInvalidDecl() &&
3164                   S.isInitListConstructor(Info.Constructor) &&
3165                   (AllowExplicit || !Info.Constructor->isExplicit());
3166     if (Usable) {
3167       // If the first argument is (a reference to) the target type,
3168       // suppress conversions.
3169       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3170           S.Context, Info.Constructor, ToType);
3171       if (Info.ConstructorTmpl)
3172         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3173                                        /*ExplicitArgs*/ nullptr, From,
3174                                        CandidateSet, SuppressUserConversions);
3175       else
3176         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3177                                CandidateSet, SuppressUserConversions);
3178     }
3179   }
3180 
3181   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3182 
3183   OverloadCandidateSet::iterator Best;
3184   switch (auto Result =
3185             CandidateSet.BestViableFunction(S, From->getLocStart(),
3186                                             Best, true)) {
3187   case OR_Deleted:
3188   case OR_Success: {
3189     // Record the standard conversion we used and the conversion function.
3190     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3191     QualType ThisType = Constructor->getThisType(S.Context);
3192     // Initializer lists don't have conversions as such.
3193     User.Before.setAsIdentityConversion();
3194     User.HadMultipleCandidates = HadMultipleCandidates;
3195     User.ConversionFunction = Constructor;
3196     User.FoundConversionFunction = Best->FoundDecl;
3197     User.After.setAsIdentityConversion();
3198     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3199     User.After.setAllToTypes(ToType);
3200     return Result;
3201   }
3202 
3203   case OR_No_Viable_Function:
3204     return OR_No_Viable_Function;
3205   case OR_Ambiguous:
3206     return OR_Ambiguous;
3207   }
3208 
3209   llvm_unreachable("Invalid OverloadResult!");
3210 }
3211 
3212 /// Determines whether there is a user-defined conversion sequence
3213 /// (C++ [over.ics.user]) that converts expression From to the type
3214 /// ToType. If such a conversion exists, User will contain the
3215 /// user-defined conversion sequence that performs such a conversion
3216 /// and this routine will return true. Otherwise, this routine returns
3217 /// false and User is unspecified.
3218 ///
3219 /// \param AllowExplicit  true if the conversion should consider C++0x
3220 /// "explicit" conversion functions as well as non-explicit conversion
3221 /// functions (C++0x [class.conv.fct]p2).
3222 ///
3223 /// \param AllowObjCConversionOnExplicit true if the conversion should
3224 /// allow an extra Objective-C pointer conversion on uses of explicit
3225 /// constructors. Requires \c AllowExplicit to also be set.
3226 static OverloadingResult
3227 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3228                         UserDefinedConversionSequence &User,
3229                         OverloadCandidateSet &CandidateSet,
3230                         bool AllowExplicit,
3231                         bool AllowObjCConversionOnExplicit) {
3232   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3233 
3234   // Whether we will only visit constructors.
3235   bool ConstructorsOnly = false;
3236 
3237   // If the type we are conversion to is a class type, enumerate its
3238   // constructors.
3239   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3240     // C++ [over.match.ctor]p1:
3241     //   When objects of class type are direct-initialized (8.5), or
3242     //   copy-initialized from an expression of the same or a
3243     //   derived class type (8.5), overload resolution selects the
3244     //   constructor. [...] For copy-initialization, the candidate
3245     //   functions are all the converting constructors (12.3.1) of
3246     //   that class. The argument list is the expression-list within
3247     //   the parentheses of the initializer.
3248     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3249         (From->getType()->getAs<RecordType>() &&
3250          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3251       ConstructorsOnly = true;
3252 
3253     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3254       // We're not going to find any constructors.
3255     } else if (CXXRecordDecl *ToRecordDecl
3256                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3257 
3258       Expr **Args = &From;
3259       unsigned NumArgs = 1;
3260       bool ListInitializing = false;
3261       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3262         // But first, see if there is an init-list-constructor that will work.
3263         OverloadingResult Result = IsInitializerListConstructorConversion(
3264             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3265         if (Result != OR_No_Viable_Function)
3266           return Result;
3267         // Never mind.
3268         CandidateSet.clear();
3269 
3270         // If we're list-initializing, we pass the individual elements as
3271         // arguments, not the entire list.
3272         Args = InitList->getInits();
3273         NumArgs = InitList->getNumInits();
3274         ListInitializing = true;
3275       }
3276 
3277       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3278         auto Info = getConstructorInfo(D);
3279         if (!Info)
3280           continue;
3281 
3282         bool Usable = !Info.Constructor->isInvalidDecl();
3283         if (ListInitializing)
3284           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3285         else
3286           Usable = Usable &&
3287                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3288         if (Usable) {
3289           bool SuppressUserConversions = !ConstructorsOnly;
3290           if (SuppressUserConversions && ListInitializing) {
3291             SuppressUserConversions = false;
3292             if (NumArgs == 1) {
3293               // If the first argument is (a reference to) the target type,
3294               // suppress conversions.
3295               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3296                   S.Context, Info.Constructor, ToType);
3297             }
3298           }
3299           if (Info.ConstructorTmpl)
3300             S.AddTemplateOverloadCandidate(
3301                 Info.ConstructorTmpl, Info.FoundDecl,
3302                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3303                 CandidateSet, SuppressUserConversions);
3304           else
3305             // Allow one user-defined conversion when user specifies a
3306             // From->ToType conversion via an static cast (c-style, etc).
3307             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3308                                    llvm::makeArrayRef(Args, NumArgs),
3309                                    CandidateSet, SuppressUserConversions);
3310         }
3311       }
3312     }
3313   }
3314 
3315   // Enumerate conversion functions, if we're allowed to.
3316   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3317   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3318     // No conversion functions from incomplete types.
3319   } else if (const RecordType *FromRecordType
3320                                    = From->getType()->getAs<RecordType>()) {
3321     if (CXXRecordDecl *FromRecordDecl
3322          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3323       // Add all of the conversion functions as candidates.
3324       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3325       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3326         DeclAccessPair FoundDecl = I.getPair();
3327         NamedDecl *D = FoundDecl.getDecl();
3328         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3329         if (isa<UsingShadowDecl>(D))
3330           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3331 
3332         CXXConversionDecl *Conv;
3333         FunctionTemplateDecl *ConvTemplate;
3334         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3335           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3336         else
3337           Conv = cast<CXXConversionDecl>(D);
3338 
3339         if (AllowExplicit || !Conv->isExplicit()) {
3340           if (ConvTemplate)
3341             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3342                                              ActingContext, From, ToType,
3343                                              CandidateSet,
3344                                              AllowObjCConversionOnExplicit);
3345           else
3346             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3347                                      From, ToType, CandidateSet,
3348                                      AllowObjCConversionOnExplicit);
3349         }
3350       }
3351     }
3352   }
3353 
3354   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3355 
3356   OverloadCandidateSet::iterator Best;
3357   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3358                                                         Best, true)) {
3359   case OR_Success:
3360   case OR_Deleted:
3361     // Record the standard conversion we used and the conversion function.
3362     if (CXXConstructorDecl *Constructor
3363           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3364       // C++ [over.ics.user]p1:
3365       //   If the user-defined conversion is specified by a
3366       //   constructor (12.3.1), the initial standard conversion
3367       //   sequence converts the source type to the type required by
3368       //   the argument of the constructor.
3369       //
3370       QualType ThisType = Constructor->getThisType(S.Context);
3371       if (isa<InitListExpr>(From)) {
3372         // Initializer lists don't have conversions as such.
3373         User.Before.setAsIdentityConversion();
3374       } else {
3375         if (Best->Conversions[0].isEllipsis())
3376           User.EllipsisConversion = true;
3377         else {
3378           User.Before = Best->Conversions[0].Standard;
3379           User.EllipsisConversion = false;
3380         }
3381       }
3382       User.HadMultipleCandidates = HadMultipleCandidates;
3383       User.ConversionFunction = Constructor;
3384       User.FoundConversionFunction = Best->FoundDecl;
3385       User.After.setAsIdentityConversion();
3386       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3387       User.After.setAllToTypes(ToType);
3388       return Result;
3389     }
3390     if (CXXConversionDecl *Conversion
3391                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3392       // C++ [over.ics.user]p1:
3393       //
3394       //   [...] If the user-defined conversion is specified by a
3395       //   conversion function (12.3.2), the initial standard
3396       //   conversion sequence converts the source type to the
3397       //   implicit object parameter of the conversion function.
3398       User.Before = Best->Conversions[0].Standard;
3399       User.HadMultipleCandidates = HadMultipleCandidates;
3400       User.ConversionFunction = Conversion;
3401       User.FoundConversionFunction = Best->FoundDecl;
3402       User.EllipsisConversion = false;
3403 
3404       // C++ [over.ics.user]p2:
3405       //   The second standard conversion sequence converts the
3406       //   result of the user-defined conversion to the target type
3407       //   for the sequence. Since an implicit conversion sequence
3408       //   is an initialization, the special rules for
3409       //   initialization by user-defined conversion apply when
3410       //   selecting the best user-defined conversion for a
3411       //   user-defined conversion sequence (see 13.3.3 and
3412       //   13.3.3.1).
3413       User.After = Best->FinalConversion;
3414       return Result;
3415     }
3416     llvm_unreachable("Not a constructor or conversion function?");
3417 
3418   case OR_No_Viable_Function:
3419     return OR_No_Viable_Function;
3420 
3421   case OR_Ambiguous:
3422     return OR_Ambiguous;
3423   }
3424 
3425   llvm_unreachable("Invalid OverloadResult!");
3426 }
3427 
3428 bool
3429 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3430   ImplicitConversionSequence ICS;
3431   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3432                                     OverloadCandidateSet::CSK_Normal);
3433   OverloadingResult OvResult =
3434     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3435                             CandidateSet, false, false);
3436   if (OvResult == OR_Ambiguous)
3437     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3438         << From->getType() << ToType << From->getSourceRange();
3439   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3440     if (!RequireCompleteType(From->getLocStart(), ToType,
3441                              diag::err_typecheck_nonviable_condition_incomplete,
3442                              From->getType(), From->getSourceRange()))
3443       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3444           << false << From->getType() << From->getSourceRange() << ToType;
3445   } else
3446     return false;
3447   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3448   return true;
3449 }
3450 
3451 /// \brief Compare the user-defined conversion functions or constructors
3452 /// of two user-defined conversion sequences to determine whether any ordering
3453 /// is possible.
3454 static ImplicitConversionSequence::CompareKind
3455 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3456                            FunctionDecl *Function2) {
3457   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3458     return ImplicitConversionSequence::Indistinguishable;
3459 
3460   // Objective-C++:
3461   //   If both conversion functions are implicitly-declared conversions from
3462   //   a lambda closure type to a function pointer and a block pointer,
3463   //   respectively, always prefer the conversion to a function pointer,
3464   //   because the function pointer is more lightweight and is more likely
3465   //   to keep code working.
3466   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3467   if (!Conv1)
3468     return ImplicitConversionSequence::Indistinguishable;
3469 
3470   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3471   if (!Conv2)
3472     return ImplicitConversionSequence::Indistinguishable;
3473 
3474   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3475     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3476     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3477     if (Block1 != Block2)
3478       return Block1 ? ImplicitConversionSequence::Worse
3479                     : ImplicitConversionSequence::Better;
3480   }
3481 
3482   return ImplicitConversionSequence::Indistinguishable;
3483 }
3484 
3485 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3486     const ImplicitConversionSequence &ICS) {
3487   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3488          (ICS.isUserDefined() &&
3489           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3490 }
3491 
3492 /// CompareImplicitConversionSequences - Compare two implicit
3493 /// conversion sequences to determine whether one is better than the
3494 /// other or if they are indistinguishable (C++ 13.3.3.2).
3495 static ImplicitConversionSequence::CompareKind
3496 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3497                                    const ImplicitConversionSequence& ICS1,
3498                                    const ImplicitConversionSequence& ICS2)
3499 {
3500   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3501   // conversion sequences (as defined in 13.3.3.1)
3502   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3503   //      conversion sequence than a user-defined conversion sequence or
3504   //      an ellipsis conversion sequence, and
3505   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3506   //      conversion sequence than an ellipsis conversion sequence
3507   //      (13.3.3.1.3).
3508   //
3509   // C++0x [over.best.ics]p10:
3510   //   For the purpose of ranking implicit conversion sequences as
3511   //   described in 13.3.3.2, the ambiguous conversion sequence is
3512   //   treated as a user-defined sequence that is indistinguishable
3513   //   from any other user-defined conversion sequence.
3514 
3515   // String literal to 'char *' conversion has been deprecated in C++03. It has
3516   // been removed from C++11. We still accept this conversion, if it happens at
3517   // the best viable function. Otherwise, this conversion is considered worse
3518   // than ellipsis conversion. Consider this as an extension; this is not in the
3519   // standard. For example:
3520   //
3521   // int &f(...);    // #1
3522   // void f(char*);  // #2
3523   // void g() { int &r = f("foo"); }
3524   //
3525   // In C++03, we pick #2 as the best viable function.
3526   // In C++11, we pick #1 as the best viable function, because ellipsis
3527   // conversion is better than string-literal to char* conversion (since there
3528   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3529   // convert arguments, #2 would be the best viable function in C++11.
3530   // If the best viable function has this conversion, a warning will be issued
3531   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3532 
3533   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3534       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3535       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3536     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3537                ? ImplicitConversionSequence::Worse
3538                : ImplicitConversionSequence::Better;
3539 
3540   if (ICS1.getKindRank() < ICS2.getKindRank())
3541     return ImplicitConversionSequence::Better;
3542   if (ICS2.getKindRank() < ICS1.getKindRank())
3543     return ImplicitConversionSequence::Worse;
3544 
3545   // The following checks require both conversion sequences to be of
3546   // the same kind.
3547   if (ICS1.getKind() != ICS2.getKind())
3548     return ImplicitConversionSequence::Indistinguishable;
3549 
3550   ImplicitConversionSequence::CompareKind Result =
3551       ImplicitConversionSequence::Indistinguishable;
3552 
3553   // Two implicit conversion sequences of the same form are
3554   // indistinguishable conversion sequences unless one of the
3555   // following rules apply: (C++ 13.3.3.2p3):
3556 
3557   // List-initialization sequence L1 is a better conversion sequence than
3558   // list-initialization sequence L2 if:
3559   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3560   //   if not that,
3561   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3562   //   and N1 is smaller than N2.,
3563   // even if one of the other rules in this paragraph would otherwise apply.
3564   if (!ICS1.isBad()) {
3565     if (ICS1.isStdInitializerListElement() &&
3566         !ICS2.isStdInitializerListElement())
3567       return ImplicitConversionSequence::Better;
3568     if (!ICS1.isStdInitializerListElement() &&
3569         ICS2.isStdInitializerListElement())
3570       return ImplicitConversionSequence::Worse;
3571   }
3572 
3573   if (ICS1.isStandard())
3574     // Standard conversion sequence S1 is a better conversion sequence than
3575     // standard conversion sequence S2 if [...]
3576     Result = CompareStandardConversionSequences(S, Loc,
3577                                                 ICS1.Standard, ICS2.Standard);
3578   else if (ICS1.isUserDefined()) {
3579     // User-defined conversion sequence U1 is a better conversion
3580     // sequence than another user-defined conversion sequence U2 if
3581     // they contain the same user-defined conversion function or
3582     // constructor and if the second standard conversion sequence of
3583     // U1 is better than the second standard conversion sequence of
3584     // U2 (C++ 13.3.3.2p3).
3585     if (ICS1.UserDefined.ConversionFunction ==
3586           ICS2.UserDefined.ConversionFunction)
3587       Result = CompareStandardConversionSequences(S, Loc,
3588                                                   ICS1.UserDefined.After,
3589                                                   ICS2.UserDefined.After);
3590     else
3591       Result = compareConversionFunctions(S,
3592                                           ICS1.UserDefined.ConversionFunction,
3593                                           ICS2.UserDefined.ConversionFunction);
3594   }
3595 
3596   return Result;
3597 }
3598 
3599 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3600   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3601     Qualifiers Quals;
3602     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3603     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3604   }
3605 
3606   return Context.hasSameUnqualifiedType(T1, T2);
3607 }
3608 
3609 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3610 // determine if one is a proper subset of the other.
3611 static ImplicitConversionSequence::CompareKind
3612 compareStandardConversionSubsets(ASTContext &Context,
3613                                  const StandardConversionSequence& SCS1,
3614                                  const StandardConversionSequence& SCS2) {
3615   ImplicitConversionSequence::CompareKind Result
3616     = ImplicitConversionSequence::Indistinguishable;
3617 
3618   // the identity conversion sequence is considered to be a subsequence of
3619   // any non-identity conversion sequence
3620   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3621     return ImplicitConversionSequence::Better;
3622   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3623     return ImplicitConversionSequence::Worse;
3624 
3625   if (SCS1.Second != SCS2.Second) {
3626     if (SCS1.Second == ICK_Identity)
3627       Result = ImplicitConversionSequence::Better;
3628     else if (SCS2.Second == ICK_Identity)
3629       Result = ImplicitConversionSequence::Worse;
3630     else
3631       return ImplicitConversionSequence::Indistinguishable;
3632   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3633     return ImplicitConversionSequence::Indistinguishable;
3634 
3635   if (SCS1.Third == SCS2.Third) {
3636     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3637                              : ImplicitConversionSequence::Indistinguishable;
3638   }
3639 
3640   if (SCS1.Third == ICK_Identity)
3641     return Result == ImplicitConversionSequence::Worse
3642              ? ImplicitConversionSequence::Indistinguishable
3643              : ImplicitConversionSequence::Better;
3644 
3645   if (SCS2.Third == ICK_Identity)
3646     return Result == ImplicitConversionSequence::Better
3647              ? ImplicitConversionSequence::Indistinguishable
3648              : ImplicitConversionSequence::Worse;
3649 
3650   return ImplicitConversionSequence::Indistinguishable;
3651 }
3652 
3653 /// \brief Determine whether one of the given reference bindings is better
3654 /// than the other based on what kind of bindings they are.
3655 static bool
3656 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3657                              const StandardConversionSequence &SCS2) {
3658   // C++0x [over.ics.rank]p3b4:
3659   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3660   //      implicit object parameter of a non-static member function declared
3661   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3662   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3663   //      lvalue reference to a function lvalue and S2 binds an rvalue
3664   //      reference*.
3665   //
3666   // FIXME: Rvalue references. We're going rogue with the above edits,
3667   // because the semantics in the current C++0x working paper (N3225 at the
3668   // time of this writing) break the standard definition of std::forward
3669   // and std::reference_wrapper when dealing with references to functions.
3670   // Proposed wording changes submitted to CWG for consideration.
3671   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3672       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3673     return false;
3674 
3675   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3676           SCS2.IsLvalueReference) ||
3677          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3678           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3679 }
3680 
3681 /// CompareStandardConversionSequences - Compare two standard
3682 /// conversion sequences to determine whether one is better than the
3683 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3684 static ImplicitConversionSequence::CompareKind
3685 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3686                                    const StandardConversionSequence& SCS1,
3687                                    const StandardConversionSequence& SCS2)
3688 {
3689   // Standard conversion sequence S1 is a better conversion sequence
3690   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3691 
3692   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3693   //     sequences in the canonical form defined by 13.3.3.1.1,
3694   //     excluding any Lvalue Transformation; the identity conversion
3695   //     sequence is considered to be a subsequence of any
3696   //     non-identity conversion sequence) or, if not that,
3697   if (ImplicitConversionSequence::CompareKind CK
3698         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3699     return CK;
3700 
3701   //  -- the rank of S1 is better than the rank of S2 (by the rules
3702   //     defined below), or, if not that,
3703   ImplicitConversionRank Rank1 = SCS1.getRank();
3704   ImplicitConversionRank Rank2 = SCS2.getRank();
3705   if (Rank1 < Rank2)
3706     return ImplicitConversionSequence::Better;
3707   else if (Rank2 < Rank1)
3708     return ImplicitConversionSequence::Worse;
3709 
3710   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3711   // are indistinguishable unless one of the following rules
3712   // applies:
3713 
3714   //   A conversion that is not a conversion of a pointer, or
3715   //   pointer to member, to bool is better than another conversion
3716   //   that is such a conversion.
3717   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3718     return SCS2.isPointerConversionToBool()
3719              ? ImplicitConversionSequence::Better
3720              : ImplicitConversionSequence::Worse;
3721 
3722   // C++ [over.ics.rank]p4b2:
3723   //
3724   //   If class B is derived directly or indirectly from class A,
3725   //   conversion of B* to A* is better than conversion of B* to
3726   //   void*, and conversion of A* to void* is better than conversion
3727   //   of B* to void*.
3728   bool SCS1ConvertsToVoid
3729     = SCS1.isPointerConversionToVoidPointer(S.Context);
3730   bool SCS2ConvertsToVoid
3731     = SCS2.isPointerConversionToVoidPointer(S.Context);
3732   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3733     // Exactly one of the conversion sequences is a conversion to
3734     // a void pointer; it's the worse conversion.
3735     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3736                               : ImplicitConversionSequence::Worse;
3737   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3738     // Neither conversion sequence converts to a void pointer; compare
3739     // their derived-to-base conversions.
3740     if (ImplicitConversionSequence::CompareKind DerivedCK
3741           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3742       return DerivedCK;
3743   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3744              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3745     // Both conversion sequences are conversions to void
3746     // pointers. Compare the source types to determine if there's an
3747     // inheritance relationship in their sources.
3748     QualType FromType1 = SCS1.getFromType();
3749     QualType FromType2 = SCS2.getFromType();
3750 
3751     // Adjust the types we're converting from via the array-to-pointer
3752     // conversion, if we need to.
3753     if (SCS1.First == ICK_Array_To_Pointer)
3754       FromType1 = S.Context.getArrayDecayedType(FromType1);
3755     if (SCS2.First == ICK_Array_To_Pointer)
3756       FromType2 = S.Context.getArrayDecayedType(FromType2);
3757 
3758     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3759     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3760 
3761     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3762       return ImplicitConversionSequence::Better;
3763     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3764       return ImplicitConversionSequence::Worse;
3765 
3766     // Objective-C++: If one interface is more specific than the
3767     // other, it is the better one.
3768     const ObjCObjectPointerType* FromObjCPtr1
3769       = FromType1->getAs<ObjCObjectPointerType>();
3770     const ObjCObjectPointerType* FromObjCPtr2
3771       = FromType2->getAs<ObjCObjectPointerType>();
3772     if (FromObjCPtr1 && FromObjCPtr2) {
3773       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3774                                                           FromObjCPtr2);
3775       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3776                                                            FromObjCPtr1);
3777       if (AssignLeft != AssignRight) {
3778         return AssignLeft? ImplicitConversionSequence::Better
3779                          : ImplicitConversionSequence::Worse;
3780       }
3781     }
3782   }
3783 
3784   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3785   // bullet 3).
3786   if (ImplicitConversionSequence::CompareKind QualCK
3787         = CompareQualificationConversions(S, SCS1, SCS2))
3788     return QualCK;
3789 
3790   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3791     // Check for a better reference binding based on the kind of bindings.
3792     if (isBetterReferenceBindingKind(SCS1, SCS2))
3793       return ImplicitConversionSequence::Better;
3794     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3795       return ImplicitConversionSequence::Worse;
3796 
3797     // C++ [over.ics.rank]p3b4:
3798     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3799     //      which the references refer are the same type except for
3800     //      top-level cv-qualifiers, and the type to which the reference
3801     //      initialized by S2 refers is more cv-qualified than the type
3802     //      to which the reference initialized by S1 refers.
3803     QualType T1 = SCS1.getToType(2);
3804     QualType T2 = SCS2.getToType(2);
3805     T1 = S.Context.getCanonicalType(T1);
3806     T2 = S.Context.getCanonicalType(T2);
3807     Qualifiers T1Quals, T2Quals;
3808     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3809     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3810     if (UnqualT1 == UnqualT2) {
3811       // Objective-C++ ARC: If the references refer to objects with different
3812       // lifetimes, prefer bindings that don't change lifetime.
3813       if (SCS1.ObjCLifetimeConversionBinding !=
3814                                           SCS2.ObjCLifetimeConversionBinding) {
3815         return SCS1.ObjCLifetimeConversionBinding
3816                                            ? ImplicitConversionSequence::Worse
3817                                            : ImplicitConversionSequence::Better;
3818       }
3819 
3820       // If the type is an array type, promote the element qualifiers to the
3821       // type for comparison.
3822       if (isa<ArrayType>(T1) && T1Quals)
3823         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3824       if (isa<ArrayType>(T2) && T2Quals)
3825         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3826       if (T2.isMoreQualifiedThan(T1))
3827         return ImplicitConversionSequence::Better;
3828       else if (T1.isMoreQualifiedThan(T2))
3829         return ImplicitConversionSequence::Worse;
3830     }
3831   }
3832 
3833   // In Microsoft mode, prefer an integral conversion to a
3834   // floating-to-integral conversion if the integral conversion
3835   // is between types of the same size.
3836   // For example:
3837   // void f(float);
3838   // void f(int);
3839   // int main {
3840   //    long a;
3841   //    f(a);
3842   // }
3843   // Here, MSVC will call f(int) instead of generating a compile error
3844   // as clang will do in standard mode.
3845   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3846       SCS2.Second == ICK_Floating_Integral &&
3847       S.Context.getTypeSize(SCS1.getFromType()) ==
3848           S.Context.getTypeSize(SCS1.getToType(2)))
3849     return ImplicitConversionSequence::Better;
3850 
3851   return ImplicitConversionSequence::Indistinguishable;
3852 }
3853 
3854 /// CompareQualificationConversions - Compares two standard conversion
3855 /// sequences to determine whether they can be ranked based on their
3856 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3857 static ImplicitConversionSequence::CompareKind
3858 CompareQualificationConversions(Sema &S,
3859                                 const StandardConversionSequence& SCS1,
3860                                 const StandardConversionSequence& SCS2) {
3861   // C++ 13.3.3.2p3:
3862   //  -- S1 and S2 differ only in their qualification conversion and
3863   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3864   //     cv-qualification signature of type T1 is a proper subset of
3865   //     the cv-qualification signature of type T2, and S1 is not the
3866   //     deprecated string literal array-to-pointer conversion (4.2).
3867   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3868       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3869     return ImplicitConversionSequence::Indistinguishable;
3870 
3871   // FIXME: the example in the standard doesn't use a qualification
3872   // conversion (!)
3873   QualType T1 = SCS1.getToType(2);
3874   QualType T2 = SCS2.getToType(2);
3875   T1 = S.Context.getCanonicalType(T1);
3876   T2 = S.Context.getCanonicalType(T2);
3877   Qualifiers T1Quals, T2Quals;
3878   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3879   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3880 
3881   // If the types are the same, we won't learn anything by unwrapped
3882   // them.
3883   if (UnqualT1 == UnqualT2)
3884     return ImplicitConversionSequence::Indistinguishable;
3885 
3886   // If the type is an array type, promote the element qualifiers to the type
3887   // for comparison.
3888   if (isa<ArrayType>(T1) && T1Quals)
3889     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3890   if (isa<ArrayType>(T2) && T2Quals)
3891     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3892 
3893   ImplicitConversionSequence::CompareKind Result
3894     = ImplicitConversionSequence::Indistinguishable;
3895 
3896   // Objective-C++ ARC:
3897   //   Prefer qualification conversions not involving a change in lifetime
3898   //   to qualification conversions that do not change lifetime.
3899   if (SCS1.QualificationIncludesObjCLifetime !=
3900                                       SCS2.QualificationIncludesObjCLifetime) {
3901     Result = SCS1.QualificationIncludesObjCLifetime
3902                ? ImplicitConversionSequence::Worse
3903                : ImplicitConversionSequence::Better;
3904   }
3905 
3906   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3907     // Within each iteration of the loop, we check the qualifiers to
3908     // determine if this still looks like a qualification
3909     // conversion. Then, if all is well, we unwrap one more level of
3910     // pointers or pointers-to-members and do it all again
3911     // until there are no more pointers or pointers-to-members left
3912     // to unwrap. This essentially mimics what
3913     // IsQualificationConversion does, but here we're checking for a
3914     // strict subset of qualifiers.
3915     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3916       // The qualifiers are the same, so this doesn't tell us anything
3917       // about how the sequences rank.
3918       ;
3919     else if (T2.isMoreQualifiedThan(T1)) {
3920       // T1 has fewer qualifiers, so it could be the better sequence.
3921       if (Result == ImplicitConversionSequence::Worse)
3922         // Neither has qualifiers that are a subset of the other's
3923         // qualifiers.
3924         return ImplicitConversionSequence::Indistinguishable;
3925 
3926       Result = ImplicitConversionSequence::Better;
3927     } else if (T1.isMoreQualifiedThan(T2)) {
3928       // T2 has fewer qualifiers, so it could be the better sequence.
3929       if (Result == ImplicitConversionSequence::Better)
3930         // Neither has qualifiers that are a subset of the other's
3931         // qualifiers.
3932         return ImplicitConversionSequence::Indistinguishable;
3933 
3934       Result = ImplicitConversionSequence::Worse;
3935     } else {
3936       // Qualifiers are disjoint.
3937       return ImplicitConversionSequence::Indistinguishable;
3938     }
3939 
3940     // If the types after this point are equivalent, we're done.
3941     if (S.Context.hasSameUnqualifiedType(T1, T2))
3942       break;
3943   }
3944 
3945   // Check that the winning standard conversion sequence isn't using
3946   // the deprecated string literal array to pointer conversion.
3947   switch (Result) {
3948   case ImplicitConversionSequence::Better:
3949     if (SCS1.DeprecatedStringLiteralToCharPtr)
3950       Result = ImplicitConversionSequence::Indistinguishable;
3951     break;
3952 
3953   case ImplicitConversionSequence::Indistinguishable:
3954     break;
3955 
3956   case ImplicitConversionSequence::Worse:
3957     if (SCS2.DeprecatedStringLiteralToCharPtr)
3958       Result = ImplicitConversionSequence::Indistinguishable;
3959     break;
3960   }
3961 
3962   return Result;
3963 }
3964 
3965 /// CompareDerivedToBaseConversions - Compares two standard conversion
3966 /// sequences to determine whether they can be ranked based on their
3967 /// various kinds of derived-to-base conversions (C++
3968 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3969 /// conversions between Objective-C interface types.
3970 static ImplicitConversionSequence::CompareKind
3971 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3972                                 const StandardConversionSequence& SCS1,
3973                                 const StandardConversionSequence& SCS2) {
3974   QualType FromType1 = SCS1.getFromType();
3975   QualType ToType1 = SCS1.getToType(1);
3976   QualType FromType2 = SCS2.getFromType();
3977   QualType ToType2 = SCS2.getToType(1);
3978 
3979   // Adjust the types we're converting from via the array-to-pointer
3980   // conversion, if we need to.
3981   if (SCS1.First == ICK_Array_To_Pointer)
3982     FromType1 = S.Context.getArrayDecayedType(FromType1);
3983   if (SCS2.First == ICK_Array_To_Pointer)
3984     FromType2 = S.Context.getArrayDecayedType(FromType2);
3985 
3986   // Canonicalize all of the types.
3987   FromType1 = S.Context.getCanonicalType(FromType1);
3988   ToType1 = S.Context.getCanonicalType(ToType1);
3989   FromType2 = S.Context.getCanonicalType(FromType2);
3990   ToType2 = S.Context.getCanonicalType(ToType2);
3991 
3992   // C++ [over.ics.rank]p4b3:
3993   //
3994   //   If class B is derived directly or indirectly from class A and
3995   //   class C is derived directly or indirectly from B,
3996   //
3997   // Compare based on pointer conversions.
3998   if (SCS1.Second == ICK_Pointer_Conversion &&
3999       SCS2.Second == ICK_Pointer_Conversion &&
4000       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4001       FromType1->isPointerType() && FromType2->isPointerType() &&
4002       ToType1->isPointerType() && ToType2->isPointerType()) {
4003     QualType FromPointee1
4004       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4005     QualType ToPointee1
4006       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4007     QualType FromPointee2
4008       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4009     QualType ToPointee2
4010       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4011 
4012     //   -- conversion of C* to B* is better than conversion of C* to A*,
4013     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4014       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4015         return ImplicitConversionSequence::Better;
4016       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4017         return ImplicitConversionSequence::Worse;
4018     }
4019 
4020     //   -- conversion of B* to A* is better than conversion of C* to A*,
4021     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4022       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4023         return ImplicitConversionSequence::Better;
4024       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4025         return ImplicitConversionSequence::Worse;
4026     }
4027   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4028              SCS2.Second == ICK_Pointer_Conversion) {
4029     const ObjCObjectPointerType *FromPtr1
4030       = FromType1->getAs<ObjCObjectPointerType>();
4031     const ObjCObjectPointerType *FromPtr2
4032       = FromType2->getAs<ObjCObjectPointerType>();
4033     const ObjCObjectPointerType *ToPtr1
4034       = ToType1->getAs<ObjCObjectPointerType>();
4035     const ObjCObjectPointerType *ToPtr2
4036       = ToType2->getAs<ObjCObjectPointerType>();
4037 
4038     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4039       // Apply the same conversion ranking rules for Objective-C pointer types
4040       // that we do for C++ pointers to class types. However, we employ the
4041       // Objective-C pseudo-subtyping relationship used for assignment of
4042       // Objective-C pointer types.
4043       bool FromAssignLeft
4044         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4045       bool FromAssignRight
4046         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4047       bool ToAssignLeft
4048         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4049       bool ToAssignRight
4050         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4051 
4052       // A conversion to an a non-id object pointer type or qualified 'id'
4053       // type is better than a conversion to 'id'.
4054       if (ToPtr1->isObjCIdType() &&
4055           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4056         return ImplicitConversionSequence::Worse;
4057       if (ToPtr2->isObjCIdType() &&
4058           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4059         return ImplicitConversionSequence::Better;
4060 
4061       // A conversion to a non-id object pointer type is better than a
4062       // conversion to a qualified 'id' type
4063       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4064         return ImplicitConversionSequence::Worse;
4065       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4066         return ImplicitConversionSequence::Better;
4067 
4068       // A conversion to an a non-Class object pointer type or qualified 'Class'
4069       // type is better than a conversion to 'Class'.
4070       if (ToPtr1->isObjCClassType() &&
4071           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4072         return ImplicitConversionSequence::Worse;
4073       if (ToPtr2->isObjCClassType() &&
4074           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4075         return ImplicitConversionSequence::Better;
4076 
4077       // A conversion to a non-Class object pointer type is better than a
4078       // conversion to a qualified 'Class' type.
4079       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4080         return ImplicitConversionSequence::Worse;
4081       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4082         return ImplicitConversionSequence::Better;
4083 
4084       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4085       if (S.Context.hasSameType(FromType1, FromType2) &&
4086           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4087           (ToAssignLeft != ToAssignRight))
4088         return ToAssignLeft? ImplicitConversionSequence::Worse
4089                            : ImplicitConversionSequence::Better;
4090 
4091       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4092       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4093           (FromAssignLeft != FromAssignRight))
4094         return FromAssignLeft? ImplicitConversionSequence::Better
4095         : ImplicitConversionSequence::Worse;
4096     }
4097   }
4098 
4099   // Ranking of member-pointer types.
4100   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4101       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4102       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4103     const MemberPointerType * FromMemPointer1 =
4104                                         FromType1->getAs<MemberPointerType>();
4105     const MemberPointerType * ToMemPointer1 =
4106                                           ToType1->getAs<MemberPointerType>();
4107     const MemberPointerType * FromMemPointer2 =
4108                                           FromType2->getAs<MemberPointerType>();
4109     const MemberPointerType * ToMemPointer2 =
4110                                           ToType2->getAs<MemberPointerType>();
4111     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4112     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4113     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4114     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4115     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4116     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4117     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4118     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4119     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4120     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4121       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4122         return ImplicitConversionSequence::Worse;
4123       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4124         return ImplicitConversionSequence::Better;
4125     }
4126     // conversion of B::* to C::* is better than conversion of A::* to C::*
4127     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4128       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4129         return ImplicitConversionSequence::Better;
4130       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4131         return ImplicitConversionSequence::Worse;
4132     }
4133   }
4134 
4135   if (SCS1.Second == ICK_Derived_To_Base) {
4136     //   -- conversion of C to B is better than conversion of C to A,
4137     //   -- binding of an expression of type C to a reference of type
4138     //      B& is better than binding an expression of type C to a
4139     //      reference of type A&,
4140     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4141         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4142       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4143         return ImplicitConversionSequence::Better;
4144       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4145         return ImplicitConversionSequence::Worse;
4146     }
4147 
4148     //   -- conversion of B to A is better than conversion of C to A.
4149     //   -- binding of an expression of type B to a reference of type
4150     //      A& is better than binding an expression of type C to a
4151     //      reference of type A&,
4152     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4153         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4154       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4155         return ImplicitConversionSequence::Better;
4156       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4157         return ImplicitConversionSequence::Worse;
4158     }
4159   }
4160 
4161   return ImplicitConversionSequence::Indistinguishable;
4162 }
4163 
4164 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4165 /// C++ class.
4166 static bool isTypeValid(QualType T) {
4167   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4168     return !Record->isInvalidDecl();
4169 
4170   return true;
4171 }
4172 
4173 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4174 /// determine whether they are reference-related,
4175 /// reference-compatible, reference-compatible with added
4176 /// qualification, or incompatible, for use in C++ initialization by
4177 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4178 /// type, and the first type (T1) is the pointee type of the reference
4179 /// type being initialized.
4180 Sema::ReferenceCompareResult
4181 Sema::CompareReferenceRelationship(SourceLocation Loc,
4182                                    QualType OrigT1, QualType OrigT2,
4183                                    bool &DerivedToBase,
4184                                    bool &ObjCConversion,
4185                                    bool &ObjCLifetimeConversion) {
4186   assert(!OrigT1->isReferenceType() &&
4187     "T1 must be the pointee type of the reference type");
4188   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4189 
4190   QualType T1 = Context.getCanonicalType(OrigT1);
4191   QualType T2 = Context.getCanonicalType(OrigT2);
4192   Qualifiers T1Quals, T2Quals;
4193   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4194   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4195 
4196   // C++ [dcl.init.ref]p4:
4197   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4198   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4199   //   T1 is a base class of T2.
4200   DerivedToBase = false;
4201   ObjCConversion = false;
4202   ObjCLifetimeConversion = false;
4203   QualType ConvertedT2;
4204   if (UnqualT1 == UnqualT2) {
4205     // Nothing to do.
4206   } else if (isCompleteType(Loc, OrigT2) &&
4207              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4208              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4209     DerivedToBase = true;
4210   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4211            UnqualT2->isObjCObjectOrInterfaceType() &&
4212            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4213     ObjCConversion = true;
4214   else if (UnqualT2->isFunctionType() &&
4215            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4216     // C++1z [dcl.init.ref]p4:
4217     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4218     //   function" and T1 is "function"
4219     //
4220     // We extend this to also apply to 'noreturn', so allow any function
4221     // conversion between function types.
4222     return Ref_Compatible;
4223   else
4224     return Ref_Incompatible;
4225 
4226   // At this point, we know that T1 and T2 are reference-related (at
4227   // least).
4228 
4229   // If the type is an array type, promote the element qualifiers to the type
4230   // for comparison.
4231   if (isa<ArrayType>(T1) && T1Quals)
4232     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4233   if (isa<ArrayType>(T2) && T2Quals)
4234     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4235 
4236   // C++ [dcl.init.ref]p4:
4237   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4238   //   reference-related to T2 and cv1 is the same cv-qualification
4239   //   as, or greater cv-qualification than, cv2. For purposes of
4240   //   overload resolution, cases for which cv1 is greater
4241   //   cv-qualification than cv2 are identified as
4242   //   reference-compatible with added qualification (see 13.3.3.2).
4243   //
4244   // Note that we also require equivalence of Objective-C GC and address-space
4245   // qualifiers when performing these computations, so that e.g., an int in
4246   // address space 1 is not reference-compatible with an int in address
4247   // space 2.
4248   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4249       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4250     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4251       ObjCLifetimeConversion = true;
4252 
4253     T1Quals.removeObjCLifetime();
4254     T2Quals.removeObjCLifetime();
4255   }
4256 
4257   // MS compiler ignores __unaligned qualifier for references; do the same.
4258   T1Quals.removeUnaligned();
4259   T2Quals.removeUnaligned();
4260 
4261   if (T1Quals.compatiblyIncludes(T2Quals))
4262     return Ref_Compatible;
4263   else
4264     return Ref_Related;
4265 }
4266 
4267 /// \brief Look for a user-defined conversion to a value reference-compatible
4268 ///        with DeclType. Return true if something definite is found.
4269 static bool
4270 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4271                          QualType DeclType, SourceLocation DeclLoc,
4272                          Expr *Init, QualType T2, bool AllowRvalues,
4273                          bool AllowExplicit) {
4274   assert(T2->isRecordType() && "Can only find conversions of record types.");
4275   CXXRecordDecl *T2RecordDecl
4276     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4277 
4278   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4279   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4280   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4281     NamedDecl *D = *I;
4282     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4283     if (isa<UsingShadowDecl>(D))
4284       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4285 
4286     FunctionTemplateDecl *ConvTemplate
4287       = dyn_cast<FunctionTemplateDecl>(D);
4288     CXXConversionDecl *Conv;
4289     if (ConvTemplate)
4290       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4291     else
4292       Conv = cast<CXXConversionDecl>(D);
4293 
4294     // If this is an explicit conversion, and we're not allowed to consider
4295     // explicit conversions, skip it.
4296     if (!AllowExplicit && Conv->isExplicit())
4297       continue;
4298 
4299     if (AllowRvalues) {
4300       bool DerivedToBase = false;
4301       bool ObjCConversion = false;
4302       bool ObjCLifetimeConversion = false;
4303 
4304       // If we are initializing an rvalue reference, don't permit conversion
4305       // functions that return lvalues.
4306       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4307         const ReferenceType *RefType
4308           = Conv->getConversionType()->getAs<LValueReferenceType>();
4309         if (RefType && !RefType->getPointeeType()->isFunctionType())
4310           continue;
4311       }
4312 
4313       if (!ConvTemplate &&
4314           S.CompareReferenceRelationship(
4315             DeclLoc,
4316             Conv->getConversionType().getNonReferenceType()
4317               .getUnqualifiedType(),
4318             DeclType.getNonReferenceType().getUnqualifiedType(),
4319             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4320           Sema::Ref_Incompatible)
4321         continue;
4322     } else {
4323       // If the conversion function doesn't return a reference type,
4324       // it can't be considered for this conversion. An rvalue reference
4325       // is only acceptable if its referencee is a function type.
4326 
4327       const ReferenceType *RefType =
4328         Conv->getConversionType()->getAs<ReferenceType>();
4329       if (!RefType ||
4330           (!RefType->isLValueReferenceType() &&
4331            !RefType->getPointeeType()->isFunctionType()))
4332         continue;
4333     }
4334 
4335     if (ConvTemplate)
4336       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4337                                        Init, DeclType, CandidateSet,
4338                                        /*AllowObjCConversionOnExplicit=*/false);
4339     else
4340       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4341                                DeclType, CandidateSet,
4342                                /*AllowObjCConversionOnExplicit=*/false);
4343   }
4344 
4345   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4346 
4347   OverloadCandidateSet::iterator Best;
4348   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4349   case OR_Success:
4350     // C++ [over.ics.ref]p1:
4351     //
4352     //   [...] If the parameter binds directly to the result of
4353     //   applying a conversion function to the argument
4354     //   expression, the implicit conversion sequence is a
4355     //   user-defined conversion sequence (13.3.3.1.2), with the
4356     //   second standard conversion sequence either an identity
4357     //   conversion or, if the conversion function returns an
4358     //   entity of a type that is a derived class of the parameter
4359     //   type, a derived-to-base Conversion.
4360     if (!Best->FinalConversion.DirectBinding)
4361       return false;
4362 
4363     ICS.setUserDefined();
4364     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4365     ICS.UserDefined.After = Best->FinalConversion;
4366     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4367     ICS.UserDefined.ConversionFunction = Best->Function;
4368     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4369     ICS.UserDefined.EllipsisConversion = false;
4370     assert(ICS.UserDefined.After.ReferenceBinding &&
4371            ICS.UserDefined.After.DirectBinding &&
4372            "Expected a direct reference binding!");
4373     return true;
4374 
4375   case OR_Ambiguous:
4376     ICS.setAmbiguous();
4377     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4378          Cand != CandidateSet.end(); ++Cand)
4379       if (Cand->Viable)
4380         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4381     return true;
4382 
4383   case OR_No_Viable_Function:
4384   case OR_Deleted:
4385     // There was no suitable conversion, or we found a deleted
4386     // conversion; continue with other checks.
4387     return false;
4388   }
4389 
4390   llvm_unreachable("Invalid OverloadResult!");
4391 }
4392 
4393 /// \brief Compute an implicit conversion sequence for reference
4394 /// initialization.
4395 static ImplicitConversionSequence
4396 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4397                  SourceLocation DeclLoc,
4398                  bool SuppressUserConversions,
4399                  bool AllowExplicit) {
4400   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4401 
4402   // Most paths end in a failed conversion.
4403   ImplicitConversionSequence ICS;
4404   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4405 
4406   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4407   QualType T2 = Init->getType();
4408 
4409   // If the initializer is the address of an overloaded function, try
4410   // to resolve the overloaded function. If all goes well, T2 is the
4411   // type of the resulting function.
4412   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4413     DeclAccessPair Found;
4414     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4415                                                                 false, Found))
4416       T2 = Fn->getType();
4417   }
4418 
4419   // Compute some basic properties of the types and the initializer.
4420   bool isRValRef = DeclType->isRValueReferenceType();
4421   bool DerivedToBase = false;
4422   bool ObjCConversion = false;
4423   bool ObjCLifetimeConversion = false;
4424   Expr::Classification InitCategory = Init->Classify(S.Context);
4425   Sema::ReferenceCompareResult RefRelationship
4426     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4427                                      ObjCConversion, ObjCLifetimeConversion);
4428 
4429 
4430   // C++0x [dcl.init.ref]p5:
4431   //   A reference to type "cv1 T1" is initialized by an expression
4432   //   of type "cv2 T2" as follows:
4433 
4434   //     -- If reference is an lvalue reference and the initializer expression
4435   if (!isRValRef) {
4436     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4437     //        reference-compatible with "cv2 T2," or
4438     //
4439     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4440     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4441       // C++ [over.ics.ref]p1:
4442       //   When a parameter of reference type binds directly (8.5.3)
4443       //   to an argument expression, the implicit conversion sequence
4444       //   is the identity conversion, unless the argument expression
4445       //   has a type that is a derived class of the parameter type,
4446       //   in which case the implicit conversion sequence is a
4447       //   derived-to-base Conversion (13.3.3.1).
4448       ICS.setStandard();
4449       ICS.Standard.First = ICK_Identity;
4450       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4451                          : ObjCConversion? ICK_Compatible_Conversion
4452                          : ICK_Identity;
4453       ICS.Standard.Third = ICK_Identity;
4454       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4455       ICS.Standard.setToType(0, T2);
4456       ICS.Standard.setToType(1, T1);
4457       ICS.Standard.setToType(2, T1);
4458       ICS.Standard.ReferenceBinding = true;
4459       ICS.Standard.DirectBinding = true;
4460       ICS.Standard.IsLvalueReference = !isRValRef;
4461       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4462       ICS.Standard.BindsToRvalue = false;
4463       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4464       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4465       ICS.Standard.CopyConstructor = nullptr;
4466       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4467 
4468       // Nothing more to do: the inaccessibility/ambiguity check for
4469       // derived-to-base conversions is suppressed when we're
4470       // computing the implicit conversion sequence (C++
4471       // [over.best.ics]p2).
4472       return ICS;
4473     }
4474 
4475     //       -- has a class type (i.e., T2 is a class type), where T1 is
4476     //          not reference-related to T2, and can be implicitly
4477     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4478     //          is reference-compatible with "cv3 T3" 92) (this
4479     //          conversion is selected by enumerating the applicable
4480     //          conversion functions (13.3.1.6) and choosing the best
4481     //          one through overload resolution (13.3)),
4482     if (!SuppressUserConversions && T2->isRecordType() &&
4483         S.isCompleteType(DeclLoc, T2) &&
4484         RefRelationship == Sema::Ref_Incompatible) {
4485       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4486                                    Init, T2, /*AllowRvalues=*/false,
4487                                    AllowExplicit))
4488         return ICS;
4489     }
4490   }
4491 
4492   //     -- Otherwise, the reference shall be an lvalue reference to a
4493   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4494   //        shall be an rvalue reference.
4495   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4496     return ICS;
4497 
4498   //       -- If the initializer expression
4499   //
4500   //            -- is an xvalue, class prvalue, array prvalue or function
4501   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4502   if (RefRelationship == Sema::Ref_Compatible &&
4503       (InitCategory.isXValue() ||
4504        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4505        (InitCategory.isLValue() && T2->isFunctionType()))) {
4506     ICS.setStandard();
4507     ICS.Standard.First = ICK_Identity;
4508     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4509                       : ObjCConversion? ICK_Compatible_Conversion
4510                       : ICK_Identity;
4511     ICS.Standard.Third = ICK_Identity;
4512     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4513     ICS.Standard.setToType(0, T2);
4514     ICS.Standard.setToType(1, T1);
4515     ICS.Standard.setToType(2, T1);
4516     ICS.Standard.ReferenceBinding = true;
4517     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4518     // binding unless we're binding to a class prvalue.
4519     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4520     // allow the use of rvalue references in C++98/03 for the benefit of
4521     // standard library implementors; therefore, we need the xvalue check here.
4522     ICS.Standard.DirectBinding =
4523       S.getLangOpts().CPlusPlus11 ||
4524       !(InitCategory.isPRValue() || T2->isRecordType());
4525     ICS.Standard.IsLvalueReference = !isRValRef;
4526     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4527     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4528     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4529     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4530     ICS.Standard.CopyConstructor = nullptr;
4531     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4532     return ICS;
4533   }
4534 
4535   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4536   //               reference-related to T2, and can be implicitly converted to
4537   //               an xvalue, class prvalue, or function lvalue of type
4538   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4539   //               "cv3 T3",
4540   //
4541   //          then the reference is bound to the value of the initializer
4542   //          expression in the first case and to the result of the conversion
4543   //          in the second case (or, in either case, to an appropriate base
4544   //          class subobject).
4545   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4546       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4547       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4548                                Init, T2, /*AllowRvalues=*/true,
4549                                AllowExplicit)) {
4550     // In the second case, if the reference is an rvalue reference
4551     // and the second standard conversion sequence of the
4552     // user-defined conversion sequence includes an lvalue-to-rvalue
4553     // conversion, the program is ill-formed.
4554     if (ICS.isUserDefined() && isRValRef &&
4555         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4556       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4557 
4558     return ICS;
4559   }
4560 
4561   // A temporary of function type cannot be created; don't even try.
4562   if (T1->isFunctionType())
4563     return ICS;
4564 
4565   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4566   //          initialized from the initializer expression using the
4567   //          rules for a non-reference copy initialization (8.5). The
4568   //          reference is then bound to the temporary. If T1 is
4569   //          reference-related to T2, cv1 must be the same
4570   //          cv-qualification as, or greater cv-qualification than,
4571   //          cv2; otherwise, the program is ill-formed.
4572   if (RefRelationship == Sema::Ref_Related) {
4573     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4574     // we would be reference-compatible or reference-compatible with
4575     // added qualification. But that wasn't the case, so the reference
4576     // initialization fails.
4577     //
4578     // Note that we only want to check address spaces and cvr-qualifiers here.
4579     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4580     Qualifiers T1Quals = T1.getQualifiers();
4581     Qualifiers T2Quals = T2.getQualifiers();
4582     T1Quals.removeObjCGCAttr();
4583     T1Quals.removeObjCLifetime();
4584     T2Quals.removeObjCGCAttr();
4585     T2Quals.removeObjCLifetime();
4586     // MS compiler ignores __unaligned qualifier for references; do the same.
4587     T1Quals.removeUnaligned();
4588     T2Quals.removeUnaligned();
4589     if (!T1Quals.compatiblyIncludes(T2Quals))
4590       return ICS;
4591   }
4592 
4593   // If at least one of the types is a class type, the types are not
4594   // related, and we aren't allowed any user conversions, the
4595   // reference binding fails. This case is important for breaking
4596   // recursion, since TryImplicitConversion below will attempt to
4597   // create a temporary through the use of a copy constructor.
4598   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4599       (T1->isRecordType() || T2->isRecordType()))
4600     return ICS;
4601 
4602   // If T1 is reference-related to T2 and the reference is an rvalue
4603   // reference, the initializer expression shall not be an lvalue.
4604   if (RefRelationship >= Sema::Ref_Related &&
4605       isRValRef && Init->Classify(S.Context).isLValue())
4606     return ICS;
4607 
4608   // C++ [over.ics.ref]p2:
4609   //   When a parameter of reference type is not bound directly to
4610   //   an argument expression, the conversion sequence is the one
4611   //   required to convert the argument expression to the
4612   //   underlying type of the reference according to
4613   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4614   //   to copy-initializing a temporary of the underlying type with
4615   //   the argument expression. Any difference in top-level
4616   //   cv-qualification is subsumed by the initialization itself
4617   //   and does not constitute a conversion.
4618   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4619                               /*AllowExplicit=*/false,
4620                               /*InOverloadResolution=*/false,
4621                               /*CStyle=*/false,
4622                               /*AllowObjCWritebackConversion=*/false,
4623                               /*AllowObjCConversionOnExplicit=*/false);
4624 
4625   // Of course, that's still a reference binding.
4626   if (ICS.isStandard()) {
4627     ICS.Standard.ReferenceBinding = true;
4628     ICS.Standard.IsLvalueReference = !isRValRef;
4629     ICS.Standard.BindsToFunctionLvalue = false;
4630     ICS.Standard.BindsToRvalue = true;
4631     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4632     ICS.Standard.ObjCLifetimeConversionBinding = false;
4633   } else if (ICS.isUserDefined()) {
4634     const ReferenceType *LValRefType =
4635         ICS.UserDefined.ConversionFunction->getReturnType()
4636             ->getAs<LValueReferenceType>();
4637 
4638     // C++ [over.ics.ref]p3:
4639     //   Except for an implicit object parameter, for which see 13.3.1, a
4640     //   standard conversion sequence cannot be formed if it requires [...]
4641     //   binding an rvalue reference to an lvalue other than a function
4642     //   lvalue.
4643     // Note that the function case is not possible here.
4644     if (DeclType->isRValueReferenceType() && LValRefType) {
4645       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4646       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4647       // reference to an rvalue!
4648       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4649       return ICS;
4650     }
4651 
4652     ICS.UserDefined.After.ReferenceBinding = true;
4653     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4654     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4655     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4656     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4657     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4658   }
4659 
4660   return ICS;
4661 }
4662 
4663 static ImplicitConversionSequence
4664 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4665                       bool SuppressUserConversions,
4666                       bool InOverloadResolution,
4667                       bool AllowObjCWritebackConversion,
4668                       bool AllowExplicit = false);
4669 
4670 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4671 /// initializer list From.
4672 static ImplicitConversionSequence
4673 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4674                   bool SuppressUserConversions,
4675                   bool InOverloadResolution,
4676                   bool AllowObjCWritebackConversion) {
4677   // C++11 [over.ics.list]p1:
4678   //   When an argument is an initializer list, it is not an expression and
4679   //   special rules apply for converting it to a parameter type.
4680 
4681   ImplicitConversionSequence Result;
4682   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4683 
4684   // We need a complete type for what follows. Incomplete types can never be
4685   // initialized from init lists.
4686   if (!S.isCompleteType(From->getLocStart(), ToType))
4687     return Result;
4688 
4689   // Per DR1467:
4690   //   If the parameter type is a class X and the initializer list has a single
4691   //   element of type cv U, where U is X or a class derived from X, the
4692   //   implicit conversion sequence is the one required to convert the element
4693   //   to the parameter type.
4694   //
4695   //   Otherwise, if the parameter type is a character array [... ]
4696   //   and the initializer list has a single element that is an
4697   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4698   //   implicit conversion sequence is the identity conversion.
4699   if (From->getNumInits() == 1) {
4700     if (ToType->isRecordType()) {
4701       QualType InitType = From->getInit(0)->getType();
4702       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4703           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4704         return TryCopyInitialization(S, From->getInit(0), ToType,
4705                                      SuppressUserConversions,
4706                                      InOverloadResolution,
4707                                      AllowObjCWritebackConversion);
4708     }
4709     // FIXME: Check the other conditions here: array of character type,
4710     // initializer is a string literal.
4711     if (ToType->isArrayType()) {
4712       InitializedEntity Entity =
4713         InitializedEntity::InitializeParameter(S.Context, ToType,
4714                                                /*Consumed=*/false);
4715       if (S.CanPerformCopyInitialization(Entity, From)) {
4716         Result.setStandard();
4717         Result.Standard.setAsIdentityConversion();
4718         Result.Standard.setFromType(ToType);
4719         Result.Standard.setAllToTypes(ToType);
4720         return Result;
4721       }
4722     }
4723   }
4724 
4725   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4726   // C++11 [over.ics.list]p2:
4727   //   If the parameter type is std::initializer_list<X> or "array of X" and
4728   //   all the elements can be implicitly converted to X, the implicit
4729   //   conversion sequence is the worst conversion necessary to convert an
4730   //   element of the list to X.
4731   //
4732   // C++14 [over.ics.list]p3:
4733   //   Otherwise, if the parameter type is "array of N X", if the initializer
4734   //   list has exactly N elements or if it has fewer than N elements and X is
4735   //   default-constructible, and if all the elements of the initializer list
4736   //   can be implicitly converted to X, the implicit conversion sequence is
4737   //   the worst conversion necessary to convert an element of the list to X.
4738   //
4739   // FIXME: We're missing a lot of these checks.
4740   bool toStdInitializerList = false;
4741   QualType X;
4742   if (ToType->isArrayType())
4743     X = S.Context.getAsArrayType(ToType)->getElementType();
4744   else
4745     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4746   if (!X.isNull()) {
4747     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4748       Expr *Init = From->getInit(i);
4749       ImplicitConversionSequence ICS =
4750           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4751                                 InOverloadResolution,
4752                                 AllowObjCWritebackConversion);
4753       // If a single element isn't convertible, fail.
4754       if (ICS.isBad()) {
4755         Result = ICS;
4756         break;
4757       }
4758       // Otherwise, look for the worst conversion.
4759       if (Result.isBad() ||
4760           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4761                                              Result) ==
4762               ImplicitConversionSequence::Worse)
4763         Result = ICS;
4764     }
4765 
4766     // For an empty list, we won't have computed any conversion sequence.
4767     // Introduce the identity conversion sequence.
4768     if (From->getNumInits() == 0) {
4769       Result.setStandard();
4770       Result.Standard.setAsIdentityConversion();
4771       Result.Standard.setFromType(ToType);
4772       Result.Standard.setAllToTypes(ToType);
4773     }
4774 
4775     Result.setStdInitializerListElement(toStdInitializerList);
4776     return Result;
4777   }
4778 
4779   // C++14 [over.ics.list]p4:
4780   // C++11 [over.ics.list]p3:
4781   //   Otherwise, if the parameter is a non-aggregate class X and overload
4782   //   resolution chooses a single best constructor [...] the implicit
4783   //   conversion sequence is a user-defined conversion sequence. If multiple
4784   //   constructors are viable but none is better than the others, the
4785   //   implicit conversion sequence is a user-defined conversion sequence.
4786   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4787     // This function can deal with initializer lists.
4788     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4789                                     /*AllowExplicit=*/false,
4790                                     InOverloadResolution, /*CStyle=*/false,
4791                                     AllowObjCWritebackConversion,
4792                                     /*AllowObjCConversionOnExplicit=*/false);
4793   }
4794 
4795   // C++14 [over.ics.list]p5:
4796   // C++11 [over.ics.list]p4:
4797   //   Otherwise, if the parameter has an aggregate type which can be
4798   //   initialized from the initializer list [...] the implicit conversion
4799   //   sequence is a user-defined conversion sequence.
4800   if (ToType->isAggregateType()) {
4801     // Type is an aggregate, argument is an init list. At this point it comes
4802     // down to checking whether the initialization works.
4803     // FIXME: Find out whether this parameter is consumed or not.
4804     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4805     // need to call into the initialization code here; overload resolution
4806     // should not be doing that.
4807     InitializedEntity Entity =
4808         InitializedEntity::InitializeParameter(S.Context, ToType,
4809                                                /*Consumed=*/false);
4810     if (S.CanPerformCopyInitialization(Entity, From)) {
4811       Result.setUserDefined();
4812       Result.UserDefined.Before.setAsIdentityConversion();
4813       // Initializer lists don't have a type.
4814       Result.UserDefined.Before.setFromType(QualType());
4815       Result.UserDefined.Before.setAllToTypes(QualType());
4816 
4817       Result.UserDefined.After.setAsIdentityConversion();
4818       Result.UserDefined.After.setFromType(ToType);
4819       Result.UserDefined.After.setAllToTypes(ToType);
4820       Result.UserDefined.ConversionFunction = nullptr;
4821     }
4822     return Result;
4823   }
4824 
4825   // C++14 [over.ics.list]p6:
4826   // C++11 [over.ics.list]p5:
4827   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4828   if (ToType->isReferenceType()) {
4829     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4830     // mention initializer lists in any way. So we go by what list-
4831     // initialization would do and try to extrapolate from that.
4832 
4833     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4834 
4835     // If the initializer list has a single element that is reference-related
4836     // to the parameter type, we initialize the reference from that.
4837     if (From->getNumInits() == 1) {
4838       Expr *Init = From->getInit(0);
4839 
4840       QualType T2 = Init->getType();
4841 
4842       // If the initializer is the address of an overloaded function, try
4843       // to resolve the overloaded function. If all goes well, T2 is the
4844       // type of the resulting function.
4845       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4846         DeclAccessPair Found;
4847         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4848                                    Init, ToType, false, Found))
4849           T2 = Fn->getType();
4850       }
4851 
4852       // Compute some basic properties of the types and the initializer.
4853       bool dummy1 = false;
4854       bool dummy2 = false;
4855       bool dummy3 = false;
4856       Sema::ReferenceCompareResult RefRelationship
4857         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4858                                          dummy2, dummy3);
4859 
4860       if (RefRelationship >= Sema::Ref_Related) {
4861         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4862                                 SuppressUserConversions,
4863                                 /*AllowExplicit=*/false);
4864       }
4865     }
4866 
4867     // Otherwise, we bind the reference to a temporary created from the
4868     // initializer list.
4869     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4870                                InOverloadResolution,
4871                                AllowObjCWritebackConversion);
4872     if (Result.isFailure())
4873       return Result;
4874     assert(!Result.isEllipsis() &&
4875            "Sub-initialization cannot result in ellipsis conversion.");
4876 
4877     // Can we even bind to a temporary?
4878     if (ToType->isRValueReferenceType() ||
4879         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4880       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4881                                             Result.UserDefined.After;
4882       SCS.ReferenceBinding = true;
4883       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4884       SCS.BindsToRvalue = true;
4885       SCS.BindsToFunctionLvalue = false;
4886       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4887       SCS.ObjCLifetimeConversionBinding = false;
4888     } else
4889       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4890                     From, ToType);
4891     return Result;
4892   }
4893 
4894   // C++14 [over.ics.list]p7:
4895   // C++11 [over.ics.list]p6:
4896   //   Otherwise, if the parameter type is not a class:
4897   if (!ToType->isRecordType()) {
4898     //    - if the initializer list has one element that is not itself an
4899     //      initializer list, the implicit conversion sequence is the one
4900     //      required to convert the element to the parameter type.
4901     unsigned NumInits = From->getNumInits();
4902     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4903       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4904                                      SuppressUserConversions,
4905                                      InOverloadResolution,
4906                                      AllowObjCWritebackConversion);
4907     //    - if the initializer list has no elements, the implicit conversion
4908     //      sequence is the identity conversion.
4909     else if (NumInits == 0) {
4910       Result.setStandard();
4911       Result.Standard.setAsIdentityConversion();
4912       Result.Standard.setFromType(ToType);
4913       Result.Standard.setAllToTypes(ToType);
4914     }
4915     return Result;
4916   }
4917 
4918   // C++14 [over.ics.list]p8:
4919   // C++11 [over.ics.list]p7:
4920   //   In all cases other than those enumerated above, no conversion is possible
4921   return Result;
4922 }
4923 
4924 /// TryCopyInitialization - Try to copy-initialize a value of type
4925 /// ToType from the expression From. Return the implicit conversion
4926 /// sequence required to pass this argument, which may be a bad
4927 /// conversion sequence (meaning that the argument cannot be passed to
4928 /// a parameter of this type). If @p SuppressUserConversions, then we
4929 /// do not permit any user-defined conversion sequences.
4930 static ImplicitConversionSequence
4931 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4932                       bool SuppressUserConversions,
4933                       bool InOverloadResolution,
4934                       bool AllowObjCWritebackConversion,
4935                       bool AllowExplicit) {
4936   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4937     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4938                              InOverloadResolution,AllowObjCWritebackConversion);
4939 
4940   if (ToType->isReferenceType())
4941     return TryReferenceInit(S, From, ToType,
4942                             /*FIXME:*/From->getLocStart(),
4943                             SuppressUserConversions,
4944                             AllowExplicit);
4945 
4946   return TryImplicitConversion(S, From, ToType,
4947                                SuppressUserConversions,
4948                                /*AllowExplicit=*/false,
4949                                InOverloadResolution,
4950                                /*CStyle=*/false,
4951                                AllowObjCWritebackConversion,
4952                                /*AllowObjCConversionOnExplicit=*/false);
4953 }
4954 
4955 static bool TryCopyInitialization(const CanQualType FromQTy,
4956                                   const CanQualType ToQTy,
4957                                   Sema &S,
4958                                   SourceLocation Loc,
4959                                   ExprValueKind FromVK) {
4960   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4961   ImplicitConversionSequence ICS =
4962     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4963 
4964   return !ICS.isBad();
4965 }
4966 
4967 /// TryObjectArgumentInitialization - Try to initialize the object
4968 /// parameter of the given member function (@c Method) from the
4969 /// expression @p From.
4970 static ImplicitConversionSequence
4971 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4972                                 Expr::Classification FromClassification,
4973                                 CXXMethodDecl *Method,
4974                                 CXXRecordDecl *ActingContext) {
4975   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4976   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4977   //                 const volatile object.
4978   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4979     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4980   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4981 
4982   // Set up the conversion sequence as a "bad" conversion, to allow us
4983   // to exit early.
4984   ImplicitConversionSequence ICS;
4985 
4986   // We need to have an object of class type.
4987   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4988     FromType = PT->getPointeeType();
4989 
4990     // When we had a pointer, it's implicitly dereferenced, so we
4991     // better have an lvalue.
4992     assert(FromClassification.isLValue());
4993   }
4994 
4995   assert(FromType->isRecordType());
4996 
4997   // C++0x [over.match.funcs]p4:
4998   //   For non-static member functions, the type of the implicit object
4999   //   parameter is
5000   //
5001   //     - "lvalue reference to cv X" for functions declared without a
5002   //        ref-qualifier or with the & ref-qualifier
5003   //     - "rvalue reference to cv X" for functions declared with the &&
5004   //        ref-qualifier
5005   //
5006   // where X is the class of which the function is a member and cv is the
5007   // cv-qualification on the member function declaration.
5008   //
5009   // However, when finding an implicit conversion sequence for the argument, we
5010   // are not allowed to perform user-defined conversions
5011   // (C++ [over.match.funcs]p5). We perform a simplified version of
5012   // reference binding here, that allows class rvalues to bind to
5013   // non-constant references.
5014 
5015   // First check the qualifiers.
5016   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5017   if (ImplicitParamType.getCVRQualifiers()
5018                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5019       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5020     ICS.setBad(BadConversionSequence::bad_qualifiers,
5021                FromType, ImplicitParamType);
5022     return ICS;
5023   }
5024 
5025   // Check that we have either the same type or a derived type. It
5026   // affects the conversion rank.
5027   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5028   ImplicitConversionKind SecondKind;
5029   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5030     SecondKind = ICK_Identity;
5031   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5032     SecondKind = ICK_Derived_To_Base;
5033   else {
5034     ICS.setBad(BadConversionSequence::unrelated_class,
5035                FromType, ImplicitParamType);
5036     return ICS;
5037   }
5038 
5039   // Check the ref-qualifier.
5040   switch (Method->getRefQualifier()) {
5041   case RQ_None:
5042     // Do nothing; we don't care about lvalueness or rvalueness.
5043     break;
5044 
5045   case RQ_LValue:
5046     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5047       // non-const lvalue reference cannot bind to an rvalue
5048       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5049                  ImplicitParamType);
5050       return ICS;
5051     }
5052     break;
5053 
5054   case RQ_RValue:
5055     if (!FromClassification.isRValue()) {
5056       // rvalue reference cannot bind to an lvalue
5057       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5058                  ImplicitParamType);
5059       return ICS;
5060     }
5061     break;
5062   }
5063 
5064   // Success. Mark this as a reference binding.
5065   ICS.setStandard();
5066   ICS.Standard.setAsIdentityConversion();
5067   ICS.Standard.Second = SecondKind;
5068   ICS.Standard.setFromType(FromType);
5069   ICS.Standard.setAllToTypes(ImplicitParamType);
5070   ICS.Standard.ReferenceBinding = true;
5071   ICS.Standard.DirectBinding = true;
5072   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5073   ICS.Standard.BindsToFunctionLvalue = false;
5074   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5075   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5076     = (Method->getRefQualifier() == RQ_None);
5077   return ICS;
5078 }
5079 
5080 /// PerformObjectArgumentInitialization - Perform initialization of
5081 /// the implicit object parameter for the given Method with the given
5082 /// expression.
5083 ExprResult
5084 Sema::PerformObjectArgumentInitialization(Expr *From,
5085                                           NestedNameSpecifier *Qualifier,
5086                                           NamedDecl *FoundDecl,
5087                                           CXXMethodDecl *Method) {
5088   QualType FromRecordType, DestType;
5089   QualType ImplicitParamRecordType  =
5090     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5091 
5092   Expr::Classification FromClassification;
5093   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5094     FromRecordType = PT->getPointeeType();
5095     DestType = Method->getThisType(Context);
5096     FromClassification = Expr::Classification::makeSimpleLValue();
5097   } else {
5098     FromRecordType = From->getType();
5099     DestType = ImplicitParamRecordType;
5100     FromClassification = From->Classify(Context);
5101   }
5102 
5103   // Note that we always use the true parent context when performing
5104   // the actual argument initialization.
5105   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5106       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5107       Method->getParent());
5108   if (ICS.isBad()) {
5109     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5110       Qualifiers FromQs = FromRecordType.getQualifiers();
5111       Qualifiers ToQs = DestType.getQualifiers();
5112       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5113       if (CVR) {
5114         Diag(From->getLocStart(),
5115              diag::err_member_function_call_bad_cvr)
5116           << Method->getDeclName() << FromRecordType << (CVR - 1)
5117           << From->getSourceRange();
5118         Diag(Method->getLocation(), diag::note_previous_decl)
5119           << Method->getDeclName();
5120         return ExprError();
5121       }
5122     }
5123 
5124     return Diag(From->getLocStart(),
5125                 diag::err_implicit_object_parameter_init)
5126        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5127   }
5128 
5129   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5130     ExprResult FromRes =
5131       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5132     if (FromRes.isInvalid())
5133       return ExprError();
5134     From = FromRes.get();
5135   }
5136 
5137   if (!Context.hasSameType(From->getType(), DestType))
5138     From = ImpCastExprToType(From, DestType, CK_NoOp,
5139                              From->getValueKind()).get();
5140   return From;
5141 }
5142 
5143 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5144 /// expression From to bool (C++0x [conv]p3).
5145 static ImplicitConversionSequence
5146 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5147   return TryImplicitConversion(S, From, S.Context.BoolTy,
5148                                /*SuppressUserConversions=*/false,
5149                                /*AllowExplicit=*/true,
5150                                /*InOverloadResolution=*/false,
5151                                /*CStyle=*/false,
5152                                /*AllowObjCWritebackConversion=*/false,
5153                                /*AllowObjCConversionOnExplicit=*/false);
5154 }
5155 
5156 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5157 /// of the expression From to bool (C++0x [conv]p3).
5158 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5159   if (checkPlaceholderForOverload(*this, From))
5160     return ExprError();
5161 
5162   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5163   if (!ICS.isBad())
5164     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5165 
5166   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5167     return Diag(From->getLocStart(),
5168                 diag::err_typecheck_bool_condition)
5169                   << From->getType() << From->getSourceRange();
5170   return ExprError();
5171 }
5172 
5173 /// Check that the specified conversion is permitted in a converted constant
5174 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5175 /// is acceptable.
5176 static bool CheckConvertedConstantConversions(Sema &S,
5177                                               StandardConversionSequence &SCS) {
5178   // Since we know that the target type is an integral or unscoped enumeration
5179   // type, most conversion kinds are impossible. All possible First and Third
5180   // conversions are fine.
5181   switch (SCS.Second) {
5182   case ICK_Identity:
5183   case ICK_Function_Conversion:
5184   case ICK_Integral_Promotion:
5185   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5186   case ICK_Zero_Queue_Conversion:
5187     return true;
5188 
5189   case ICK_Boolean_Conversion:
5190     // Conversion from an integral or unscoped enumeration type to bool is
5191     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5192     // conversion, so we allow it in a converted constant expression.
5193     //
5194     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5195     // a lot of popular code. We should at least add a warning for this
5196     // (non-conforming) extension.
5197     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5198            SCS.getToType(2)->isBooleanType();
5199 
5200   case ICK_Pointer_Conversion:
5201   case ICK_Pointer_Member:
5202     // C++1z: null pointer conversions and null member pointer conversions are
5203     // only permitted if the source type is std::nullptr_t.
5204     return SCS.getFromType()->isNullPtrType();
5205 
5206   case ICK_Floating_Promotion:
5207   case ICK_Complex_Promotion:
5208   case ICK_Floating_Conversion:
5209   case ICK_Complex_Conversion:
5210   case ICK_Floating_Integral:
5211   case ICK_Compatible_Conversion:
5212   case ICK_Derived_To_Base:
5213   case ICK_Vector_Conversion:
5214   case ICK_Vector_Splat:
5215   case ICK_Complex_Real:
5216   case ICK_Block_Pointer_Conversion:
5217   case ICK_TransparentUnionConversion:
5218   case ICK_Writeback_Conversion:
5219   case ICK_Zero_Event_Conversion:
5220   case ICK_C_Only_Conversion:
5221   case ICK_Incompatible_Pointer_Conversion:
5222     return false;
5223 
5224   case ICK_Lvalue_To_Rvalue:
5225   case ICK_Array_To_Pointer:
5226   case ICK_Function_To_Pointer:
5227     llvm_unreachable("found a first conversion kind in Second");
5228 
5229   case ICK_Qualification:
5230     llvm_unreachable("found a third conversion kind in Second");
5231 
5232   case ICK_Num_Conversion_Kinds:
5233     break;
5234   }
5235 
5236   llvm_unreachable("unknown conversion kind");
5237 }
5238 
5239 /// CheckConvertedConstantExpression - Check that the expression From is a
5240 /// converted constant expression of type T, perform the conversion and produce
5241 /// the converted expression, per C++11 [expr.const]p3.
5242 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5243                                                    QualType T, APValue &Value,
5244                                                    Sema::CCEKind CCE,
5245                                                    bool RequireInt) {
5246   assert(S.getLangOpts().CPlusPlus11 &&
5247          "converted constant expression outside C++11");
5248 
5249   if (checkPlaceholderForOverload(S, From))
5250     return ExprError();
5251 
5252   // C++1z [expr.const]p3:
5253   //  A converted constant expression of type T is an expression,
5254   //  implicitly converted to type T, where the converted
5255   //  expression is a constant expression and the implicit conversion
5256   //  sequence contains only [... list of conversions ...].
5257   // C++1z [stmt.if]p2:
5258   //  If the if statement is of the form if constexpr, the value of the
5259   //  condition shall be a contextually converted constant expression of type
5260   //  bool.
5261   ImplicitConversionSequence ICS =
5262       CCE == Sema::CCEK_ConstexprIf
5263           ? TryContextuallyConvertToBool(S, From)
5264           : TryCopyInitialization(S, From, T,
5265                                   /*SuppressUserConversions=*/false,
5266                                   /*InOverloadResolution=*/false,
5267                                   /*AllowObjcWritebackConversion=*/false,
5268                                   /*AllowExplicit=*/false);
5269   StandardConversionSequence *SCS = nullptr;
5270   switch (ICS.getKind()) {
5271   case ImplicitConversionSequence::StandardConversion:
5272     SCS = &ICS.Standard;
5273     break;
5274   case ImplicitConversionSequence::UserDefinedConversion:
5275     // We are converting to a non-class type, so the Before sequence
5276     // must be trivial.
5277     SCS = &ICS.UserDefined.After;
5278     break;
5279   case ImplicitConversionSequence::AmbiguousConversion:
5280   case ImplicitConversionSequence::BadConversion:
5281     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5282       return S.Diag(From->getLocStart(),
5283                     diag::err_typecheck_converted_constant_expression)
5284                 << From->getType() << From->getSourceRange() << T;
5285     return ExprError();
5286 
5287   case ImplicitConversionSequence::EllipsisConversion:
5288     llvm_unreachable("ellipsis conversion in converted constant expression");
5289   }
5290 
5291   // Check that we would only use permitted conversions.
5292   if (!CheckConvertedConstantConversions(S, *SCS)) {
5293     return S.Diag(From->getLocStart(),
5294                   diag::err_typecheck_converted_constant_expression_disallowed)
5295              << From->getType() << From->getSourceRange() << T;
5296   }
5297   // [...] and where the reference binding (if any) binds directly.
5298   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5299     return S.Diag(From->getLocStart(),
5300                   diag::err_typecheck_converted_constant_expression_indirect)
5301              << From->getType() << From->getSourceRange() << T;
5302   }
5303 
5304   ExprResult Result =
5305       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5306   if (Result.isInvalid())
5307     return Result;
5308 
5309   // Check for a narrowing implicit conversion.
5310   APValue PreNarrowingValue;
5311   QualType PreNarrowingType;
5312   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5313                                 PreNarrowingType)) {
5314   case NK_Dependent_Narrowing:
5315     // Implicit conversion to a narrower type, but the expression is
5316     // value-dependent so we can't tell whether it's actually narrowing.
5317   case NK_Variable_Narrowing:
5318     // Implicit conversion to a narrower type, and the value is not a constant
5319     // expression. We'll diagnose this in a moment.
5320   case NK_Not_Narrowing:
5321     break;
5322 
5323   case NK_Constant_Narrowing:
5324     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5325       << CCE << /*Constant*/1
5326       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5327     break;
5328 
5329   case NK_Type_Narrowing:
5330     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5331       << CCE << /*Constant*/0 << From->getType() << T;
5332     break;
5333   }
5334 
5335   if (Result.get()->isValueDependent()) {
5336     Value = APValue();
5337     return Result;
5338   }
5339 
5340   // Check the expression is a constant expression.
5341   SmallVector<PartialDiagnosticAt, 8> Notes;
5342   Expr::EvalResult Eval;
5343   Eval.Diag = &Notes;
5344 
5345   if ((T->isReferenceType()
5346            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5347            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5348       (RequireInt && !Eval.Val.isInt())) {
5349     // The expression can't be folded, so we can't keep it at this position in
5350     // the AST.
5351     Result = ExprError();
5352   } else {
5353     Value = Eval.Val;
5354 
5355     if (Notes.empty()) {
5356       // It's a constant expression.
5357       return Result;
5358     }
5359   }
5360 
5361   // It's not a constant expression. Produce an appropriate diagnostic.
5362   if (Notes.size() == 1 &&
5363       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5364     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5365   else {
5366     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5367       << CCE << From->getSourceRange();
5368     for (unsigned I = 0; I < Notes.size(); ++I)
5369       S.Diag(Notes[I].first, Notes[I].second);
5370   }
5371   return ExprError();
5372 }
5373 
5374 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5375                                                   APValue &Value, CCEKind CCE) {
5376   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5377 }
5378 
5379 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5380                                                   llvm::APSInt &Value,
5381                                                   CCEKind CCE) {
5382   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5383 
5384   APValue V;
5385   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5386   if (!R.isInvalid() && !R.get()->isValueDependent())
5387     Value = V.getInt();
5388   return R;
5389 }
5390 
5391 
5392 /// dropPointerConversions - If the given standard conversion sequence
5393 /// involves any pointer conversions, remove them.  This may change
5394 /// the result type of the conversion sequence.
5395 static void dropPointerConversion(StandardConversionSequence &SCS) {
5396   if (SCS.Second == ICK_Pointer_Conversion) {
5397     SCS.Second = ICK_Identity;
5398     SCS.Third = ICK_Identity;
5399     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5400   }
5401 }
5402 
5403 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5404 /// convert the expression From to an Objective-C pointer type.
5405 static ImplicitConversionSequence
5406 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5407   // Do an implicit conversion to 'id'.
5408   QualType Ty = S.Context.getObjCIdType();
5409   ImplicitConversionSequence ICS
5410     = TryImplicitConversion(S, From, Ty,
5411                             // FIXME: Are these flags correct?
5412                             /*SuppressUserConversions=*/false,
5413                             /*AllowExplicit=*/true,
5414                             /*InOverloadResolution=*/false,
5415                             /*CStyle=*/false,
5416                             /*AllowObjCWritebackConversion=*/false,
5417                             /*AllowObjCConversionOnExplicit=*/true);
5418 
5419   // Strip off any final conversions to 'id'.
5420   switch (ICS.getKind()) {
5421   case ImplicitConversionSequence::BadConversion:
5422   case ImplicitConversionSequence::AmbiguousConversion:
5423   case ImplicitConversionSequence::EllipsisConversion:
5424     break;
5425 
5426   case ImplicitConversionSequence::UserDefinedConversion:
5427     dropPointerConversion(ICS.UserDefined.After);
5428     break;
5429 
5430   case ImplicitConversionSequence::StandardConversion:
5431     dropPointerConversion(ICS.Standard);
5432     break;
5433   }
5434 
5435   return ICS;
5436 }
5437 
5438 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5439 /// conversion of the expression From to an Objective-C pointer type.
5440 /// Returns a valid but null ExprResult if no conversion sequence exists.
5441 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5442   if (checkPlaceholderForOverload(*this, From))
5443     return ExprError();
5444 
5445   QualType Ty = Context.getObjCIdType();
5446   ImplicitConversionSequence ICS =
5447     TryContextuallyConvertToObjCPointer(*this, From);
5448   if (!ICS.isBad())
5449     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5450   return ExprResult();
5451 }
5452 
5453 /// Determine whether the provided type is an integral type, or an enumeration
5454 /// type of a permitted flavor.
5455 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5456   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5457                                  : T->isIntegralOrUnscopedEnumerationType();
5458 }
5459 
5460 static ExprResult
5461 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5462                             Sema::ContextualImplicitConverter &Converter,
5463                             QualType T, UnresolvedSetImpl &ViableConversions) {
5464 
5465   if (Converter.Suppress)
5466     return ExprError();
5467 
5468   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5469   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5470     CXXConversionDecl *Conv =
5471         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5472     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5473     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5474   }
5475   return From;
5476 }
5477 
5478 static bool
5479 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5480                            Sema::ContextualImplicitConverter &Converter,
5481                            QualType T, bool HadMultipleCandidates,
5482                            UnresolvedSetImpl &ExplicitConversions) {
5483   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5484     DeclAccessPair Found = ExplicitConversions[0];
5485     CXXConversionDecl *Conversion =
5486         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5487 
5488     // The user probably meant to invoke the given explicit
5489     // conversion; use it.
5490     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5491     std::string TypeStr;
5492     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5493 
5494     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5495         << FixItHint::CreateInsertion(From->getLocStart(),
5496                                       "static_cast<" + TypeStr + ">(")
5497         << FixItHint::CreateInsertion(
5498                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5499     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5500 
5501     // If we aren't in a SFINAE context, build a call to the
5502     // explicit conversion function.
5503     if (SemaRef.isSFINAEContext())
5504       return true;
5505 
5506     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5507     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5508                                                        HadMultipleCandidates);
5509     if (Result.isInvalid())
5510       return true;
5511     // Record usage of conversion in an implicit cast.
5512     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5513                                     CK_UserDefinedConversion, Result.get(),
5514                                     nullptr, Result.get()->getValueKind());
5515   }
5516   return false;
5517 }
5518 
5519 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5520                              Sema::ContextualImplicitConverter &Converter,
5521                              QualType T, bool HadMultipleCandidates,
5522                              DeclAccessPair &Found) {
5523   CXXConversionDecl *Conversion =
5524       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5525   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5526 
5527   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5528   if (!Converter.SuppressConversion) {
5529     if (SemaRef.isSFINAEContext())
5530       return true;
5531 
5532     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5533         << From->getSourceRange();
5534   }
5535 
5536   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5537                                                      HadMultipleCandidates);
5538   if (Result.isInvalid())
5539     return true;
5540   // Record usage of conversion in an implicit cast.
5541   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5542                                   CK_UserDefinedConversion, Result.get(),
5543                                   nullptr, Result.get()->getValueKind());
5544   return false;
5545 }
5546 
5547 static ExprResult finishContextualImplicitConversion(
5548     Sema &SemaRef, SourceLocation Loc, Expr *From,
5549     Sema::ContextualImplicitConverter &Converter) {
5550   if (!Converter.match(From->getType()) && !Converter.Suppress)
5551     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5552         << From->getSourceRange();
5553 
5554   return SemaRef.DefaultLvalueConversion(From);
5555 }
5556 
5557 static void
5558 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5559                                   UnresolvedSetImpl &ViableConversions,
5560                                   OverloadCandidateSet &CandidateSet) {
5561   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5562     DeclAccessPair FoundDecl = ViableConversions[I];
5563     NamedDecl *D = FoundDecl.getDecl();
5564     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5565     if (isa<UsingShadowDecl>(D))
5566       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5567 
5568     CXXConversionDecl *Conv;
5569     FunctionTemplateDecl *ConvTemplate;
5570     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5571       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5572     else
5573       Conv = cast<CXXConversionDecl>(D);
5574 
5575     if (ConvTemplate)
5576       SemaRef.AddTemplateConversionCandidate(
5577         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5578         /*AllowObjCConversionOnExplicit=*/false);
5579     else
5580       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5581                                      ToType, CandidateSet,
5582                                      /*AllowObjCConversionOnExplicit=*/false);
5583   }
5584 }
5585 
5586 /// \brief Attempt to convert the given expression to a type which is accepted
5587 /// by the given converter.
5588 ///
5589 /// This routine will attempt to convert an expression of class type to a
5590 /// type accepted by the specified converter. In C++11 and before, the class
5591 /// must have a single non-explicit conversion function converting to a matching
5592 /// type. In C++1y, there can be multiple such conversion functions, but only
5593 /// one target type.
5594 ///
5595 /// \param Loc The source location of the construct that requires the
5596 /// conversion.
5597 ///
5598 /// \param From The expression we're converting from.
5599 ///
5600 /// \param Converter Used to control and diagnose the conversion process.
5601 ///
5602 /// \returns The expression, converted to an integral or enumeration type if
5603 /// successful.
5604 ExprResult Sema::PerformContextualImplicitConversion(
5605     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5606   // We can't perform any more checking for type-dependent expressions.
5607   if (From->isTypeDependent())
5608     return From;
5609 
5610   // Process placeholders immediately.
5611   if (From->hasPlaceholderType()) {
5612     ExprResult result = CheckPlaceholderExpr(From);
5613     if (result.isInvalid())
5614       return result;
5615     From = result.get();
5616   }
5617 
5618   // If the expression already has a matching type, we're golden.
5619   QualType T = From->getType();
5620   if (Converter.match(T))
5621     return DefaultLvalueConversion(From);
5622 
5623   // FIXME: Check for missing '()' if T is a function type?
5624 
5625   // We can only perform contextual implicit conversions on objects of class
5626   // type.
5627   const RecordType *RecordTy = T->getAs<RecordType>();
5628   if (!RecordTy || !getLangOpts().CPlusPlus) {
5629     if (!Converter.Suppress)
5630       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5631     return From;
5632   }
5633 
5634   // We must have a complete class type.
5635   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5636     ContextualImplicitConverter &Converter;
5637     Expr *From;
5638 
5639     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5640         : Converter(Converter), From(From) {}
5641 
5642     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5643       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5644     }
5645   } IncompleteDiagnoser(Converter, From);
5646 
5647   if (Converter.Suppress ? !isCompleteType(Loc, T)
5648                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5649     return From;
5650 
5651   // Look for a conversion to an integral or enumeration type.
5652   UnresolvedSet<4>
5653       ViableConversions; // These are *potentially* viable in C++1y.
5654   UnresolvedSet<4> ExplicitConversions;
5655   const auto &Conversions =
5656       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5657 
5658   bool HadMultipleCandidates =
5659       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5660 
5661   // To check that there is only one target type, in C++1y:
5662   QualType ToType;
5663   bool HasUniqueTargetType = true;
5664 
5665   // Collect explicit or viable (potentially in C++1y) conversions.
5666   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5667     NamedDecl *D = (*I)->getUnderlyingDecl();
5668     CXXConversionDecl *Conversion;
5669     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5670     if (ConvTemplate) {
5671       if (getLangOpts().CPlusPlus14)
5672         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5673       else
5674         continue; // C++11 does not consider conversion operator templates(?).
5675     } else
5676       Conversion = cast<CXXConversionDecl>(D);
5677 
5678     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5679            "Conversion operator templates are considered potentially "
5680            "viable in C++1y");
5681 
5682     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5683     if (Converter.match(CurToType) || ConvTemplate) {
5684 
5685       if (Conversion->isExplicit()) {
5686         // FIXME: For C++1y, do we need this restriction?
5687         // cf. diagnoseNoViableConversion()
5688         if (!ConvTemplate)
5689           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5690       } else {
5691         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5692           if (ToType.isNull())
5693             ToType = CurToType.getUnqualifiedType();
5694           else if (HasUniqueTargetType &&
5695                    (CurToType.getUnqualifiedType() != ToType))
5696             HasUniqueTargetType = false;
5697         }
5698         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5699       }
5700     }
5701   }
5702 
5703   if (getLangOpts().CPlusPlus14) {
5704     // C++1y [conv]p6:
5705     // ... An expression e of class type E appearing in such a context
5706     // is said to be contextually implicitly converted to a specified
5707     // type T and is well-formed if and only if e can be implicitly
5708     // converted to a type T that is determined as follows: E is searched
5709     // for conversion functions whose return type is cv T or reference to
5710     // cv T such that T is allowed by the context. There shall be
5711     // exactly one such T.
5712 
5713     // If no unique T is found:
5714     if (ToType.isNull()) {
5715       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5716                                      HadMultipleCandidates,
5717                                      ExplicitConversions))
5718         return ExprError();
5719       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5720     }
5721 
5722     // If more than one unique Ts are found:
5723     if (!HasUniqueTargetType)
5724       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5725                                          ViableConversions);
5726 
5727     // If one unique T is found:
5728     // First, build a candidate set from the previously recorded
5729     // potentially viable conversions.
5730     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5731     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5732                                       CandidateSet);
5733 
5734     // Then, perform overload resolution over the candidate set.
5735     OverloadCandidateSet::iterator Best;
5736     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5737     case OR_Success: {
5738       // Apply this conversion.
5739       DeclAccessPair Found =
5740           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5741       if (recordConversion(*this, Loc, From, Converter, T,
5742                            HadMultipleCandidates, Found))
5743         return ExprError();
5744       break;
5745     }
5746     case OR_Ambiguous:
5747       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5748                                          ViableConversions);
5749     case OR_No_Viable_Function:
5750       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5751                                      HadMultipleCandidates,
5752                                      ExplicitConversions))
5753         return ExprError();
5754     // fall through 'OR_Deleted' case.
5755     case OR_Deleted:
5756       // We'll complain below about a non-integral condition type.
5757       break;
5758     }
5759   } else {
5760     switch (ViableConversions.size()) {
5761     case 0: {
5762       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5763                                      HadMultipleCandidates,
5764                                      ExplicitConversions))
5765         return ExprError();
5766 
5767       // We'll complain below about a non-integral condition type.
5768       break;
5769     }
5770     case 1: {
5771       // Apply this conversion.
5772       DeclAccessPair Found = ViableConversions[0];
5773       if (recordConversion(*this, Loc, From, Converter, T,
5774                            HadMultipleCandidates, Found))
5775         return ExprError();
5776       break;
5777     }
5778     default:
5779       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5780                                          ViableConversions);
5781     }
5782   }
5783 
5784   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5785 }
5786 
5787 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5788 /// an acceptable non-member overloaded operator for a call whose
5789 /// arguments have types T1 (and, if non-empty, T2). This routine
5790 /// implements the check in C++ [over.match.oper]p3b2 concerning
5791 /// enumeration types.
5792 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5793                                                    FunctionDecl *Fn,
5794                                                    ArrayRef<Expr *> Args) {
5795   QualType T1 = Args[0]->getType();
5796   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5797 
5798   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5799     return true;
5800 
5801   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5802     return true;
5803 
5804   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5805   if (Proto->getNumParams() < 1)
5806     return false;
5807 
5808   if (T1->isEnumeralType()) {
5809     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5810     if (Context.hasSameUnqualifiedType(T1, ArgType))
5811       return true;
5812   }
5813 
5814   if (Proto->getNumParams() < 2)
5815     return false;
5816 
5817   if (!T2.isNull() && T2->isEnumeralType()) {
5818     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5819     if (Context.hasSameUnqualifiedType(T2, ArgType))
5820       return true;
5821   }
5822 
5823   return false;
5824 }
5825 
5826 /// AddOverloadCandidate - Adds the given function to the set of
5827 /// candidate functions, using the given function call arguments.  If
5828 /// @p SuppressUserConversions, then don't allow user-defined
5829 /// conversions via constructors or conversion operators.
5830 ///
5831 /// \param PartialOverloading true if we are performing "partial" overloading
5832 /// based on an incomplete set of function arguments. This feature is used by
5833 /// code completion.
5834 void
5835 Sema::AddOverloadCandidate(FunctionDecl *Function,
5836                            DeclAccessPair FoundDecl,
5837                            ArrayRef<Expr *> Args,
5838                            OverloadCandidateSet &CandidateSet,
5839                            bool SuppressUserConversions,
5840                            bool PartialOverloading,
5841                            bool AllowExplicit,
5842                            ConversionSequenceList EarlyConversions) {
5843   const FunctionProtoType *Proto
5844     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5845   assert(Proto && "Functions without a prototype cannot be overloaded");
5846   assert(!Function->getDescribedFunctionTemplate() &&
5847          "Use AddTemplateOverloadCandidate for function templates");
5848 
5849   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5850     if (!isa<CXXConstructorDecl>(Method)) {
5851       // If we get here, it's because we're calling a member function
5852       // that is named without a member access expression (e.g.,
5853       // "this->f") that was either written explicitly or created
5854       // implicitly. This can happen with a qualified call to a member
5855       // function, e.g., X::f(). We use an empty type for the implied
5856       // object argument (C++ [over.call.func]p3), and the acting context
5857       // is irrelevant.
5858       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5859                          Expr::Classification::makeSimpleLValue(), Args,
5860                          CandidateSet, SuppressUserConversions,
5861                          PartialOverloading, EarlyConversions);
5862       return;
5863     }
5864     // We treat a constructor like a non-member function, since its object
5865     // argument doesn't participate in overload resolution.
5866   }
5867 
5868   if (!CandidateSet.isNewCandidate(Function))
5869     return;
5870 
5871   // C++ [over.match.oper]p3:
5872   //   if no operand has a class type, only those non-member functions in the
5873   //   lookup set that have a first parameter of type T1 or "reference to
5874   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5875   //   is a right operand) a second parameter of type T2 or "reference to
5876   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5877   //   candidate functions.
5878   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5879       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5880     return;
5881 
5882   // C++11 [class.copy]p11: [DR1402]
5883   //   A defaulted move constructor that is defined as deleted is ignored by
5884   //   overload resolution.
5885   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5886   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5887       Constructor->isMoveConstructor())
5888     return;
5889 
5890   // Overload resolution is always an unevaluated context.
5891   EnterExpressionEvaluationContext Unevaluated(
5892       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5893 
5894   // Add this candidate
5895   OverloadCandidate &Candidate =
5896       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5897   Candidate.FoundDecl = FoundDecl;
5898   Candidate.Function = Function;
5899   Candidate.Viable = true;
5900   Candidate.IsSurrogate = false;
5901   Candidate.IgnoreObjectArgument = false;
5902   Candidate.ExplicitCallArguments = Args.size();
5903 
5904   if (Constructor) {
5905     // C++ [class.copy]p3:
5906     //   A member function template is never instantiated to perform the copy
5907     //   of a class object to an object of its class type.
5908     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5909     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5910         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5911          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5912                        ClassType))) {
5913       Candidate.Viable = false;
5914       Candidate.FailureKind = ovl_fail_illegal_constructor;
5915       return;
5916     }
5917 
5918     // C++ [over.match.funcs]p8: (proposed DR resolution)
5919     //   A constructor inherited from class type C that has a first parameter
5920     //   of type "reference to P" (including such a constructor instantiated
5921     //   from a template) is excluded from the set of candidate functions when
5922     //   constructing an object of type cv D if the argument list has exactly
5923     //   one argument and D is reference-related to P and P is reference-related
5924     //   to C.
5925     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5926     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5927         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5928       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5929       QualType C = Context.getRecordType(Constructor->getParent());
5930       QualType D = Context.getRecordType(Shadow->getParent());
5931       SourceLocation Loc = Args.front()->getExprLoc();
5932       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5933           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5934         Candidate.Viable = false;
5935         Candidate.FailureKind = ovl_fail_inhctor_slice;
5936         return;
5937       }
5938     }
5939   }
5940 
5941   unsigned NumParams = Proto->getNumParams();
5942 
5943   // (C++ 13.3.2p2): A candidate function having fewer than m
5944   // parameters is viable only if it has an ellipsis in its parameter
5945   // list (8.3.5).
5946   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5947       !Proto->isVariadic()) {
5948     Candidate.Viable = false;
5949     Candidate.FailureKind = ovl_fail_too_many_arguments;
5950     return;
5951   }
5952 
5953   // (C++ 13.3.2p2): A candidate function having more than m parameters
5954   // is viable only if the (m+1)st parameter has a default argument
5955   // (8.3.6). For the purposes of overload resolution, the
5956   // parameter list is truncated on the right, so that there are
5957   // exactly m parameters.
5958   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5959   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5960     // Not enough arguments.
5961     Candidate.Viable = false;
5962     Candidate.FailureKind = ovl_fail_too_few_arguments;
5963     return;
5964   }
5965 
5966   // (CUDA B.1): Check for invalid calls between targets.
5967   if (getLangOpts().CUDA)
5968     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5969       // Skip the check for callers that are implicit members, because in this
5970       // case we may not yet know what the member's target is; the target is
5971       // inferred for the member automatically, based on the bases and fields of
5972       // the class.
5973       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5974         Candidate.Viable = false;
5975         Candidate.FailureKind = ovl_fail_bad_target;
5976         return;
5977       }
5978 
5979   // Determine the implicit conversion sequences for each of the
5980   // arguments.
5981   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5982     if (Candidate.Conversions[ArgIdx].isInitialized()) {
5983       // We already formed a conversion sequence for this parameter during
5984       // template argument deduction.
5985     } else if (ArgIdx < NumParams) {
5986       // (C++ 13.3.2p3): for F to be a viable function, there shall
5987       // exist for each argument an implicit conversion sequence
5988       // (13.3.3.1) that converts that argument to the corresponding
5989       // parameter of F.
5990       QualType ParamType = Proto->getParamType(ArgIdx);
5991       Candidate.Conversions[ArgIdx]
5992         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5993                                 SuppressUserConversions,
5994                                 /*InOverloadResolution=*/true,
5995                                 /*AllowObjCWritebackConversion=*/
5996                                   getLangOpts().ObjCAutoRefCount,
5997                                 AllowExplicit);
5998       if (Candidate.Conversions[ArgIdx].isBad()) {
5999         Candidate.Viable = false;
6000         Candidate.FailureKind = ovl_fail_bad_conversion;
6001         return;
6002       }
6003     } else {
6004       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6005       // argument for which there is no corresponding parameter is
6006       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6007       Candidate.Conversions[ArgIdx].setEllipsis();
6008     }
6009   }
6010 
6011   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6012     Candidate.Viable = false;
6013     Candidate.FailureKind = ovl_fail_enable_if;
6014     Candidate.DeductionFailure.Data = FailedAttr;
6015     return;
6016   }
6017 
6018   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6019     Candidate.Viable = false;
6020     Candidate.FailureKind = ovl_fail_ext_disabled;
6021     return;
6022   }
6023 }
6024 
6025 ObjCMethodDecl *
6026 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6027                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6028   if (Methods.size() <= 1)
6029     return nullptr;
6030 
6031   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6032     bool Match = true;
6033     ObjCMethodDecl *Method = Methods[b];
6034     unsigned NumNamedArgs = Sel.getNumArgs();
6035     // Method might have more arguments than selector indicates. This is due
6036     // to addition of c-style arguments in method.
6037     if (Method->param_size() > NumNamedArgs)
6038       NumNamedArgs = Method->param_size();
6039     if (Args.size() < NumNamedArgs)
6040       continue;
6041 
6042     for (unsigned i = 0; i < NumNamedArgs; i++) {
6043       // We can't do any type-checking on a type-dependent argument.
6044       if (Args[i]->isTypeDependent()) {
6045         Match = false;
6046         break;
6047       }
6048 
6049       ParmVarDecl *param = Method->parameters()[i];
6050       Expr *argExpr = Args[i];
6051       assert(argExpr && "SelectBestMethod(): missing expression");
6052 
6053       // Strip the unbridged-cast placeholder expression off unless it's
6054       // a consumed argument.
6055       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6056           !param->hasAttr<CFConsumedAttr>())
6057         argExpr = stripARCUnbridgedCast(argExpr);
6058 
6059       // If the parameter is __unknown_anytype, move on to the next method.
6060       if (param->getType() == Context.UnknownAnyTy) {
6061         Match = false;
6062         break;
6063       }
6064 
6065       ImplicitConversionSequence ConversionState
6066         = TryCopyInitialization(*this, argExpr, param->getType(),
6067                                 /*SuppressUserConversions*/false,
6068                                 /*InOverloadResolution=*/true,
6069                                 /*AllowObjCWritebackConversion=*/
6070                                 getLangOpts().ObjCAutoRefCount,
6071                                 /*AllowExplicit*/false);
6072       // This function looks for a reasonably-exact match, so we consider
6073       // incompatible pointer conversions to be a failure here.
6074       if (ConversionState.isBad() ||
6075           (ConversionState.isStandard() &&
6076            ConversionState.Standard.Second ==
6077                ICK_Incompatible_Pointer_Conversion)) {
6078         Match = false;
6079         break;
6080       }
6081     }
6082     // Promote additional arguments to variadic methods.
6083     if (Match && Method->isVariadic()) {
6084       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6085         if (Args[i]->isTypeDependent()) {
6086           Match = false;
6087           break;
6088         }
6089         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6090                                                           nullptr);
6091         if (Arg.isInvalid()) {
6092           Match = false;
6093           break;
6094         }
6095       }
6096     } else {
6097       // Check for extra arguments to non-variadic methods.
6098       if (Args.size() != NumNamedArgs)
6099         Match = false;
6100       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6101         // Special case when selectors have no argument. In this case, select
6102         // one with the most general result type of 'id'.
6103         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6104           QualType ReturnT = Methods[b]->getReturnType();
6105           if (ReturnT->isObjCIdType())
6106             return Methods[b];
6107         }
6108       }
6109     }
6110 
6111     if (Match)
6112       return Method;
6113   }
6114   return nullptr;
6115 }
6116 
6117 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6118 // enable_if is order-sensitive. As a result, we need to reverse things
6119 // sometimes. Size of 4 elements is arbitrary.
6120 static SmallVector<EnableIfAttr *, 4>
6121 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6122   SmallVector<EnableIfAttr *, 4> Result;
6123   if (!Function->hasAttrs())
6124     return Result;
6125 
6126   const auto &FuncAttrs = Function->getAttrs();
6127   for (Attr *Attr : FuncAttrs)
6128     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6129       Result.push_back(EnableIf);
6130 
6131   std::reverse(Result.begin(), Result.end());
6132   return Result;
6133 }
6134 
6135 static bool
6136 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6137                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6138                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6139                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6140   if (ThisArg) {
6141     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6142     assert(!isa<CXXConstructorDecl>(Method) &&
6143            "Shouldn't have `this` for ctors!");
6144     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6145     ExprResult R = S.PerformObjectArgumentInitialization(
6146         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6147     if (R.isInvalid())
6148       return false;
6149     ConvertedThis = R.get();
6150   } else {
6151     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6152       (void)MD;
6153       assert((MissingImplicitThis || MD->isStatic() ||
6154               isa<CXXConstructorDecl>(MD)) &&
6155              "Expected `this` for non-ctor instance methods");
6156     }
6157     ConvertedThis = nullptr;
6158   }
6159 
6160   // Ignore any variadic arguments. Converting them is pointless, since the
6161   // user can't refer to them in the function condition.
6162   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6163 
6164   // Convert the arguments.
6165   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6166     ExprResult R;
6167     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6168                                         S.Context, Function->getParamDecl(I)),
6169                                     SourceLocation(), Args[I]);
6170 
6171     if (R.isInvalid())
6172       return false;
6173 
6174     ConvertedArgs.push_back(R.get());
6175   }
6176 
6177   if (Trap.hasErrorOccurred())
6178     return false;
6179 
6180   // Push default arguments if needed.
6181   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6182     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6183       ParmVarDecl *P = Function->getParamDecl(i);
6184       ExprResult R = S.PerformCopyInitialization(
6185           InitializedEntity::InitializeParameter(S.Context,
6186                                                  Function->getParamDecl(i)),
6187           SourceLocation(),
6188           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6189                                            : P->getDefaultArg());
6190       if (R.isInvalid())
6191         return false;
6192       ConvertedArgs.push_back(R.get());
6193     }
6194 
6195     if (Trap.hasErrorOccurred())
6196       return false;
6197   }
6198   return true;
6199 }
6200 
6201 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6202                                   bool MissingImplicitThis) {
6203   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6204       getOrderedEnableIfAttrs(Function);
6205   if (EnableIfAttrs.empty())
6206     return nullptr;
6207 
6208   SFINAETrap Trap(*this);
6209   SmallVector<Expr *, 16> ConvertedArgs;
6210   // FIXME: We should look into making enable_if late-parsed.
6211   Expr *DiscardedThis;
6212   if (!convertArgsForAvailabilityChecks(
6213           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6214           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6215     return EnableIfAttrs[0];
6216 
6217   for (auto *EIA : EnableIfAttrs) {
6218     APValue Result;
6219     // FIXME: This doesn't consider value-dependent cases, because doing so is
6220     // very difficult. Ideally, we should handle them more gracefully.
6221     if (!EIA->getCond()->EvaluateWithSubstitution(
6222             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6223       return EIA;
6224 
6225     if (!Result.isInt() || !Result.getInt().getBoolValue())
6226       return EIA;
6227   }
6228   return nullptr;
6229 }
6230 
6231 template <typename CheckFn>
6232 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const FunctionDecl *FD,
6233                                         bool ArgDependent, SourceLocation Loc,
6234                                         CheckFn &&IsSuccessful) {
6235   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6236   for (const auto *DIA : FD->specific_attrs<DiagnoseIfAttr>()) {
6237     if (ArgDependent == DIA->getArgDependent())
6238       Attrs.push_back(DIA);
6239   }
6240 
6241   // Common case: No diagnose_if attributes, so we can quit early.
6242   if (Attrs.empty())
6243     return false;
6244 
6245   auto WarningBegin = std::stable_partition(
6246       Attrs.begin(), Attrs.end(),
6247       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6248 
6249   // Note that diagnose_if attributes are late-parsed, so they appear in the
6250   // correct order (unlike enable_if attributes).
6251   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6252                                IsSuccessful);
6253   if (ErrAttr != WarningBegin) {
6254     const DiagnoseIfAttr *DIA = *ErrAttr;
6255     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6256     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6257         << DIA->getParent() << DIA->getCond()->getSourceRange();
6258     return true;
6259   }
6260 
6261   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6262     if (IsSuccessful(DIA)) {
6263       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6264       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6265           << DIA->getParent() << DIA->getCond()->getSourceRange();
6266     }
6267 
6268   return false;
6269 }
6270 
6271 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6272                                                const Expr *ThisArg,
6273                                                ArrayRef<const Expr *> Args,
6274                                                SourceLocation Loc) {
6275   return diagnoseDiagnoseIfAttrsWith(
6276       *this, Function, /*ArgDependent=*/true, Loc,
6277       [&](const DiagnoseIfAttr *DIA) {
6278         APValue Result;
6279         // It's sane to use the same Args for any redecl of this function, since
6280         // EvaluateWithSubstitution only cares about the position of each
6281         // argument in the arg list, not the ParmVarDecl* it maps to.
6282         if (!DIA->getCond()->EvaluateWithSubstitution(
6283                 Result, Context, DIA->getParent(), Args, ThisArg))
6284           return false;
6285         return Result.isInt() && Result.getInt().getBoolValue();
6286       });
6287 }
6288 
6289 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
6290                                                  SourceLocation Loc) {
6291   return diagnoseDiagnoseIfAttrsWith(
6292       *this, Function, /*ArgDependent=*/false, Loc,
6293       [&](const DiagnoseIfAttr *DIA) {
6294         bool Result;
6295         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6296                Result;
6297       });
6298 }
6299 
6300 /// \brief Add all of the function declarations in the given function set to
6301 /// the overload candidate set.
6302 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6303                                  ArrayRef<Expr *> Args,
6304                                  OverloadCandidateSet& CandidateSet,
6305                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6306                                  bool SuppressUserConversions,
6307                                  bool PartialOverloading) {
6308   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6309     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6310     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6311       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6312         QualType ObjectType;
6313         Expr::Classification ObjectClassification;
6314         if (Expr *E = Args[0]) {
6315           // Use the explit base to restrict the lookup:
6316           ObjectType = E->getType();
6317           ObjectClassification = E->Classify(Context);
6318         } // .. else there is an implit base.
6319         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6320                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6321                            ObjectClassification, Args.slice(1), CandidateSet,
6322                            SuppressUserConversions, PartialOverloading);
6323       } else {
6324         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6325                              SuppressUserConversions, PartialOverloading);
6326       }
6327     } else {
6328       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6329       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6330           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6331         QualType ObjectType;
6332         Expr::Classification ObjectClassification;
6333         if (Expr *E = Args[0]) {
6334           // Use the explit base to restrict the lookup:
6335           ObjectType = E->getType();
6336           ObjectClassification = E->Classify(Context);
6337         } // .. else there is an implit base.
6338         AddMethodTemplateCandidate(
6339             FunTmpl, F.getPair(),
6340             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6341             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6342             Args.slice(1), CandidateSet, SuppressUserConversions,
6343             PartialOverloading);
6344       } else {
6345         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6346                                      ExplicitTemplateArgs, Args,
6347                                      CandidateSet, SuppressUserConversions,
6348                                      PartialOverloading);
6349       }
6350     }
6351   }
6352 }
6353 
6354 /// AddMethodCandidate - Adds a named decl (which is some kind of
6355 /// method) as a method candidate to the given overload set.
6356 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6357                               QualType ObjectType,
6358                               Expr::Classification ObjectClassification,
6359                               ArrayRef<Expr *> Args,
6360                               OverloadCandidateSet& CandidateSet,
6361                               bool SuppressUserConversions) {
6362   NamedDecl *Decl = FoundDecl.getDecl();
6363   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6364 
6365   if (isa<UsingShadowDecl>(Decl))
6366     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6367 
6368   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6369     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6370            "Expected a member function template");
6371     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6372                                /*ExplicitArgs*/ nullptr, ObjectType,
6373                                ObjectClassification, Args, CandidateSet,
6374                                SuppressUserConversions);
6375   } else {
6376     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6377                        ObjectType, ObjectClassification, Args, CandidateSet,
6378                        SuppressUserConversions);
6379   }
6380 }
6381 
6382 /// AddMethodCandidate - Adds the given C++ member function to the set
6383 /// of candidate functions, using the given function call arguments
6384 /// and the object argument (@c Object). For example, in a call
6385 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6386 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6387 /// allow user-defined conversions via constructors or conversion
6388 /// operators.
6389 void
6390 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6391                          CXXRecordDecl *ActingContext, QualType ObjectType,
6392                          Expr::Classification ObjectClassification,
6393                          ArrayRef<Expr *> Args,
6394                          OverloadCandidateSet &CandidateSet,
6395                          bool SuppressUserConversions,
6396                          bool PartialOverloading,
6397                          ConversionSequenceList EarlyConversions) {
6398   const FunctionProtoType *Proto
6399     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6400   assert(Proto && "Methods without a prototype cannot be overloaded");
6401   assert(!isa<CXXConstructorDecl>(Method) &&
6402          "Use AddOverloadCandidate for constructors");
6403 
6404   if (!CandidateSet.isNewCandidate(Method))
6405     return;
6406 
6407   // C++11 [class.copy]p23: [DR1402]
6408   //   A defaulted move assignment operator that is defined as deleted is
6409   //   ignored by overload resolution.
6410   if (Method->isDefaulted() && Method->isDeleted() &&
6411       Method->isMoveAssignmentOperator())
6412     return;
6413 
6414   // Overload resolution is always an unevaluated context.
6415   EnterExpressionEvaluationContext Unevaluated(
6416       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6417 
6418   // Add this candidate
6419   OverloadCandidate &Candidate =
6420       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6421   Candidate.FoundDecl = FoundDecl;
6422   Candidate.Function = Method;
6423   Candidate.IsSurrogate = false;
6424   Candidate.IgnoreObjectArgument = false;
6425   Candidate.ExplicitCallArguments = Args.size();
6426 
6427   unsigned NumParams = Proto->getNumParams();
6428 
6429   // (C++ 13.3.2p2): A candidate function having fewer than m
6430   // parameters is viable only if it has an ellipsis in its parameter
6431   // list (8.3.5).
6432   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6433       !Proto->isVariadic()) {
6434     Candidate.Viable = false;
6435     Candidate.FailureKind = ovl_fail_too_many_arguments;
6436     return;
6437   }
6438 
6439   // (C++ 13.3.2p2): A candidate function having more than m parameters
6440   // is viable only if the (m+1)st parameter has a default argument
6441   // (8.3.6). For the purposes of overload resolution, the
6442   // parameter list is truncated on the right, so that there are
6443   // exactly m parameters.
6444   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6445   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6446     // Not enough arguments.
6447     Candidate.Viable = false;
6448     Candidate.FailureKind = ovl_fail_too_few_arguments;
6449     return;
6450   }
6451 
6452   Candidate.Viable = true;
6453 
6454   if (Method->isStatic() || ObjectType.isNull())
6455     // The implicit object argument is ignored.
6456     Candidate.IgnoreObjectArgument = true;
6457   else {
6458     // Determine the implicit conversion sequence for the object
6459     // parameter.
6460     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6461         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6462         Method, ActingContext);
6463     if (Candidate.Conversions[0].isBad()) {
6464       Candidate.Viable = false;
6465       Candidate.FailureKind = ovl_fail_bad_conversion;
6466       return;
6467     }
6468   }
6469 
6470   // (CUDA B.1): Check for invalid calls between targets.
6471   if (getLangOpts().CUDA)
6472     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6473       if (!IsAllowedCUDACall(Caller, Method)) {
6474         Candidate.Viable = false;
6475         Candidate.FailureKind = ovl_fail_bad_target;
6476         return;
6477       }
6478 
6479   // Determine the implicit conversion sequences for each of the
6480   // arguments.
6481   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6482     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6483       // We already formed a conversion sequence for this parameter during
6484       // template argument deduction.
6485     } else if (ArgIdx < NumParams) {
6486       // (C++ 13.3.2p3): for F to be a viable function, there shall
6487       // exist for each argument an implicit conversion sequence
6488       // (13.3.3.1) that converts that argument to the corresponding
6489       // parameter of F.
6490       QualType ParamType = Proto->getParamType(ArgIdx);
6491       Candidate.Conversions[ArgIdx + 1]
6492         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6493                                 SuppressUserConversions,
6494                                 /*InOverloadResolution=*/true,
6495                                 /*AllowObjCWritebackConversion=*/
6496                                   getLangOpts().ObjCAutoRefCount);
6497       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6498         Candidate.Viable = false;
6499         Candidate.FailureKind = ovl_fail_bad_conversion;
6500         return;
6501       }
6502     } else {
6503       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6504       // argument for which there is no corresponding parameter is
6505       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6506       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6507     }
6508   }
6509 
6510   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6511     Candidate.Viable = false;
6512     Candidate.FailureKind = ovl_fail_enable_if;
6513     Candidate.DeductionFailure.Data = FailedAttr;
6514     return;
6515   }
6516 }
6517 
6518 /// \brief Add a C++ member function template as a candidate to the candidate
6519 /// set, using template argument deduction to produce an appropriate member
6520 /// function template specialization.
6521 void
6522 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6523                                  DeclAccessPair FoundDecl,
6524                                  CXXRecordDecl *ActingContext,
6525                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6526                                  QualType ObjectType,
6527                                  Expr::Classification ObjectClassification,
6528                                  ArrayRef<Expr *> Args,
6529                                  OverloadCandidateSet& CandidateSet,
6530                                  bool SuppressUserConversions,
6531                                  bool PartialOverloading) {
6532   if (!CandidateSet.isNewCandidate(MethodTmpl))
6533     return;
6534 
6535   // C++ [over.match.funcs]p7:
6536   //   In each case where a candidate is a function template, candidate
6537   //   function template specializations are generated using template argument
6538   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6539   //   candidate functions in the usual way.113) A given name can refer to one
6540   //   or more function templates and also to a set of overloaded non-template
6541   //   functions. In such a case, the candidate functions generated from each
6542   //   function template are combined with the set of non-template candidate
6543   //   functions.
6544   TemplateDeductionInfo Info(CandidateSet.getLocation());
6545   FunctionDecl *Specialization = nullptr;
6546   ConversionSequenceList Conversions;
6547   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6548           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6549           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6550             return CheckNonDependentConversions(
6551                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6552                 SuppressUserConversions, ActingContext, ObjectType,
6553                 ObjectClassification);
6554           })) {
6555     OverloadCandidate &Candidate =
6556         CandidateSet.addCandidate(Conversions.size(), Conversions);
6557     Candidate.FoundDecl = FoundDecl;
6558     Candidate.Function = MethodTmpl->getTemplatedDecl();
6559     Candidate.Viable = false;
6560     Candidate.IsSurrogate = false;
6561     Candidate.IgnoreObjectArgument =
6562         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6563         ObjectType.isNull();
6564     Candidate.ExplicitCallArguments = Args.size();
6565     if (Result == TDK_NonDependentConversionFailure)
6566       Candidate.FailureKind = ovl_fail_bad_conversion;
6567     else {
6568       Candidate.FailureKind = ovl_fail_bad_deduction;
6569       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6570                                                             Info);
6571     }
6572     return;
6573   }
6574 
6575   // Add the function template specialization produced by template argument
6576   // deduction as a candidate.
6577   assert(Specialization && "Missing member function template specialization?");
6578   assert(isa<CXXMethodDecl>(Specialization) &&
6579          "Specialization is not a member function?");
6580   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6581                      ActingContext, ObjectType, ObjectClassification, Args,
6582                      CandidateSet, SuppressUserConversions, PartialOverloading,
6583                      Conversions);
6584 }
6585 
6586 /// \brief Add a C++ function template specialization as a candidate
6587 /// in the candidate set, using template argument deduction to produce
6588 /// an appropriate function template specialization.
6589 void
6590 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6591                                    DeclAccessPair FoundDecl,
6592                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6593                                    ArrayRef<Expr *> Args,
6594                                    OverloadCandidateSet& CandidateSet,
6595                                    bool SuppressUserConversions,
6596                                    bool PartialOverloading) {
6597   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6598     return;
6599 
6600   // C++ [over.match.funcs]p7:
6601   //   In each case where a candidate is a function template, candidate
6602   //   function template specializations are generated using template argument
6603   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6604   //   candidate functions in the usual way.113) A given name can refer to one
6605   //   or more function templates and also to a set of overloaded non-template
6606   //   functions. In such a case, the candidate functions generated from each
6607   //   function template are combined with the set of non-template candidate
6608   //   functions.
6609   TemplateDeductionInfo Info(CandidateSet.getLocation());
6610   FunctionDecl *Specialization = nullptr;
6611   ConversionSequenceList Conversions;
6612   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6613           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6614           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6615             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6616                                                 Args, CandidateSet, Conversions,
6617                                                 SuppressUserConversions);
6618           })) {
6619     OverloadCandidate &Candidate =
6620         CandidateSet.addCandidate(Conversions.size(), Conversions);
6621     Candidate.FoundDecl = FoundDecl;
6622     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6623     Candidate.Viable = false;
6624     Candidate.IsSurrogate = false;
6625     // Ignore the object argument if there is one, since we don't have an object
6626     // type.
6627     Candidate.IgnoreObjectArgument =
6628         isa<CXXMethodDecl>(Candidate.Function) &&
6629         !isa<CXXConstructorDecl>(Candidate.Function);
6630     Candidate.ExplicitCallArguments = Args.size();
6631     if (Result == TDK_NonDependentConversionFailure)
6632       Candidate.FailureKind = ovl_fail_bad_conversion;
6633     else {
6634       Candidate.FailureKind = ovl_fail_bad_deduction;
6635       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6636                                                             Info);
6637     }
6638     return;
6639   }
6640 
6641   // Add the function template specialization produced by template argument
6642   // deduction as a candidate.
6643   assert(Specialization && "Missing function template specialization?");
6644   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6645                        SuppressUserConversions, PartialOverloading,
6646                        /*AllowExplicit*/false, Conversions);
6647 }
6648 
6649 /// Check that implicit conversion sequences can be formed for each argument
6650 /// whose corresponding parameter has a non-dependent type, per DR1391's
6651 /// [temp.deduct.call]p10.
6652 bool Sema::CheckNonDependentConversions(
6653     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6654     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6655     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6656     CXXRecordDecl *ActingContext, QualType ObjectType,
6657     Expr::Classification ObjectClassification) {
6658   // FIXME: The cases in which we allow explicit conversions for constructor
6659   // arguments never consider calling a constructor template. It's not clear
6660   // that is correct.
6661   const bool AllowExplicit = false;
6662 
6663   auto *FD = FunctionTemplate->getTemplatedDecl();
6664   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6665   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6666   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6667 
6668   Conversions =
6669       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6670 
6671   // Overload resolution is always an unevaluated context.
6672   EnterExpressionEvaluationContext Unevaluated(
6673       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6674 
6675   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6676   // require that, but this check should never result in a hard error, and
6677   // overload resolution is permitted to sidestep instantiations.
6678   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6679       !ObjectType.isNull()) {
6680     Conversions[0] = TryObjectArgumentInitialization(
6681         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6682         Method, ActingContext);
6683     if (Conversions[0].isBad())
6684       return true;
6685   }
6686 
6687   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6688        ++I) {
6689     QualType ParamType = ParamTypes[I];
6690     if (!ParamType->isDependentType()) {
6691       Conversions[ThisConversions + I]
6692         = TryCopyInitialization(*this, Args[I], ParamType,
6693                                 SuppressUserConversions,
6694                                 /*InOverloadResolution=*/true,
6695                                 /*AllowObjCWritebackConversion=*/
6696                                   getLangOpts().ObjCAutoRefCount,
6697                                 AllowExplicit);
6698       if (Conversions[ThisConversions + I].isBad())
6699         return true;
6700     }
6701   }
6702 
6703   return false;
6704 }
6705 
6706 /// Determine whether this is an allowable conversion from the result
6707 /// of an explicit conversion operator to the expected type, per C++
6708 /// [over.match.conv]p1 and [over.match.ref]p1.
6709 ///
6710 /// \param ConvType The return type of the conversion function.
6711 ///
6712 /// \param ToType The type we are converting to.
6713 ///
6714 /// \param AllowObjCPointerConversion Allow a conversion from one
6715 /// Objective-C pointer to another.
6716 ///
6717 /// \returns true if the conversion is allowable, false otherwise.
6718 static bool isAllowableExplicitConversion(Sema &S,
6719                                           QualType ConvType, QualType ToType,
6720                                           bool AllowObjCPointerConversion) {
6721   QualType ToNonRefType = ToType.getNonReferenceType();
6722 
6723   // Easy case: the types are the same.
6724   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6725     return true;
6726 
6727   // Allow qualification conversions.
6728   bool ObjCLifetimeConversion;
6729   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6730                                   ObjCLifetimeConversion))
6731     return true;
6732 
6733   // If we're not allowed to consider Objective-C pointer conversions,
6734   // we're done.
6735   if (!AllowObjCPointerConversion)
6736     return false;
6737 
6738   // Is this an Objective-C pointer conversion?
6739   bool IncompatibleObjC = false;
6740   QualType ConvertedType;
6741   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6742                                    IncompatibleObjC);
6743 }
6744 
6745 /// AddConversionCandidate - Add a C++ conversion function as a
6746 /// candidate in the candidate set (C++ [over.match.conv],
6747 /// C++ [over.match.copy]). From is the expression we're converting from,
6748 /// and ToType is the type that we're eventually trying to convert to
6749 /// (which may or may not be the same type as the type that the
6750 /// conversion function produces).
6751 void
6752 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6753                              DeclAccessPair FoundDecl,
6754                              CXXRecordDecl *ActingContext,
6755                              Expr *From, QualType ToType,
6756                              OverloadCandidateSet& CandidateSet,
6757                              bool AllowObjCConversionOnExplicit) {
6758   assert(!Conversion->getDescribedFunctionTemplate() &&
6759          "Conversion function templates use AddTemplateConversionCandidate");
6760   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6761   if (!CandidateSet.isNewCandidate(Conversion))
6762     return;
6763 
6764   // If the conversion function has an undeduced return type, trigger its
6765   // deduction now.
6766   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6767     if (DeduceReturnType(Conversion, From->getExprLoc()))
6768       return;
6769     ConvType = Conversion->getConversionType().getNonReferenceType();
6770   }
6771 
6772   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6773   // operator is only a candidate if its return type is the target type or
6774   // can be converted to the target type with a qualification conversion.
6775   if (Conversion->isExplicit() &&
6776       !isAllowableExplicitConversion(*this, ConvType, ToType,
6777                                      AllowObjCConversionOnExplicit))
6778     return;
6779 
6780   // Overload resolution is always an unevaluated context.
6781   EnterExpressionEvaluationContext Unevaluated(
6782       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6783 
6784   // Add this candidate
6785   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6786   Candidate.FoundDecl = FoundDecl;
6787   Candidate.Function = Conversion;
6788   Candidate.IsSurrogate = false;
6789   Candidate.IgnoreObjectArgument = false;
6790   Candidate.FinalConversion.setAsIdentityConversion();
6791   Candidate.FinalConversion.setFromType(ConvType);
6792   Candidate.FinalConversion.setAllToTypes(ToType);
6793   Candidate.Viable = true;
6794   Candidate.ExplicitCallArguments = 1;
6795 
6796   // C++ [over.match.funcs]p4:
6797   //   For conversion functions, the function is considered to be a member of
6798   //   the class of the implicit implied object argument for the purpose of
6799   //   defining the type of the implicit object parameter.
6800   //
6801   // Determine the implicit conversion sequence for the implicit
6802   // object parameter.
6803   QualType ImplicitParamType = From->getType();
6804   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6805     ImplicitParamType = FromPtrType->getPointeeType();
6806   CXXRecordDecl *ConversionContext
6807     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6808 
6809   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6810       *this, CandidateSet.getLocation(), From->getType(),
6811       From->Classify(Context), Conversion, ConversionContext);
6812 
6813   if (Candidate.Conversions[0].isBad()) {
6814     Candidate.Viable = false;
6815     Candidate.FailureKind = ovl_fail_bad_conversion;
6816     return;
6817   }
6818 
6819   // We won't go through a user-defined type conversion function to convert a
6820   // derived to base as such conversions are given Conversion Rank. They only
6821   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6822   QualType FromCanon
6823     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6824   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6825   if (FromCanon == ToCanon ||
6826       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6827     Candidate.Viable = false;
6828     Candidate.FailureKind = ovl_fail_trivial_conversion;
6829     return;
6830   }
6831 
6832   // To determine what the conversion from the result of calling the
6833   // conversion function to the type we're eventually trying to
6834   // convert to (ToType), we need to synthesize a call to the
6835   // conversion function and attempt copy initialization from it. This
6836   // makes sure that we get the right semantics with respect to
6837   // lvalues/rvalues and the type. Fortunately, we can allocate this
6838   // call on the stack and we don't need its arguments to be
6839   // well-formed.
6840   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6841                             VK_LValue, From->getLocStart());
6842   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6843                                 Context.getPointerType(Conversion->getType()),
6844                                 CK_FunctionToPointerDecay,
6845                                 &ConversionRef, VK_RValue);
6846 
6847   QualType ConversionType = Conversion->getConversionType();
6848   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6849     Candidate.Viable = false;
6850     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6851     return;
6852   }
6853 
6854   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6855 
6856   // Note that it is safe to allocate CallExpr on the stack here because
6857   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6858   // allocator).
6859   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6860   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6861                 From->getLocStart());
6862   ImplicitConversionSequence ICS =
6863     TryCopyInitialization(*this, &Call, ToType,
6864                           /*SuppressUserConversions=*/true,
6865                           /*InOverloadResolution=*/false,
6866                           /*AllowObjCWritebackConversion=*/false);
6867 
6868   switch (ICS.getKind()) {
6869   case ImplicitConversionSequence::StandardConversion:
6870     Candidate.FinalConversion = ICS.Standard;
6871 
6872     // C++ [over.ics.user]p3:
6873     //   If the user-defined conversion is specified by a specialization of a
6874     //   conversion function template, the second standard conversion sequence
6875     //   shall have exact match rank.
6876     if (Conversion->getPrimaryTemplate() &&
6877         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6878       Candidate.Viable = false;
6879       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6880       return;
6881     }
6882 
6883     // C++0x [dcl.init.ref]p5:
6884     //    In the second case, if the reference is an rvalue reference and
6885     //    the second standard conversion sequence of the user-defined
6886     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6887     //    program is ill-formed.
6888     if (ToType->isRValueReferenceType() &&
6889         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6890       Candidate.Viable = false;
6891       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6892       return;
6893     }
6894     break;
6895 
6896   case ImplicitConversionSequence::BadConversion:
6897     Candidate.Viable = false;
6898     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6899     return;
6900 
6901   default:
6902     llvm_unreachable(
6903            "Can only end up with a standard conversion sequence or failure");
6904   }
6905 
6906   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6907     Candidate.Viable = false;
6908     Candidate.FailureKind = ovl_fail_enable_if;
6909     Candidate.DeductionFailure.Data = FailedAttr;
6910     return;
6911   }
6912 }
6913 
6914 /// \brief Adds a conversion function template specialization
6915 /// candidate to the overload set, using template argument deduction
6916 /// to deduce the template arguments of the conversion function
6917 /// template from the type that we are converting to (C++
6918 /// [temp.deduct.conv]).
6919 void
6920 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6921                                      DeclAccessPair FoundDecl,
6922                                      CXXRecordDecl *ActingDC,
6923                                      Expr *From, QualType ToType,
6924                                      OverloadCandidateSet &CandidateSet,
6925                                      bool AllowObjCConversionOnExplicit) {
6926   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6927          "Only conversion function templates permitted here");
6928 
6929   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6930     return;
6931 
6932   TemplateDeductionInfo Info(CandidateSet.getLocation());
6933   CXXConversionDecl *Specialization = nullptr;
6934   if (TemplateDeductionResult Result
6935         = DeduceTemplateArguments(FunctionTemplate, ToType,
6936                                   Specialization, Info)) {
6937     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6938     Candidate.FoundDecl = FoundDecl;
6939     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6940     Candidate.Viable = false;
6941     Candidate.FailureKind = ovl_fail_bad_deduction;
6942     Candidate.IsSurrogate = false;
6943     Candidate.IgnoreObjectArgument = false;
6944     Candidate.ExplicitCallArguments = 1;
6945     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6946                                                           Info);
6947     return;
6948   }
6949 
6950   // Add the conversion function template specialization produced by
6951   // template argument deduction as a candidate.
6952   assert(Specialization && "Missing function template specialization?");
6953   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6954                          CandidateSet, AllowObjCConversionOnExplicit);
6955 }
6956 
6957 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6958 /// converts the given @c Object to a function pointer via the
6959 /// conversion function @c Conversion, and then attempts to call it
6960 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6961 /// the type of function that we'll eventually be calling.
6962 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6963                                  DeclAccessPair FoundDecl,
6964                                  CXXRecordDecl *ActingContext,
6965                                  const FunctionProtoType *Proto,
6966                                  Expr *Object,
6967                                  ArrayRef<Expr *> Args,
6968                                  OverloadCandidateSet& CandidateSet) {
6969   if (!CandidateSet.isNewCandidate(Conversion))
6970     return;
6971 
6972   // Overload resolution is always an unevaluated context.
6973   EnterExpressionEvaluationContext Unevaluated(
6974       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6975 
6976   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6977   Candidate.FoundDecl = FoundDecl;
6978   Candidate.Function = nullptr;
6979   Candidate.Surrogate = Conversion;
6980   Candidate.Viable = true;
6981   Candidate.IsSurrogate = true;
6982   Candidate.IgnoreObjectArgument = false;
6983   Candidate.ExplicitCallArguments = Args.size();
6984 
6985   // Determine the implicit conversion sequence for the implicit
6986   // object parameter.
6987   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6988       *this, CandidateSet.getLocation(), Object->getType(),
6989       Object->Classify(Context), Conversion, ActingContext);
6990   if (ObjectInit.isBad()) {
6991     Candidate.Viable = false;
6992     Candidate.FailureKind = ovl_fail_bad_conversion;
6993     Candidate.Conversions[0] = ObjectInit;
6994     return;
6995   }
6996 
6997   // The first conversion is actually a user-defined conversion whose
6998   // first conversion is ObjectInit's standard conversion (which is
6999   // effectively a reference binding). Record it as such.
7000   Candidate.Conversions[0].setUserDefined();
7001   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7002   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7003   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7004   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7005   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7006   Candidate.Conversions[0].UserDefined.After
7007     = Candidate.Conversions[0].UserDefined.Before;
7008   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7009 
7010   // Find the
7011   unsigned NumParams = Proto->getNumParams();
7012 
7013   // (C++ 13.3.2p2): A candidate function having fewer than m
7014   // parameters is viable only if it has an ellipsis in its parameter
7015   // list (8.3.5).
7016   if (Args.size() > NumParams && !Proto->isVariadic()) {
7017     Candidate.Viable = false;
7018     Candidate.FailureKind = ovl_fail_too_many_arguments;
7019     return;
7020   }
7021 
7022   // Function types don't have any default arguments, so just check if
7023   // we have enough arguments.
7024   if (Args.size() < NumParams) {
7025     // Not enough arguments.
7026     Candidate.Viable = false;
7027     Candidate.FailureKind = ovl_fail_too_few_arguments;
7028     return;
7029   }
7030 
7031   // Determine the implicit conversion sequences for each of the
7032   // arguments.
7033   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7034     if (ArgIdx < NumParams) {
7035       // (C++ 13.3.2p3): for F to be a viable function, there shall
7036       // exist for each argument an implicit conversion sequence
7037       // (13.3.3.1) that converts that argument to the corresponding
7038       // parameter of F.
7039       QualType ParamType = Proto->getParamType(ArgIdx);
7040       Candidate.Conversions[ArgIdx + 1]
7041         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7042                                 /*SuppressUserConversions=*/false,
7043                                 /*InOverloadResolution=*/false,
7044                                 /*AllowObjCWritebackConversion=*/
7045                                   getLangOpts().ObjCAutoRefCount);
7046       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7047         Candidate.Viable = false;
7048         Candidate.FailureKind = ovl_fail_bad_conversion;
7049         return;
7050       }
7051     } else {
7052       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7053       // argument for which there is no corresponding parameter is
7054       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7055       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7056     }
7057   }
7058 
7059   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7060     Candidate.Viable = false;
7061     Candidate.FailureKind = ovl_fail_enable_if;
7062     Candidate.DeductionFailure.Data = FailedAttr;
7063     return;
7064   }
7065 }
7066 
7067 /// \brief Add overload candidates for overloaded operators that are
7068 /// member functions.
7069 ///
7070 /// Add the overloaded operator candidates that are member functions
7071 /// for the operator Op that was used in an operator expression such
7072 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7073 /// CandidateSet will store the added overload candidates. (C++
7074 /// [over.match.oper]).
7075 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7076                                        SourceLocation OpLoc,
7077                                        ArrayRef<Expr *> Args,
7078                                        OverloadCandidateSet& CandidateSet,
7079                                        SourceRange OpRange) {
7080   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7081 
7082   // C++ [over.match.oper]p3:
7083   //   For a unary operator @ with an operand of a type whose
7084   //   cv-unqualified version is T1, and for a binary operator @ with
7085   //   a left operand of a type whose cv-unqualified version is T1 and
7086   //   a right operand of a type whose cv-unqualified version is T2,
7087   //   three sets of candidate functions, designated member
7088   //   candidates, non-member candidates and built-in candidates, are
7089   //   constructed as follows:
7090   QualType T1 = Args[0]->getType();
7091 
7092   //     -- If T1 is a complete class type or a class currently being
7093   //        defined, the set of member candidates is the result of the
7094   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7095   //        the set of member candidates is empty.
7096   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7097     // Complete the type if it can be completed.
7098     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7099       return;
7100     // If the type is neither complete nor being defined, bail out now.
7101     if (!T1Rec->getDecl()->getDefinition())
7102       return;
7103 
7104     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7105     LookupQualifiedName(Operators, T1Rec->getDecl());
7106     Operators.suppressDiagnostics();
7107 
7108     for (LookupResult::iterator Oper = Operators.begin(),
7109                              OperEnd = Operators.end();
7110          Oper != OperEnd;
7111          ++Oper)
7112       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7113                          Args[0]->Classify(Context), Args.slice(1),
7114                          CandidateSet, /*SuppressUserConversions=*/false);
7115   }
7116 }
7117 
7118 /// AddBuiltinCandidate - Add a candidate for a built-in
7119 /// operator. ResultTy and ParamTys are the result and parameter types
7120 /// of the built-in candidate, respectively. Args and NumArgs are the
7121 /// arguments being passed to the candidate. IsAssignmentOperator
7122 /// should be true when this built-in candidate is an assignment
7123 /// operator. NumContextualBoolArguments is the number of arguments
7124 /// (at the beginning of the argument list) that will be contextually
7125 /// converted to bool.
7126 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
7127                                ArrayRef<Expr *> Args,
7128                                OverloadCandidateSet& CandidateSet,
7129                                bool IsAssignmentOperator,
7130                                unsigned NumContextualBoolArguments) {
7131   // Overload resolution is always an unevaluated context.
7132   EnterExpressionEvaluationContext Unevaluated(
7133       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7134 
7135   // Add this candidate
7136   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7137   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7138   Candidate.Function = nullptr;
7139   Candidate.IsSurrogate = false;
7140   Candidate.IgnoreObjectArgument = false;
7141   Candidate.BuiltinTypes.ResultTy = ResultTy;
7142   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7143     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
7144 
7145   // Determine the implicit conversion sequences for each of the
7146   // arguments.
7147   Candidate.Viable = true;
7148   Candidate.ExplicitCallArguments = Args.size();
7149   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7150     // C++ [over.match.oper]p4:
7151     //   For the built-in assignment operators, conversions of the
7152     //   left operand are restricted as follows:
7153     //     -- no temporaries are introduced to hold the left operand, and
7154     //     -- no user-defined conversions are applied to the left
7155     //        operand to achieve a type match with the left-most
7156     //        parameter of a built-in candidate.
7157     //
7158     // We block these conversions by turning off user-defined
7159     // conversions, since that is the only way that initialization of
7160     // a reference to a non-class type can occur from something that
7161     // is not of the same type.
7162     if (ArgIdx < NumContextualBoolArguments) {
7163       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7164              "Contextual conversion to bool requires bool type");
7165       Candidate.Conversions[ArgIdx]
7166         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7167     } else {
7168       Candidate.Conversions[ArgIdx]
7169         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7170                                 ArgIdx == 0 && IsAssignmentOperator,
7171                                 /*InOverloadResolution=*/false,
7172                                 /*AllowObjCWritebackConversion=*/
7173                                   getLangOpts().ObjCAutoRefCount);
7174     }
7175     if (Candidate.Conversions[ArgIdx].isBad()) {
7176       Candidate.Viable = false;
7177       Candidate.FailureKind = ovl_fail_bad_conversion;
7178       break;
7179     }
7180   }
7181 }
7182 
7183 namespace {
7184 
7185 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7186 /// candidate operator functions for built-in operators (C++
7187 /// [over.built]). The types are separated into pointer types and
7188 /// enumeration types.
7189 class BuiltinCandidateTypeSet  {
7190   /// TypeSet - A set of types.
7191   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7192                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7193 
7194   /// PointerTypes - The set of pointer types that will be used in the
7195   /// built-in candidates.
7196   TypeSet PointerTypes;
7197 
7198   /// MemberPointerTypes - The set of member pointer types that will be
7199   /// used in the built-in candidates.
7200   TypeSet MemberPointerTypes;
7201 
7202   /// EnumerationTypes - The set of enumeration types that will be
7203   /// used in the built-in candidates.
7204   TypeSet EnumerationTypes;
7205 
7206   /// \brief The set of vector types that will be used in the built-in
7207   /// candidates.
7208   TypeSet VectorTypes;
7209 
7210   /// \brief A flag indicating non-record types are viable candidates
7211   bool HasNonRecordTypes;
7212 
7213   /// \brief A flag indicating whether either arithmetic or enumeration types
7214   /// were present in the candidate set.
7215   bool HasArithmeticOrEnumeralTypes;
7216 
7217   /// \brief A flag indicating whether the nullptr type was present in the
7218   /// candidate set.
7219   bool HasNullPtrType;
7220 
7221   /// Sema - The semantic analysis instance where we are building the
7222   /// candidate type set.
7223   Sema &SemaRef;
7224 
7225   /// Context - The AST context in which we will build the type sets.
7226   ASTContext &Context;
7227 
7228   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7229                                                const Qualifiers &VisibleQuals);
7230   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7231 
7232 public:
7233   /// iterator - Iterates through the types that are part of the set.
7234   typedef TypeSet::iterator iterator;
7235 
7236   BuiltinCandidateTypeSet(Sema &SemaRef)
7237     : HasNonRecordTypes(false),
7238       HasArithmeticOrEnumeralTypes(false),
7239       HasNullPtrType(false),
7240       SemaRef(SemaRef),
7241       Context(SemaRef.Context) { }
7242 
7243   void AddTypesConvertedFrom(QualType Ty,
7244                              SourceLocation Loc,
7245                              bool AllowUserConversions,
7246                              bool AllowExplicitConversions,
7247                              const Qualifiers &VisibleTypeConversionsQuals);
7248 
7249   /// pointer_begin - First pointer type found;
7250   iterator pointer_begin() { return PointerTypes.begin(); }
7251 
7252   /// pointer_end - Past the last pointer type found;
7253   iterator pointer_end() { return PointerTypes.end(); }
7254 
7255   /// member_pointer_begin - First member pointer type found;
7256   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7257 
7258   /// member_pointer_end - Past the last member pointer type found;
7259   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7260 
7261   /// enumeration_begin - First enumeration type found;
7262   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7263 
7264   /// enumeration_end - Past the last enumeration type found;
7265   iterator enumeration_end() { return EnumerationTypes.end(); }
7266 
7267   iterator vector_begin() { return VectorTypes.begin(); }
7268   iterator vector_end() { return VectorTypes.end(); }
7269 
7270   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7271   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7272   bool hasNullPtrType() const { return HasNullPtrType; }
7273 };
7274 
7275 } // end anonymous namespace
7276 
7277 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7278 /// the set of pointer types along with any more-qualified variants of
7279 /// that type. For example, if @p Ty is "int const *", this routine
7280 /// will add "int const *", "int const volatile *", "int const
7281 /// restrict *", and "int const volatile restrict *" to the set of
7282 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7283 /// false otherwise.
7284 ///
7285 /// FIXME: what to do about extended qualifiers?
7286 bool
7287 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7288                                              const Qualifiers &VisibleQuals) {
7289 
7290   // Insert this type.
7291   if (!PointerTypes.insert(Ty))
7292     return false;
7293 
7294   QualType PointeeTy;
7295   const PointerType *PointerTy = Ty->getAs<PointerType>();
7296   bool buildObjCPtr = false;
7297   if (!PointerTy) {
7298     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7299     PointeeTy = PTy->getPointeeType();
7300     buildObjCPtr = true;
7301   } else {
7302     PointeeTy = PointerTy->getPointeeType();
7303   }
7304 
7305   // Don't add qualified variants of arrays. For one, they're not allowed
7306   // (the qualifier would sink to the element type), and for another, the
7307   // only overload situation where it matters is subscript or pointer +- int,
7308   // and those shouldn't have qualifier variants anyway.
7309   if (PointeeTy->isArrayType())
7310     return true;
7311 
7312   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7313   bool hasVolatile = VisibleQuals.hasVolatile();
7314   bool hasRestrict = VisibleQuals.hasRestrict();
7315 
7316   // Iterate through all strict supersets of BaseCVR.
7317   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7318     if ((CVR | BaseCVR) != CVR) continue;
7319     // Skip over volatile if no volatile found anywhere in the types.
7320     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7321 
7322     // Skip over restrict if no restrict found anywhere in the types, or if
7323     // the type cannot be restrict-qualified.
7324     if ((CVR & Qualifiers::Restrict) &&
7325         (!hasRestrict ||
7326          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7327       continue;
7328 
7329     // Build qualified pointee type.
7330     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7331 
7332     // Build qualified pointer type.
7333     QualType QPointerTy;
7334     if (!buildObjCPtr)
7335       QPointerTy = Context.getPointerType(QPointeeTy);
7336     else
7337       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7338 
7339     // Insert qualified pointer type.
7340     PointerTypes.insert(QPointerTy);
7341   }
7342 
7343   return true;
7344 }
7345 
7346 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7347 /// to the set of pointer types along with any more-qualified variants of
7348 /// that type. For example, if @p Ty is "int const *", this routine
7349 /// will add "int const *", "int const volatile *", "int const
7350 /// restrict *", and "int const volatile restrict *" to the set of
7351 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7352 /// false otherwise.
7353 ///
7354 /// FIXME: what to do about extended qualifiers?
7355 bool
7356 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7357     QualType Ty) {
7358   // Insert this type.
7359   if (!MemberPointerTypes.insert(Ty))
7360     return false;
7361 
7362   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7363   assert(PointerTy && "type was not a member pointer type!");
7364 
7365   QualType PointeeTy = PointerTy->getPointeeType();
7366   // Don't add qualified variants of arrays. For one, they're not allowed
7367   // (the qualifier would sink to the element type), and for another, the
7368   // only overload situation where it matters is subscript or pointer +- int,
7369   // and those shouldn't have qualifier variants anyway.
7370   if (PointeeTy->isArrayType())
7371     return true;
7372   const Type *ClassTy = PointerTy->getClass();
7373 
7374   // Iterate through all strict supersets of the pointee type's CVR
7375   // qualifiers.
7376   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7377   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7378     if ((CVR | BaseCVR) != CVR) continue;
7379 
7380     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7381     MemberPointerTypes.insert(
7382       Context.getMemberPointerType(QPointeeTy, ClassTy));
7383   }
7384 
7385   return true;
7386 }
7387 
7388 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7389 /// Ty can be implicit converted to the given set of @p Types. We're
7390 /// primarily interested in pointer types and enumeration types. We also
7391 /// take member pointer types, for the conditional operator.
7392 /// AllowUserConversions is true if we should look at the conversion
7393 /// functions of a class type, and AllowExplicitConversions if we
7394 /// should also include the explicit conversion functions of a class
7395 /// type.
7396 void
7397 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7398                                                SourceLocation Loc,
7399                                                bool AllowUserConversions,
7400                                                bool AllowExplicitConversions,
7401                                                const Qualifiers &VisibleQuals) {
7402   // Only deal with canonical types.
7403   Ty = Context.getCanonicalType(Ty);
7404 
7405   // Look through reference types; they aren't part of the type of an
7406   // expression for the purposes of conversions.
7407   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7408     Ty = RefTy->getPointeeType();
7409 
7410   // If we're dealing with an array type, decay to the pointer.
7411   if (Ty->isArrayType())
7412     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7413 
7414   // Otherwise, we don't care about qualifiers on the type.
7415   Ty = Ty.getLocalUnqualifiedType();
7416 
7417   // Flag if we ever add a non-record type.
7418   const RecordType *TyRec = Ty->getAs<RecordType>();
7419   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7420 
7421   // Flag if we encounter an arithmetic type.
7422   HasArithmeticOrEnumeralTypes =
7423     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7424 
7425   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7426     PointerTypes.insert(Ty);
7427   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7428     // Insert our type, and its more-qualified variants, into the set
7429     // of types.
7430     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7431       return;
7432   } else if (Ty->isMemberPointerType()) {
7433     // Member pointers are far easier, since the pointee can't be converted.
7434     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7435       return;
7436   } else if (Ty->isEnumeralType()) {
7437     HasArithmeticOrEnumeralTypes = true;
7438     EnumerationTypes.insert(Ty);
7439   } else if (Ty->isVectorType()) {
7440     // We treat vector types as arithmetic types in many contexts as an
7441     // extension.
7442     HasArithmeticOrEnumeralTypes = true;
7443     VectorTypes.insert(Ty);
7444   } else if (Ty->isNullPtrType()) {
7445     HasNullPtrType = true;
7446   } else if (AllowUserConversions && TyRec) {
7447     // No conversion functions in incomplete types.
7448     if (!SemaRef.isCompleteType(Loc, Ty))
7449       return;
7450 
7451     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7452     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7453       if (isa<UsingShadowDecl>(D))
7454         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7455 
7456       // Skip conversion function templates; they don't tell us anything
7457       // about which builtin types we can convert to.
7458       if (isa<FunctionTemplateDecl>(D))
7459         continue;
7460 
7461       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7462       if (AllowExplicitConversions || !Conv->isExplicit()) {
7463         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7464                               VisibleQuals);
7465       }
7466     }
7467   }
7468 }
7469 
7470 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7471 /// the volatile- and non-volatile-qualified assignment operators for the
7472 /// given type to the candidate set.
7473 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7474                                                    QualType T,
7475                                                    ArrayRef<Expr *> Args,
7476                                     OverloadCandidateSet &CandidateSet) {
7477   QualType ParamTypes[2];
7478 
7479   // T& operator=(T&, T)
7480   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7481   ParamTypes[1] = T;
7482   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7483                         /*IsAssignmentOperator=*/true);
7484 
7485   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7486     // volatile T& operator=(volatile T&, T)
7487     ParamTypes[0]
7488       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7489     ParamTypes[1] = T;
7490     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7491                           /*IsAssignmentOperator=*/true);
7492   }
7493 }
7494 
7495 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7496 /// if any, found in visible type conversion functions found in ArgExpr's type.
7497 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7498     Qualifiers VRQuals;
7499     const RecordType *TyRec;
7500     if (const MemberPointerType *RHSMPType =
7501         ArgExpr->getType()->getAs<MemberPointerType>())
7502       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7503     else
7504       TyRec = ArgExpr->getType()->getAs<RecordType>();
7505     if (!TyRec) {
7506       // Just to be safe, assume the worst case.
7507       VRQuals.addVolatile();
7508       VRQuals.addRestrict();
7509       return VRQuals;
7510     }
7511 
7512     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7513     if (!ClassDecl->hasDefinition())
7514       return VRQuals;
7515 
7516     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7517       if (isa<UsingShadowDecl>(D))
7518         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7519       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7520         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7521         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7522           CanTy = ResTypeRef->getPointeeType();
7523         // Need to go down the pointer/mempointer chain and add qualifiers
7524         // as see them.
7525         bool done = false;
7526         while (!done) {
7527           if (CanTy.isRestrictQualified())
7528             VRQuals.addRestrict();
7529           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7530             CanTy = ResTypePtr->getPointeeType();
7531           else if (const MemberPointerType *ResTypeMPtr =
7532                 CanTy->getAs<MemberPointerType>())
7533             CanTy = ResTypeMPtr->getPointeeType();
7534           else
7535             done = true;
7536           if (CanTy.isVolatileQualified())
7537             VRQuals.addVolatile();
7538           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7539             return VRQuals;
7540         }
7541       }
7542     }
7543     return VRQuals;
7544 }
7545 
7546 namespace {
7547 
7548 /// \brief Helper class to manage the addition of builtin operator overload
7549 /// candidates. It provides shared state and utility methods used throughout
7550 /// the process, as well as a helper method to add each group of builtin
7551 /// operator overloads from the standard to a candidate set.
7552 class BuiltinOperatorOverloadBuilder {
7553   // Common instance state available to all overload candidate addition methods.
7554   Sema &S;
7555   ArrayRef<Expr *> Args;
7556   Qualifiers VisibleTypeConversionsQuals;
7557   bool HasArithmeticOrEnumeralCandidateType;
7558   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7559   OverloadCandidateSet &CandidateSet;
7560 
7561   // Define some constants used to index and iterate over the arithemetic types
7562   // provided via the getArithmeticType() method below.
7563   // The "promoted arithmetic types" are the arithmetic
7564   // types are that preserved by promotion (C++ [over.built]p2).
7565   static const unsigned FirstIntegralType = 4;
7566   static const unsigned LastIntegralType = 21;
7567   static const unsigned FirstPromotedIntegralType = 4,
7568                         LastPromotedIntegralType = 12;
7569   static const unsigned FirstPromotedArithmeticType = 0,
7570                         LastPromotedArithmeticType = 12;
7571   static const unsigned NumArithmeticTypes = 21;
7572 
7573   /// \brief Get the canonical type for a given arithmetic type index.
7574   CanQualType getArithmeticType(unsigned index) {
7575     assert(index < NumArithmeticTypes);
7576     static CanQualType ASTContext::* const
7577       ArithmeticTypes[NumArithmeticTypes] = {
7578       // Start of promoted types.
7579       &ASTContext::FloatTy,
7580       &ASTContext::DoubleTy,
7581       &ASTContext::LongDoubleTy,
7582       &ASTContext::Float128Ty,
7583 
7584       // Start of integral types.
7585       &ASTContext::IntTy,
7586       &ASTContext::LongTy,
7587       &ASTContext::LongLongTy,
7588       &ASTContext::Int128Ty,
7589       &ASTContext::UnsignedIntTy,
7590       &ASTContext::UnsignedLongTy,
7591       &ASTContext::UnsignedLongLongTy,
7592       &ASTContext::UnsignedInt128Ty,
7593       // End of promoted types.
7594 
7595       &ASTContext::BoolTy,
7596       &ASTContext::CharTy,
7597       &ASTContext::WCharTy,
7598       &ASTContext::Char16Ty,
7599       &ASTContext::Char32Ty,
7600       &ASTContext::SignedCharTy,
7601       &ASTContext::ShortTy,
7602       &ASTContext::UnsignedCharTy,
7603       &ASTContext::UnsignedShortTy,
7604       // End of integral types.
7605       // FIXME: What about complex? What about half?
7606     };
7607     return S.Context.*ArithmeticTypes[index];
7608   }
7609 
7610   /// \brief Gets the canonical type resulting from the usual arithemetic
7611   /// converions for the given arithmetic types.
7612   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7613     // Accelerator table for performing the usual arithmetic conversions.
7614     // The rules are basically:
7615     //   - if either is floating-point, use the wider floating-point
7616     //   - if same signedness, use the higher rank
7617     //   - if same size, use unsigned of the higher rank
7618     //   - use the larger type
7619     // These rules, together with the axiom that higher ranks are
7620     // never smaller, are sufficient to precompute all of these results
7621     // *except* when dealing with signed types of higher rank.
7622     // (we could precompute SLL x UI for all known platforms, but it's
7623     // better not to make any assumptions).
7624     // We assume that int128 has a higher rank than long long on all platforms.
7625     enum PromotedType : int8_t {
7626             Dep=-1,
7627             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7628     };
7629     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7630                                         [LastPromotedArithmeticType] = {
7631 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7632 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7633 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7634 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7635 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7636 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7637 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7638 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7639 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7640 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7641 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7642     };
7643 
7644     assert(L < LastPromotedArithmeticType);
7645     assert(R < LastPromotedArithmeticType);
7646     int Idx = ConversionsTable[L][R];
7647 
7648     // Fast path: the table gives us a concrete answer.
7649     if (Idx != Dep) return getArithmeticType(Idx);
7650 
7651     // Slow path: we need to compare widths.
7652     // An invariant is that the signed type has higher rank.
7653     CanQualType LT = getArithmeticType(L),
7654                 RT = getArithmeticType(R);
7655     unsigned LW = S.Context.getIntWidth(LT),
7656              RW = S.Context.getIntWidth(RT);
7657 
7658     // If they're different widths, use the signed type.
7659     if (LW > RW) return LT;
7660     else if (LW < RW) return RT;
7661 
7662     // Otherwise, use the unsigned type of the signed type's rank.
7663     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7664     assert(L == SLL || R == SLL);
7665     return S.Context.UnsignedLongLongTy;
7666   }
7667 
7668   /// \brief Helper method to factor out the common pattern of adding overloads
7669   /// for '++' and '--' builtin operators.
7670   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7671                                            bool HasVolatile,
7672                                            bool HasRestrict) {
7673     QualType ParamTypes[2] = {
7674       S.Context.getLValueReferenceType(CandidateTy),
7675       S.Context.IntTy
7676     };
7677 
7678     // Non-volatile version.
7679     if (Args.size() == 1)
7680       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7681     else
7682       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7683 
7684     // Use a heuristic to reduce number of builtin candidates in the set:
7685     // add volatile version only if there are conversions to a volatile type.
7686     if (HasVolatile) {
7687       ParamTypes[0] =
7688         S.Context.getLValueReferenceType(
7689           S.Context.getVolatileType(CandidateTy));
7690       if (Args.size() == 1)
7691         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7692       else
7693         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7694     }
7695 
7696     // Add restrict version only if there are conversions to a restrict type
7697     // and our candidate type is a non-restrict-qualified pointer.
7698     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7699         !CandidateTy.isRestrictQualified()) {
7700       ParamTypes[0]
7701         = S.Context.getLValueReferenceType(
7702             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7703       if (Args.size() == 1)
7704         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7705       else
7706         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7707 
7708       if (HasVolatile) {
7709         ParamTypes[0]
7710           = S.Context.getLValueReferenceType(
7711               S.Context.getCVRQualifiedType(CandidateTy,
7712                                             (Qualifiers::Volatile |
7713                                              Qualifiers::Restrict)));
7714         if (Args.size() == 1)
7715           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7716         else
7717           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7718       }
7719     }
7720 
7721   }
7722 
7723 public:
7724   BuiltinOperatorOverloadBuilder(
7725     Sema &S, ArrayRef<Expr *> Args,
7726     Qualifiers VisibleTypeConversionsQuals,
7727     bool HasArithmeticOrEnumeralCandidateType,
7728     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7729     OverloadCandidateSet &CandidateSet)
7730     : S(S), Args(Args),
7731       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7732       HasArithmeticOrEnumeralCandidateType(
7733         HasArithmeticOrEnumeralCandidateType),
7734       CandidateTypes(CandidateTypes),
7735       CandidateSet(CandidateSet) {
7736     // Validate some of our static helper constants in debug builds.
7737     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7738            "Invalid first promoted integral type");
7739     assert(getArithmeticType(LastPromotedIntegralType - 1)
7740              == S.Context.UnsignedInt128Ty &&
7741            "Invalid last promoted integral type");
7742     assert(getArithmeticType(FirstPromotedArithmeticType)
7743              == S.Context.FloatTy &&
7744            "Invalid first promoted arithmetic type");
7745     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7746              == S.Context.UnsignedInt128Ty &&
7747            "Invalid last promoted arithmetic type");
7748   }
7749 
7750   // C++ [over.built]p3:
7751   //
7752   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7753   //   is either volatile or empty, there exist candidate operator
7754   //   functions of the form
7755   //
7756   //       VQ T&      operator++(VQ T&);
7757   //       T          operator++(VQ T&, int);
7758   //
7759   // C++ [over.built]p4:
7760   //
7761   //   For every pair (T, VQ), where T is an arithmetic type other
7762   //   than bool, and VQ is either volatile or empty, there exist
7763   //   candidate operator functions of the form
7764   //
7765   //       VQ T&      operator--(VQ T&);
7766   //       T          operator--(VQ T&, int);
7767   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7768     if (!HasArithmeticOrEnumeralCandidateType)
7769       return;
7770 
7771     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7772          Arith < NumArithmeticTypes; ++Arith) {
7773       addPlusPlusMinusMinusStyleOverloads(
7774         getArithmeticType(Arith),
7775         VisibleTypeConversionsQuals.hasVolatile(),
7776         VisibleTypeConversionsQuals.hasRestrict());
7777     }
7778   }
7779 
7780   // C++ [over.built]p5:
7781   //
7782   //   For every pair (T, VQ), where T is a cv-qualified or
7783   //   cv-unqualified object type, and VQ is either volatile or
7784   //   empty, there exist candidate operator functions of the form
7785   //
7786   //       T*VQ&      operator++(T*VQ&);
7787   //       T*VQ&      operator--(T*VQ&);
7788   //       T*         operator++(T*VQ&, int);
7789   //       T*         operator--(T*VQ&, int);
7790   void addPlusPlusMinusMinusPointerOverloads() {
7791     for (BuiltinCandidateTypeSet::iterator
7792               Ptr = CandidateTypes[0].pointer_begin(),
7793            PtrEnd = CandidateTypes[0].pointer_end();
7794          Ptr != PtrEnd; ++Ptr) {
7795       // Skip pointer types that aren't pointers to object types.
7796       if (!(*Ptr)->getPointeeType()->isObjectType())
7797         continue;
7798 
7799       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7800         (!(*Ptr).isVolatileQualified() &&
7801          VisibleTypeConversionsQuals.hasVolatile()),
7802         (!(*Ptr).isRestrictQualified() &&
7803          VisibleTypeConversionsQuals.hasRestrict()));
7804     }
7805   }
7806 
7807   // C++ [over.built]p6:
7808   //   For every cv-qualified or cv-unqualified object type T, there
7809   //   exist candidate operator functions of the form
7810   //
7811   //       T&         operator*(T*);
7812   //
7813   // C++ [over.built]p7:
7814   //   For every function type T that does not have cv-qualifiers or a
7815   //   ref-qualifier, there exist candidate operator functions of the form
7816   //       T&         operator*(T*);
7817   void addUnaryStarPointerOverloads() {
7818     for (BuiltinCandidateTypeSet::iterator
7819               Ptr = CandidateTypes[0].pointer_begin(),
7820            PtrEnd = CandidateTypes[0].pointer_end();
7821          Ptr != PtrEnd; ++Ptr) {
7822       QualType ParamTy = *Ptr;
7823       QualType PointeeTy = ParamTy->getPointeeType();
7824       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7825         continue;
7826 
7827       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7828         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7829           continue;
7830 
7831       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7832                             &ParamTy, Args, CandidateSet);
7833     }
7834   }
7835 
7836   // C++ [over.built]p9:
7837   //  For every promoted arithmetic type T, there exist candidate
7838   //  operator functions of the form
7839   //
7840   //       T         operator+(T);
7841   //       T         operator-(T);
7842   void addUnaryPlusOrMinusArithmeticOverloads() {
7843     if (!HasArithmeticOrEnumeralCandidateType)
7844       return;
7845 
7846     for (unsigned Arith = FirstPromotedArithmeticType;
7847          Arith < LastPromotedArithmeticType; ++Arith) {
7848       QualType ArithTy = getArithmeticType(Arith);
7849       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7850     }
7851 
7852     // Extension: We also add these operators for vector types.
7853     for (BuiltinCandidateTypeSet::iterator
7854               Vec = CandidateTypes[0].vector_begin(),
7855            VecEnd = CandidateTypes[0].vector_end();
7856          Vec != VecEnd; ++Vec) {
7857       QualType VecTy = *Vec;
7858       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7859     }
7860   }
7861 
7862   // C++ [over.built]p8:
7863   //   For every type T, there exist candidate operator functions of
7864   //   the form
7865   //
7866   //       T*         operator+(T*);
7867   void addUnaryPlusPointerOverloads() {
7868     for (BuiltinCandidateTypeSet::iterator
7869               Ptr = CandidateTypes[0].pointer_begin(),
7870            PtrEnd = CandidateTypes[0].pointer_end();
7871          Ptr != PtrEnd; ++Ptr) {
7872       QualType ParamTy = *Ptr;
7873       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7874     }
7875   }
7876 
7877   // C++ [over.built]p10:
7878   //   For every promoted integral type T, there exist candidate
7879   //   operator functions of the form
7880   //
7881   //        T         operator~(T);
7882   void addUnaryTildePromotedIntegralOverloads() {
7883     if (!HasArithmeticOrEnumeralCandidateType)
7884       return;
7885 
7886     for (unsigned Int = FirstPromotedIntegralType;
7887          Int < LastPromotedIntegralType; ++Int) {
7888       QualType IntTy = getArithmeticType(Int);
7889       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7890     }
7891 
7892     // Extension: We also add this operator for vector types.
7893     for (BuiltinCandidateTypeSet::iterator
7894               Vec = CandidateTypes[0].vector_begin(),
7895            VecEnd = CandidateTypes[0].vector_end();
7896          Vec != VecEnd; ++Vec) {
7897       QualType VecTy = *Vec;
7898       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7899     }
7900   }
7901 
7902   // C++ [over.match.oper]p16:
7903   //   For every pointer to member type T or type std::nullptr_t, there
7904   //   exist candidate operator functions of the form
7905   //
7906   //        bool operator==(T,T);
7907   //        bool operator!=(T,T);
7908   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7909     /// Set of (canonical) types that we've already handled.
7910     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7911 
7912     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7913       for (BuiltinCandidateTypeSet::iterator
7914                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7915              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7916            MemPtr != MemPtrEnd;
7917            ++MemPtr) {
7918         // Don't add the same builtin candidate twice.
7919         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7920           continue;
7921 
7922         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7923         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7924       }
7925 
7926       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7927         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7928         if (AddedTypes.insert(NullPtrTy).second) {
7929           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7930           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7931                                 CandidateSet);
7932         }
7933       }
7934     }
7935   }
7936 
7937   // C++ [over.built]p15:
7938   //
7939   //   For every T, where T is an enumeration type or a pointer type,
7940   //   there exist candidate operator functions of the form
7941   //
7942   //        bool       operator<(T, T);
7943   //        bool       operator>(T, T);
7944   //        bool       operator<=(T, T);
7945   //        bool       operator>=(T, T);
7946   //        bool       operator==(T, T);
7947   //        bool       operator!=(T, T);
7948   void addRelationalPointerOrEnumeralOverloads() {
7949     // C++ [over.match.oper]p3:
7950     //   [...]the built-in candidates include all of the candidate operator
7951     //   functions defined in 13.6 that, compared to the given operator, [...]
7952     //   do not have the same parameter-type-list as any non-template non-member
7953     //   candidate.
7954     //
7955     // Note that in practice, this only affects enumeration types because there
7956     // aren't any built-in candidates of record type, and a user-defined operator
7957     // must have an operand of record or enumeration type. Also, the only other
7958     // overloaded operator with enumeration arguments, operator=,
7959     // cannot be overloaded for enumeration types, so this is the only place
7960     // where we must suppress candidates like this.
7961     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7962       UserDefinedBinaryOperators;
7963 
7964     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7965       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7966           CandidateTypes[ArgIdx].enumeration_end()) {
7967         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7968                                          CEnd = CandidateSet.end();
7969              C != CEnd; ++C) {
7970           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7971             continue;
7972 
7973           if (C->Function->isFunctionTemplateSpecialization())
7974             continue;
7975 
7976           QualType FirstParamType =
7977             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7978           QualType SecondParamType =
7979             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7980 
7981           // Skip if either parameter isn't of enumeral type.
7982           if (!FirstParamType->isEnumeralType() ||
7983               !SecondParamType->isEnumeralType())
7984             continue;
7985 
7986           // Add this operator to the set of known user-defined operators.
7987           UserDefinedBinaryOperators.insert(
7988             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7989                            S.Context.getCanonicalType(SecondParamType)));
7990         }
7991       }
7992     }
7993 
7994     /// Set of (canonical) types that we've already handled.
7995     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7996 
7997     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7998       for (BuiltinCandidateTypeSet::iterator
7999                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8000              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8001            Ptr != PtrEnd; ++Ptr) {
8002         // Don't add the same builtin candidate twice.
8003         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8004           continue;
8005 
8006         QualType ParamTypes[2] = { *Ptr, *Ptr };
8007         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
8008       }
8009       for (BuiltinCandidateTypeSet::iterator
8010                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8011              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8012            Enum != EnumEnd; ++Enum) {
8013         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8014 
8015         // Don't add the same builtin candidate twice, or if a user defined
8016         // candidate exists.
8017         if (!AddedTypes.insert(CanonType).second ||
8018             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8019                                                             CanonType)))
8020           continue;
8021 
8022         QualType ParamTypes[2] = { *Enum, *Enum };
8023         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
8024       }
8025     }
8026   }
8027 
8028   // C++ [over.built]p13:
8029   //
8030   //   For every cv-qualified or cv-unqualified object type T
8031   //   there exist candidate operator functions of the form
8032   //
8033   //      T*         operator+(T*, ptrdiff_t);
8034   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8035   //      T*         operator-(T*, ptrdiff_t);
8036   //      T*         operator+(ptrdiff_t, T*);
8037   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8038   //
8039   // C++ [over.built]p14:
8040   //
8041   //   For every T, where T is a pointer to object type, there
8042   //   exist candidate operator functions of the form
8043   //
8044   //      ptrdiff_t  operator-(T, T);
8045   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8046     /// Set of (canonical) types that we've already handled.
8047     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8048 
8049     for (int Arg = 0; Arg < 2; ++Arg) {
8050       QualType AsymmetricParamTypes[2] = {
8051         S.Context.getPointerDiffType(),
8052         S.Context.getPointerDiffType(),
8053       };
8054       for (BuiltinCandidateTypeSet::iterator
8055                 Ptr = CandidateTypes[Arg].pointer_begin(),
8056              PtrEnd = CandidateTypes[Arg].pointer_end();
8057            Ptr != PtrEnd; ++Ptr) {
8058         QualType PointeeTy = (*Ptr)->getPointeeType();
8059         if (!PointeeTy->isObjectType())
8060           continue;
8061 
8062         AsymmetricParamTypes[Arg] = *Ptr;
8063         if (Arg == 0 || Op == OO_Plus) {
8064           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8065           // T* operator+(ptrdiff_t, T*);
8066           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
8067         }
8068         if (Op == OO_Minus) {
8069           // ptrdiff_t operator-(T, T);
8070           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8071             continue;
8072 
8073           QualType ParamTypes[2] = { *Ptr, *Ptr };
8074           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
8075                                 Args, CandidateSet);
8076         }
8077       }
8078     }
8079   }
8080 
8081   // C++ [over.built]p12:
8082   //
8083   //   For every pair of promoted arithmetic types L and R, there
8084   //   exist candidate operator functions of the form
8085   //
8086   //        LR         operator*(L, R);
8087   //        LR         operator/(L, R);
8088   //        LR         operator+(L, R);
8089   //        LR         operator-(L, R);
8090   //        bool       operator<(L, R);
8091   //        bool       operator>(L, R);
8092   //        bool       operator<=(L, R);
8093   //        bool       operator>=(L, R);
8094   //        bool       operator==(L, R);
8095   //        bool       operator!=(L, R);
8096   //
8097   //   where LR is the result of the usual arithmetic conversions
8098   //   between types L and R.
8099   //
8100   // C++ [over.built]p24:
8101   //
8102   //   For every pair of promoted arithmetic types L and R, there exist
8103   //   candidate operator functions of the form
8104   //
8105   //        LR       operator?(bool, L, R);
8106   //
8107   //   where LR is the result of the usual arithmetic conversions
8108   //   between types L and R.
8109   // Our candidates ignore the first parameter.
8110   void addGenericBinaryArithmeticOverloads(bool isComparison) {
8111     if (!HasArithmeticOrEnumeralCandidateType)
8112       return;
8113 
8114     for (unsigned Left = FirstPromotedArithmeticType;
8115          Left < LastPromotedArithmeticType; ++Left) {
8116       for (unsigned Right = FirstPromotedArithmeticType;
8117            Right < LastPromotedArithmeticType; ++Right) {
8118         QualType LandR[2] = { getArithmeticType(Left),
8119                               getArithmeticType(Right) };
8120         QualType Result =
8121           isComparison ? S.Context.BoolTy
8122                        : getUsualArithmeticConversions(Left, Right);
8123         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8124       }
8125     }
8126 
8127     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8128     // conditional operator for vector types.
8129     for (BuiltinCandidateTypeSet::iterator
8130               Vec1 = CandidateTypes[0].vector_begin(),
8131            Vec1End = CandidateTypes[0].vector_end();
8132          Vec1 != Vec1End; ++Vec1) {
8133       for (BuiltinCandidateTypeSet::iterator
8134                 Vec2 = CandidateTypes[1].vector_begin(),
8135              Vec2End = CandidateTypes[1].vector_end();
8136            Vec2 != Vec2End; ++Vec2) {
8137         QualType LandR[2] = { *Vec1, *Vec2 };
8138         QualType Result = S.Context.BoolTy;
8139         if (!isComparison) {
8140           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
8141             Result = *Vec1;
8142           else
8143             Result = *Vec2;
8144         }
8145 
8146         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8147       }
8148     }
8149   }
8150 
8151   // C++ [over.built]p17:
8152   //
8153   //   For every pair of promoted integral types L and R, there
8154   //   exist candidate operator functions of the form
8155   //
8156   //      LR         operator%(L, R);
8157   //      LR         operator&(L, R);
8158   //      LR         operator^(L, R);
8159   //      LR         operator|(L, R);
8160   //      L          operator<<(L, R);
8161   //      L          operator>>(L, R);
8162   //
8163   //   where LR is the result of the usual arithmetic conversions
8164   //   between types L and R.
8165   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8166     if (!HasArithmeticOrEnumeralCandidateType)
8167       return;
8168 
8169     for (unsigned Left = FirstPromotedIntegralType;
8170          Left < LastPromotedIntegralType; ++Left) {
8171       for (unsigned Right = FirstPromotedIntegralType;
8172            Right < LastPromotedIntegralType; ++Right) {
8173         QualType LandR[2] = { getArithmeticType(Left),
8174                               getArithmeticType(Right) };
8175         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
8176             ? LandR[0]
8177             : getUsualArithmeticConversions(Left, Right);
8178         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8179       }
8180     }
8181   }
8182 
8183   // C++ [over.built]p20:
8184   //
8185   //   For every pair (T, VQ), where T is an enumeration or
8186   //   pointer to member type and VQ is either volatile or
8187   //   empty, there exist candidate operator functions of the form
8188   //
8189   //        VQ T&      operator=(VQ T&, T);
8190   void addAssignmentMemberPointerOrEnumeralOverloads() {
8191     /// Set of (canonical) types that we've already handled.
8192     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8193 
8194     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8195       for (BuiltinCandidateTypeSet::iterator
8196                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8197              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8198            Enum != EnumEnd; ++Enum) {
8199         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8200           continue;
8201 
8202         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8203       }
8204 
8205       for (BuiltinCandidateTypeSet::iterator
8206                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8207              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8208            MemPtr != MemPtrEnd; ++MemPtr) {
8209         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8210           continue;
8211 
8212         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8213       }
8214     }
8215   }
8216 
8217   // C++ [over.built]p19:
8218   //
8219   //   For every pair (T, VQ), where T is any type and VQ is either
8220   //   volatile or empty, there exist candidate operator functions
8221   //   of the form
8222   //
8223   //        T*VQ&      operator=(T*VQ&, T*);
8224   //
8225   // C++ [over.built]p21:
8226   //
8227   //   For every pair (T, VQ), where T is a cv-qualified or
8228   //   cv-unqualified object type and VQ is either volatile or
8229   //   empty, there exist candidate operator functions of the form
8230   //
8231   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8232   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8233   void addAssignmentPointerOverloads(bool isEqualOp) {
8234     /// Set of (canonical) types that we've already handled.
8235     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8236 
8237     for (BuiltinCandidateTypeSet::iterator
8238               Ptr = CandidateTypes[0].pointer_begin(),
8239            PtrEnd = CandidateTypes[0].pointer_end();
8240          Ptr != PtrEnd; ++Ptr) {
8241       // If this is operator=, keep track of the builtin candidates we added.
8242       if (isEqualOp)
8243         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8244       else if (!(*Ptr)->getPointeeType()->isObjectType())
8245         continue;
8246 
8247       // non-volatile version
8248       QualType ParamTypes[2] = {
8249         S.Context.getLValueReferenceType(*Ptr),
8250         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8251       };
8252       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8253                             /*IsAssigmentOperator=*/ isEqualOp);
8254 
8255       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8256                           VisibleTypeConversionsQuals.hasVolatile();
8257       if (NeedVolatile) {
8258         // volatile version
8259         ParamTypes[0] =
8260           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8261         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8262                               /*IsAssigmentOperator=*/isEqualOp);
8263       }
8264 
8265       if (!(*Ptr).isRestrictQualified() &&
8266           VisibleTypeConversionsQuals.hasRestrict()) {
8267         // restrict version
8268         ParamTypes[0]
8269           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8270         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8271                               /*IsAssigmentOperator=*/isEqualOp);
8272 
8273         if (NeedVolatile) {
8274           // volatile restrict version
8275           ParamTypes[0]
8276             = S.Context.getLValueReferenceType(
8277                 S.Context.getCVRQualifiedType(*Ptr,
8278                                               (Qualifiers::Volatile |
8279                                                Qualifiers::Restrict)));
8280           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8281                                 /*IsAssigmentOperator=*/isEqualOp);
8282         }
8283       }
8284     }
8285 
8286     if (isEqualOp) {
8287       for (BuiltinCandidateTypeSet::iterator
8288                 Ptr = CandidateTypes[1].pointer_begin(),
8289              PtrEnd = CandidateTypes[1].pointer_end();
8290            Ptr != PtrEnd; ++Ptr) {
8291         // Make sure we don't add the same candidate twice.
8292         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8293           continue;
8294 
8295         QualType ParamTypes[2] = {
8296           S.Context.getLValueReferenceType(*Ptr),
8297           *Ptr,
8298         };
8299 
8300         // non-volatile version
8301         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8302                               /*IsAssigmentOperator=*/true);
8303 
8304         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8305                            VisibleTypeConversionsQuals.hasVolatile();
8306         if (NeedVolatile) {
8307           // volatile version
8308           ParamTypes[0] =
8309             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8310           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8311                                 /*IsAssigmentOperator=*/true);
8312         }
8313 
8314         if (!(*Ptr).isRestrictQualified() &&
8315             VisibleTypeConversionsQuals.hasRestrict()) {
8316           // restrict version
8317           ParamTypes[0]
8318             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8319           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8320                                 /*IsAssigmentOperator=*/true);
8321 
8322           if (NeedVolatile) {
8323             // volatile restrict version
8324             ParamTypes[0]
8325               = S.Context.getLValueReferenceType(
8326                   S.Context.getCVRQualifiedType(*Ptr,
8327                                                 (Qualifiers::Volatile |
8328                                                  Qualifiers::Restrict)));
8329             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8330                                   /*IsAssigmentOperator=*/true);
8331           }
8332         }
8333       }
8334     }
8335   }
8336 
8337   // C++ [over.built]p18:
8338   //
8339   //   For every triple (L, VQ, R), where L is an arithmetic type,
8340   //   VQ is either volatile or empty, and R is a promoted
8341   //   arithmetic type, there exist candidate operator functions of
8342   //   the form
8343   //
8344   //        VQ L&      operator=(VQ L&, R);
8345   //        VQ L&      operator*=(VQ L&, R);
8346   //        VQ L&      operator/=(VQ L&, R);
8347   //        VQ L&      operator+=(VQ L&, R);
8348   //        VQ L&      operator-=(VQ L&, R);
8349   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8350     if (!HasArithmeticOrEnumeralCandidateType)
8351       return;
8352 
8353     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8354       for (unsigned Right = FirstPromotedArithmeticType;
8355            Right < LastPromotedArithmeticType; ++Right) {
8356         QualType ParamTypes[2];
8357         ParamTypes[1] = getArithmeticType(Right);
8358 
8359         // Add this built-in operator as a candidate (VQ is empty).
8360         ParamTypes[0] =
8361           S.Context.getLValueReferenceType(getArithmeticType(Left));
8362         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8363                               /*IsAssigmentOperator=*/isEqualOp);
8364 
8365         // Add this built-in operator as a candidate (VQ is 'volatile').
8366         if (VisibleTypeConversionsQuals.hasVolatile()) {
8367           ParamTypes[0] =
8368             S.Context.getVolatileType(getArithmeticType(Left));
8369           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8370           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8371                                 /*IsAssigmentOperator=*/isEqualOp);
8372         }
8373       }
8374     }
8375 
8376     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8377     for (BuiltinCandidateTypeSet::iterator
8378               Vec1 = CandidateTypes[0].vector_begin(),
8379            Vec1End = CandidateTypes[0].vector_end();
8380          Vec1 != Vec1End; ++Vec1) {
8381       for (BuiltinCandidateTypeSet::iterator
8382                 Vec2 = CandidateTypes[1].vector_begin(),
8383              Vec2End = CandidateTypes[1].vector_end();
8384            Vec2 != Vec2End; ++Vec2) {
8385         QualType ParamTypes[2];
8386         ParamTypes[1] = *Vec2;
8387         // Add this built-in operator as a candidate (VQ is empty).
8388         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8389         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8390                               /*IsAssigmentOperator=*/isEqualOp);
8391 
8392         // Add this built-in operator as a candidate (VQ is 'volatile').
8393         if (VisibleTypeConversionsQuals.hasVolatile()) {
8394           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8395           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8396           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8397                                 /*IsAssigmentOperator=*/isEqualOp);
8398         }
8399       }
8400     }
8401   }
8402 
8403   // C++ [over.built]p22:
8404   //
8405   //   For every triple (L, VQ, R), where L is an integral type, VQ
8406   //   is either volatile or empty, and R is a promoted integral
8407   //   type, there exist candidate operator functions of the form
8408   //
8409   //        VQ L&       operator%=(VQ L&, R);
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 addAssignmentIntegralOverloads() {
8416     if (!HasArithmeticOrEnumeralCandidateType)
8417       return;
8418 
8419     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8420       for (unsigned Right = FirstPromotedIntegralType;
8421            Right < LastPromotedIntegralType; ++Right) {
8422         QualType ParamTypes[2];
8423         ParamTypes[1] = getArithmeticType(Right);
8424 
8425         // Add this built-in operator as a candidate (VQ is empty).
8426         ParamTypes[0] =
8427           S.Context.getLValueReferenceType(getArithmeticType(Left));
8428         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8429         if (VisibleTypeConversionsQuals.hasVolatile()) {
8430           // Add this built-in operator as a candidate (VQ is 'volatile').
8431           ParamTypes[0] = getArithmeticType(Left);
8432           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8433           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8434           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8435         }
8436       }
8437     }
8438   }
8439 
8440   // C++ [over.operator]p23:
8441   //
8442   //   There also exist candidate operator functions of the form
8443   //
8444   //        bool        operator!(bool);
8445   //        bool        operator&&(bool, bool);
8446   //        bool        operator||(bool, bool);
8447   void addExclaimOverload() {
8448     QualType ParamTy = S.Context.BoolTy;
8449     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8450                           /*IsAssignmentOperator=*/false,
8451                           /*NumContextualBoolArguments=*/1);
8452   }
8453   void addAmpAmpOrPipePipeOverload() {
8454     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8455     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8456                           /*IsAssignmentOperator=*/false,
8457                           /*NumContextualBoolArguments=*/2);
8458   }
8459 
8460   // C++ [over.built]p13:
8461   //
8462   //   For every cv-qualified or cv-unqualified object type T there
8463   //   exist candidate operator functions of the form
8464   //
8465   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8466   //        T&         operator[](T*, ptrdiff_t);
8467   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8468   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8469   //        T&         operator[](ptrdiff_t, T*);
8470   void addSubscriptOverloads() {
8471     for (BuiltinCandidateTypeSet::iterator
8472               Ptr = CandidateTypes[0].pointer_begin(),
8473            PtrEnd = CandidateTypes[0].pointer_end();
8474          Ptr != PtrEnd; ++Ptr) {
8475       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8476       QualType PointeeType = (*Ptr)->getPointeeType();
8477       if (!PointeeType->isObjectType())
8478         continue;
8479 
8480       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8481 
8482       // T& operator[](T*, ptrdiff_t)
8483       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8484     }
8485 
8486     for (BuiltinCandidateTypeSet::iterator
8487               Ptr = CandidateTypes[1].pointer_begin(),
8488            PtrEnd = CandidateTypes[1].pointer_end();
8489          Ptr != PtrEnd; ++Ptr) {
8490       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8491       QualType PointeeType = (*Ptr)->getPointeeType();
8492       if (!PointeeType->isObjectType())
8493         continue;
8494 
8495       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8496 
8497       // T& operator[](ptrdiff_t, T*)
8498       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8499     }
8500   }
8501 
8502   // C++ [over.built]p11:
8503   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8504   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8505   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8506   //    there exist candidate operator functions of the form
8507   //
8508   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8509   //
8510   //    where CV12 is the union of CV1 and CV2.
8511   void addArrowStarOverloads() {
8512     for (BuiltinCandidateTypeSet::iterator
8513              Ptr = CandidateTypes[0].pointer_begin(),
8514            PtrEnd = CandidateTypes[0].pointer_end();
8515          Ptr != PtrEnd; ++Ptr) {
8516       QualType C1Ty = (*Ptr);
8517       QualType C1;
8518       QualifierCollector Q1;
8519       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8520       if (!isa<RecordType>(C1))
8521         continue;
8522       // heuristic to reduce number of builtin candidates in the set.
8523       // Add volatile/restrict version only if there are conversions to a
8524       // volatile/restrict type.
8525       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8526         continue;
8527       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8528         continue;
8529       for (BuiltinCandidateTypeSet::iterator
8530                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8531              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8532            MemPtr != MemPtrEnd; ++MemPtr) {
8533         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8534         QualType C2 = QualType(mptr->getClass(), 0);
8535         C2 = C2.getUnqualifiedType();
8536         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8537           break;
8538         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8539         // build CV12 T&
8540         QualType T = mptr->getPointeeType();
8541         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8542             T.isVolatileQualified())
8543           continue;
8544         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8545             T.isRestrictQualified())
8546           continue;
8547         T = Q1.apply(S.Context, T);
8548         QualType ResultTy = S.Context.getLValueReferenceType(T);
8549         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8550       }
8551     }
8552   }
8553 
8554   // Note that we don't consider the first argument, since it has been
8555   // contextually converted to bool long ago. The candidates below are
8556   // therefore added as binary.
8557   //
8558   // C++ [over.built]p25:
8559   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8560   //   enumeration type, there exist candidate operator functions of the form
8561   //
8562   //        T        operator?(bool, T, T);
8563   //
8564   void addConditionalOperatorOverloads() {
8565     /// Set of (canonical) types that we've already handled.
8566     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8567 
8568     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8569       for (BuiltinCandidateTypeSet::iterator
8570                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8571              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8572            Ptr != PtrEnd; ++Ptr) {
8573         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8574           continue;
8575 
8576         QualType ParamTypes[2] = { *Ptr, *Ptr };
8577         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8578       }
8579 
8580       for (BuiltinCandidateTypeSet::iterator
8581                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8582              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8583            MemPtr != MemPtrEnd; ++MemPtr) {
8584         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8585           continue;
8586 
8587         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8588         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8589       }
8590 
8591       if (S.getLangOpts().CPlusPlus11) {
8592         for (BuiltinCandidateTypeSet::iterator
8593                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8594                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8595              Enum != EnumEnd; ++Enum) {
8596           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8597             continue;
8598 
8599           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8600             continue;
8601 
8602           QualType ParamTypes[2] = { *Enum, *Enum };
8603           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8604         }
8605       }
8606     }
8607   }
8608 };
8609 
8610 } // end anonymous namespace
8611 
8612 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8613 /// operator overloads to the candidate set (C++ [over.built]), based
8614 /// on the operator @p Op and the arguments given. For example, if the
8615 /// operator is a binary '+', this routine might add "int
8616 /// operator+(int, int)" to cover integer addition.
8617 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8618                                         SourceLocation OpLoc,
8619                                         ArrayRef<Expr *> Args,
8620                                         OverloadCandidateSet &CandidateSet) {
8621   // Find all of the types that the arguments can convert to, but only
8622   // if the operator we're looking at has built-in operator candidates
8623   // that make use of these types. Also record whether we encounter non-record
8624   // candidate types or either arithmetic or enumeral candidate types.
8625   Qualifiers VisibleTypeConversionsQuals;
8626   VisibleTypeConversionsQuals.addConst();
8627   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8628     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8629 
8630   bool HasNonRecordCandidateType = false;
8631   bool HasArithmeticOrEnumeralCandidateType = false;
8632   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8633   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8634     CandidateTypes.emplace_back(*this);
8635     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8636                                                  OpLoc,
8637                                                  true,
8638                                                  (Op == OO_Exclaim ||
8639                                                   Op == OO_AmpAmp ||
8640                                                   Op == OO_PipePipe),
8641                                                  VisibleTypeConversionsQuals);
8642     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8643         CandidateTypes[ArgIdx].hasNonRecordTypes();
8644     HasArithmeticOrEnumeralCandidateType =
8645         HasArithmeticOrEnumeralCandidateType ||
8646         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8647   }
8648 
8649   // Exit early when no non-record types have been added to the candidate set
8650   // for any of the arguments to the operator.
8651   //
8652   // We can't exit early for !, ||, or &&, since there we have always have
8653   // 'bool' overloads.
8654   if (!HasNonRecordCandidateType &&
8655       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8656     return;
8657 
8658   // Setup an object to manage the common state for building overloads.
8659   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8660                                            VisibleTypeConversionsQuals,
8661                                            HasArithmeticOrEnumeralCandidateType,
8662                                            CandidateTypes, CandidateSet);
8663 
8664   // Dispatch over the operation to add in only those overloads which apply.
8665   switch (Op) {
8666   case OO_None:
8667   case NUM_OVERLOADED_OPERATORS:
8668     llvm_unreachable("Expected an overloaded operator");
8669 
8670   case OO_New:
8671   case OO_Delete:
8672   case OO_Array_New:
8673   case OO_Array_Delete:
8674   case OO_Call:
8675     llvm_unreachable(
8676                     "Special operators don't use AddBuiltinOperatorCandidates");
8677 
8678   case OO_Comma:
8679   case OO_Arrow:
8680   case OO_Coawait:
8681     // C++ [over.match.oper]p3:
8682     //   -- For the operator ',', the unary operator '&', the
8683     //      operator '->', or the operator 'co_await', the
8684     //      built-in candidates set is empty.
8685     break;
8686 
8687   case OO_Plus: // '+' is either unary or binary
8688     if (Args.size() == 1)
8689       OpBuilder.addUnaryPlusPointerOverloads();
8690     // Fall through.
8691 
8692   case OO_Minus: // '-' is either unary or binary
8693     if (Args.size() == 1) {
8694       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8695     } else {
8696       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8697       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8698     }
8699     break;
8700 
8701   case OO_Star: // '*' is either unary or binary
8702     if (Args.size() == 1)
8703       OpBuilder.addUnaryStarPointerOverloads();
8704     else
8705       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8706     break;
8707 
8708   case OO_Slash:
8709     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8710     break;
8711 
8712   case OO_PlusPlus:
8713   case OO_MinusMinus:
8714     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8715     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8716     break;
8717 
8718   case OO_EqualEqual:
8719   case OO_ExclaimEqual:
8720     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8721     // Fall through.
8722 
8723   case OO_Less:
8724   case OO_Greater:
8725   case OO_LessEqual:
8726   case OO_GreaterEqual:
8727     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8728     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8729     break;
8730 
8731   case OO_Percent:
8732   case OO_Caret:
8733   case OO_Pipe:
8734   case OO_LessLess:
8735   case OO_GreaterGreater:
8736     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8737     break;
8738 
8739   case OO_Amp: // '&' is either unary or binary
8740     if (Args.size() == 1)
8741       // C++ [over.match.oper]p3:
8742       //   -- For the operator ',', the unary operator '&', or the
8743       //      operator '->', the built-in candidates set is empty.
8744       break;
8745 
8746     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8747     break;
8748 
8749   case OO_Tilde:
8750     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8751     break;
8752 
8753   case OO_Equal:
8754     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8755     // Fall through.
8756 
8757   case OO_PlusEqual:
8758   case OO_MinusEqual:
8759     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8760     // Fall through.
8761 
8762   case OO_StarEqual:
8763   case OO_SlashEqual:
8764     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8765     break;
8766 
8767   case OO_PercentEqual:
8768   case OO_LessLessEqual:
8769   case OO_GreaterGreaterEqual:
8770   case OO_AmpEqual:
8771   case OO_CaretEqual:
8772   case OO_PipeEqual:
8773     OpBuilder.addAssignmentIntegralOverloads();
8774     break;
8775 
8776   case OO_Exclaim:
8777     OpBuilder.addExclaimOverload();
8778     break;
8779 
8780   case OO_AmpAmp:
8781   case OO_PipePipe:
8782     OpBuilder.addAmpAmpOrPipePipeOverload();
8783     break;
8784 
8785   case OO_Subscript:
8786     OpBuilder.addSubscriptOverloads();
8787     break;
8788 
8789   case OO_ArrowStar:
8790     OpBuilder.addArrowStarOverloads();
8791     break;
8792 
8793   case OO_Conditional:
8794     OpBuilder.addConditionalOperatorOverloads();
8795     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8796     break;
8797   }
8798 }
8799 
8800 /// \brief Add function candidates found via argument-dependent lookup
8801 /// to the set of overloading candidates.
8802 ///
8803 /// This routine performs argument-dependent name lookup based on the
8804 /// given function name (which may also be an operator name) and adds
8805 /// all of the overload candidates found by ADL to the overload
8806 /// candidate set (C++ [basic.lookup.argdep]).
8807 void
8808 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8809                                            SourceLocation Loc,
8810                                            ArrayRef<Expr *> Args,
8811                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8812                                            OverloadCandidateSet& CandidateSet,
8813                                            bool PartialOverloading) {
8814   ADLResult Fns;
8815 
8816   // FIXME: This approach for uniquing ADL results (and removing
8817   // redundant candidates from the set) relies on pointer-equality,
8818   // which means we need to key off the canonical decl.  However,
8819   // always going back to the canonical decl might not get us the
8820   // right set of default arguments.  What default arguments are
8821   // we supposed to consider on ADL candidates, anyway?
8822 
8823   // FIXME: Pass in the explicit template arguments?
8824   ArgumentDependentLookup(Name, Loc, Args, Fns);
8825 
8826   // Erase all of the candidates we already knew about.
8827   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8828                                    CandEnd = CandidateSet.end();
8829        Cand != CandEnd; ++Cand)
8830     if (Cand->Function) {
8831       Fns.erase(Cand->Function);
8832       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8833         Fns.erase(FunTmpl);
8834     }
8835 
8836   // For each of the ADL candidates we found, add it to the overload
8837   // set.
8838   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8839     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8840     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8841       if (ExplicitTemplateArgs)
8842         continue;
8843 
8844       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8845                            PartialOverloading);
8846     } else
8847       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8848                                    FoundDecl, ExplicitTemplateArgs,
8849                                    Args, CandidateSet, PartialOverloading);
8850   }
8851 }
8852 
8853 namespace {
8854 enum class Comparison { Equal, Better, Worse };
8855 }
8856 
8857 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8858 /// overload resolution.
8859 ///
8860 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8861 /// Cand1's first N enable_if attributes have precisely the same conditions as
8862 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8863 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8864 ///
8865 /// Note that you can have a pair of candidates such that Cand1's enable_if
8866 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8867 /// worse than Cand1's.
8868 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8869                                        const FunctionDecl *Cand2) {
8870   // Common case: One (or both) decls don't have enable_if attrs.
8871   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8872   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8873   if (!Cand1Attr || !Cand2Attr) {
8874     if (Cand1Attr == Cand2Attr)
8875       return Comparison::Equal;
8876     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8877   }
8878 
8879   // FIXME: The next several lines are just
8880   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8881   // instead of reverse order which is how they're stored in the AST.
8882   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8883   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8884 
8885   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8886   // has fewer enable_if attributes than Cand2.
8887   if (Cand1Attrs.size() < Cand2Attrs.size())
8888     return Comparison::Worse;
8889 
8890   auto Cand1I = Cand1Attrs.begin();
8891   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8892   for (auto &Cand2A : Cand2Attrs) {
8893     Cand1ID.clear();
8894     Cand2ID.clear();
8895 
8896     auto &Cand1A = *Cand1I++;
8897     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8898     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8899     if (Cand1ID != Cand2ID)
8900       return Comparison::Worse;
8901   }
8902 
8903   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8904 }
8905 
8906 /// isBetterOverloadCandidate - Determines whether the first overload
8907 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8908 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8909                                       const OverloadCandidate &Cand2,
8910                                       SourceLocation Loc,
8911                                       bool UserDefinedConversion) {
8912   // Define viable functions to be better candidates than non-viable
8913   // functions.
8914   if (!Cand2.Viable)
8915     return Cand1.Viable;
8916   else if (!Cand1.Viable)
8917     return false;
8918 
8919   // C++ [over.match.best]p1:
8920   //
8921   //   -- if F is a static member function, ICS1(F) is defined such
8922   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8923   //      any function G, and, symmetrically, ICS1(G) is neither
8924   //      better nor worse than ICS1(F).
8925   unsigned StartArg = 0;
8926   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8927     StartArg = 1;
8928 
8929   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8930     // We don't allow incompatible pointer conversions in C++.
8931     if (!S.getLangOpts().CPlusPlus)
8932       return ICS.isStandard() &&
8933              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8934 
8935     // The only ill-formed conversion we allow in C++ is the string literal to
8936     // char* conversion, which is only considered ill-formed after C++11.
8937     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8938            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8939   };
8940 
8941   // Define functions that don't require ill-formed conversions for a given
8942   // argument to be better candidates than functions that do.
8943   unsigned NumArgs = Cand1.Conversions.size();
8944   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8945   bool HasBetterConversion = false;
8946   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8947     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8948     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8949     if (Cand1Bad != Cand2Bad) {
8950       if (Cand1Bad)
8951         return false;
8952       HasBetterConversion = true;
8953     }
8954   }
8955 
8956   if (HasBetterConversion)
8957     return true;
8958 
8959   // C++ [over.match.best]p1:
8960   //   A viable function F1 is defined to be a better function than another
8961   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8962   //   conversion sequence than ICSi(F2), and then...
8963   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8964     switch (CompareImplicitConversionSequences(S, Loc,
8965                                                Cand1.Conversions[ArgIdx],
8966                                                Cand2.Conversions[ArgIdx])) {
8967     case ImplicitConversionSequence::Better:
8968       // Cand1 has a better conversion sequence.
8969       HasBetterConversion = true;
8970       break;
8971 
8972     case ImplicitConversionSequence::Worse:
8973       // Cand1 can't be better than Cand2.
8974       return false;
8975 
8976     case ImplicitConversionSequence::Indistinguishable:
8977       // Do nothing.
8978       break;
8979     }
8980   }
8981 
8982   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8983   //       ICSj(F2), or, if not that,
8984   if (HasBetterConversion)
8985     return true;
8986 
8987   //   -- the context is an initialization by user-defined conversion
8988   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8989   //      from the return type of F1 to the destination type (i.e.,
8990   //      the type of the entity being initialized) is a better
8991   //      conversion sequence than the standard conversion sequence
8992   //      from the return type of F2 to the destination type.
8993   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8994       isa<CXXConversionDecl>(Cand1.Function) &&
8995       isa<CXXConversionDecl>(Cand2.Function)) {
8996     // First check whether we prefer one of the conversion functions over the
8997     // other. This only distinguishes the results in non-standard, extension
8998     // cases such as the conversion from a lambda closure type to a function
8999     // pointer or block.
9000     ImplicitConversionSequence::CompareKind Result =
9001         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9002     if (Result == ImplicitConversionSequence::Indistinguishable)
9003       Result = CompareStandardConversionSequences(S, Loc,
9004                                                   Cand1.FinalConversion,
9005                                                   Cand2.FinalConversion);
9006 
9007     if (Result != ImplicitConversionSequence::Indistinguishable)
9008       return Result == ImplicitConversionSequence::Better;
9009 
9010     // FIXME: Compare kind of reference binding if conversion functions
9011     // convert to a reference type used in direct reference binding, per
9012     // C++14 [over.match.best]p1 section 2 bullet 3.
9013   }
9014 
9015   //    -- F1 is generated from a deduction-guide and F2 is not
9016   auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9017   auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9018   if (Guide1 && Guide2 && Guide1->isImplicit() != Guide2->isImplicit())
9019     return Guide2->isImplicit();
9020 
9021   //    -- F1 is a non-template function and F2 is a function template
9022   //       specialization, or, if not that,
9023   bool Cand1IsSpecialization = Cand1.Function &&
9024                                Cand1.Function->getPrimaryTemplate();
9025   bool Cand2IsSpecialization = Cand2.Function &&
9026                                Cand2.Function->getPrimaryTemplate();
9027   if (Cand1IsSpecialization != Cand2IsSpecialization)
9028     return Cand2IsSpecialization;
9029 
9030   //   -- F1 and F2 are function template specializations, and the function
9031   //      template for F1 is more specialized than the template for F2
9032   //      according to the partial ordering rules described in 14.5.5.2, or,
9033   //      if not that,
9034   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9035     if (FunctionTemplateDecl *BetterTemplate
9036           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9037                                          Cand2.Function->getPrimaryTemplate(),
9038                                          Loc,
9039                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9040                                                              : TPOC_Call,
9041                                          Cand1.ExplicitCallArguments,
9042                                          Cand2.ExplicitCallArguments))
9043       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9044   }
9045 
9046   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9047   // A derived-class constructor beats an (inherited) base class constructor.
9048   bool Cand1IsInherited =
9049       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9050   bool Cand2IsInherited =
9051       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9052   if (Cand1IsInherited != Cand2IsInherited)
9053     return Cand2IsInherited;
9054   else if (Cand1IsInherited) {
9055     assert(Cand2IsInherited);
9056     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9057     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9058     if (Cand1Class->isDerivedFrom(Cand2Class))
9059       return true;
9060     if (Cand2Class->isDerivedFrom(Cand1Class))
9061       return false;
9062     // Inherited from sibling base classes: still ambiguous.
9063   }
9064 
9065   // Check for enable_if value-based overload resolution.
9066   if (Cand1.Function && Cand2.Function) {
9067     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9068     if (Cmp != Comparison::Equal)
9069       return Cmp == Comparison::Better;
9070   }
9071 
9072   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9073     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9074     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9075            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9076   }
9077 
9078   bool HasPS1 = Cand1.Function != nullptr &&
9079                 functionHasPassObjectSizeParams(Cand1.Function);
9080   bool HasPS2 = Cand2.Function != nullptr &&
9081                 functionHasPassObjectSizeParams(Cand2.Function);
9082   return HasPS1 != HasPS2 && HasPS1;
9083 }
9084 
9085 /// Determine whether two declarations are "equivalent" for the purposes of
9086 /// name lookup and overload resolution. This applies when the same internal/no
9087 /// linkage entity is defined by two modules (probably by textually including
9088 /// the same header). In such a case, we don't consider the declarations to
9089 /// declare the same entity, but we also don't want lookups with both
9090 /// declarations visible to be ambiguous in some cases (this happens when using
9091 /// a modularized libstdc++).
9092 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9093                                                   const NamedDecl *B) {
9094   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9095   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9096   if (!VA || !VB)
9097     return false;
9098 
9099   // The declarations must be declaring the same name as an internal linkage
9100   // entity in different modules.
9101   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9102           VB->getDeclContext()->getRedeclContext()) ||
9103       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9104           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9105       VA->isExternallyVisible() || VB->isExternallyVisible())
9106     return false;
9107 
9108   // Check that the declarations appear to be equivalent.
9109   //
9110   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9111   // For constants and functions, we should check the initializer or body is
9112   // the same. For non-constant variables, we shouldn't allow it at all.
9113   if (Context.hasSameType(VA->getType(), VB->getType()))
9114     return true;
9115 
9116   // Enum constants within unnamed enumerations will have different types, but
9117   // may still be similar enough to be interchangeable for our purposes.
9118   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9119     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9120       // Only handle anonymous enums. If the enumerations were named and
9121       // equivalent, they would have been merged to the same type.
9122       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9123       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9124       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9125           !Context.hasSameType(EnumA->getIntegerType(),
9126                                EnumB->getIntegerType()))
9127         return false;
9128       // Allow this only if the value is the same for both enumerators.
9129       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9130     }
9131   }
9132 
9133   // Nothing else is sufficiently similar.
9134   return false;
9135 }
9136 
9137 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9138     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9139   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9140 
9141   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9142   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9143       << !M << (M ? M->getFullModuleName() : "");
9144 
9145   for (auto *E : Equiv) {
9146     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9147     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9148         << !M << (M ? M->getFullModuleName() : "");
9149   }
9150 }
9151 
9152 /// \brief Computes the best viable function (C++ 13.3.3)
9153 /// within an overload candidate set.
9154 ///
9155 /// \param Loc The location of the function name (or operator symbol) for
9156 /// which overload resolution occurs.
9157 ///
9158 /// \param Best If overload resolution was successful or found a deleted
9159 /// function, \p Best points to the candidate function found.
9160 ///
9161 /// \returns The result of overload resolution.
9162 OverloadingResult
9163 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9164                                          iterator &Best,
9165                                          bool UserDefinedConversion) {
9166   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9167   std::transform(begin(), end(), std::back_inserter(Candidates),
9168                  [](OverloadCandidate &Cand) { return &Cand; });
9169 
9170   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9171   // are accepted by both clang and NVCC. However, during a particular
9172   // compilation mode only one call variant is viable. We need to
9173   // exclude non-viable overload candidates from consideration based
9174   // only on their host/device attributes. Specifically, if one
9175   // candidate call is WrongSide and the other is SameSide, we ignore
9176   // the WrongSide candidate.
9177   if (S.getLangOpts().CUDA) {
9178     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9179     bool ContainsSameSideCandidate =
9180         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9181           return Cand->Function &&
9182                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9183                      Sema::CFP_SameSide;
9184         });
9185     if (ContainsSameSideCandidate) {
9186       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9187         return Cand->Function &&
9188                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9189                    Sema::CFP_WrongSide;
9190       };
9191       llvm::erase_if(Candidates, IsWrongSideCandidate);
9192     }
9193   }
9194 
9195   // Find the best viable function.
9196   Best = end();
9197   for (auto *Cand : Candidates)
9198     if (Cand->Viable)
9199       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
9200                                                      UserDefinedConversion))
9201         Best = Cand;
9202 
9203   // If we didn't find any viable functions, abort.
9204   if (Best == end())
9205     return OR_No_Viable_Function;
9206 
9207   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9208 
9209   // Make sure that this function is better than every other viable
9210   // function. If not, we have an ambiguity.
9211   for (auto *Cand : Candidates) {
9212     if (Cand->Viable &&
9213         Cand != Best &&
9214         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
9215                                    UserDefinedConversion)) {
9216       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9217                                                    Cand->Function)) {
9218         EquivalentCands.push_back(Cand->Function);
9219         continue;
9220       }
9221 
9222       Best = end();
9223       return OR_Ambiguous;
9224     }
9225   }
9226 
9227   // Best is the best viable function.
9228   if (Best->Function &&
9229       (Best->Function->isDeleted() ||
9230        S.isFunctionConsideredUnavailable(Best->Function)))
9231     return OR_Deleted;
9232 
9233   if (!EquivalentCands.empty())
9234     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9235                                                     EquivalentCands);
9236 
9237   return OR_Success;
9238 }
9239 
9240 namespace {
9241 
9242 enum OverloadCandidateKind {
9243   oc_function,
9244   oc_method,
9245   oc_constructor,
9246   oc_function_template,
9247   oc_method_template,
9248   oc_constructor_template,
9249   oc_implicit_default_constructor,
9250   oc_implicit_copy_constructor,
9251   oc_implicit_move_constructor,
9252   oc_implicit_copy_assignment,
9253   oc_implicit_move_assignment,
9254   oc_inherited_constructor,
9255   oc_inherited_constructor_template
9256 };
9257 
9258 static OverloadCandidateKind
9259 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9260                           std::string &Description) {
9261   bool isTemplate = false;
9262 
9263   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9264     isTemplate = true;
9265     Description = S.getTemplateArgumentBindingsText(
9266       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9267   }
9268 
9269   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9270     if (!Ctor->isImplicit()) {
9271       if (isa<ConstructorUsingShadowDecl>(Found))
9272         return isTemplate ? oc_inherited_constructor_template
9273                           : oc_inherited_constructor;
9274       else
9275         return isTemplate ? oc_constructor_template : oc_constructor;
9276     }
9277 
9278     if (Ctor->isDefaultConstructor())
9279       return oc_implicit_default_constructor;
9280 
9281     if (Ctor->isMoveConstructor())
9282       return oc_implicit_move_constructor;
9283 
9284     assert(Ctor->isCopyConstructor() &&
9285            "unexpected sort of implicit constructor");
9286     return oc_implicit_copy_constructor;
9287   }
9288 
9289   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9290     // This actually gets spelled 'candidate function' for now, but
9291     // it doesn't hurt to split it out.
9292     if (!Meth->isImplicit())
9293       return isTemplate ? oc_method_template : oc_method;
9294 
9295     if (Meth->isMoveAssignmentOperator())
9296       return oc_implicit_move_assignment;
9297 
9298     if (Meth->isCopyAssignmentOperator())
9299       return oc_implicit_copy_assignment;
9300 
9301     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9302     return oc_method;
9303   }
9304 
9305   return isTemplate ? oc_function_template : oc_function;
9306 }
9307 
9308 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9309   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9310   // set.
9311   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9312     S.Diag(FoundDecl->getLocation(),
9313            diag::note_ovl_candidate_inherited_constructor)
9314       << Shadow->getNominatedBaseClass();
9315 }
9316 
9317 } // end anonymous namespace
9318 
9319 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9320                                     const FunctionDecl *FD) {
9321   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9322     bool AlwaysTrue;
9323     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9324       return false;
9325     if (!AlwaysTrue)
9326       return false;
9327   }
9328   return true;
9329 }
9330 
9331 /// \brief Returns true if we can take the address of the function.
9332 ///
9333 /// \param Complain - If true, we'll emit a diagnostic
9334 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9335 ///   we in overload resolution?
9336 /// \param Loc - The location of the statement we're complaining about. Ignored
9337 ///   if we're not complaining, or if we're in overload resolution.
9338 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9339                                               bool Complain,
9340                                               bool InOverloadResolution,
9341                                               SourceLocation Loc) {
9342   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9343     if (Complain) {
9344       if (InOverloadResolution)
9345         S.Diag(FD->getLocStart(),
9346                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9347       else
9348         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9349     }
9350     return false;
9351   }
9352 
9353   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9354     return P->hasAttr<PassObjectSizeAttr>();
9355   });
9356   if (I == FD->param_end())
9357     return true;
9358 
9359   if (Complain) {
9360     // Add one to ParamNo because it's user-facing
9361     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9362     if (InOverloadResolution)
9363       S.Diag(FD->getLocation(),
9364              diag::note_ovl_candidate_has_pass_object_size_params)
9365           << ParamNo;
9366     else
9367       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9368           << FD << ParamNo;
9369   }
9370   return false;
9371 }
9372 
9373 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9374                                                const FunctionDecl *FD) {
9375   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9376                                            /*InOverloadResolution=*/true,
9377                                            /*Loc=*/SourceLocation());
9378 }
9379 
9380 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9381                                              bool Complain,
9382                                              SourceLocation Loc) {
9383   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9384                                              /*InOverloadResolution=*/false,
9385                                              Loc);
9386 }
9387 
9388 // Notes the location of an overload candidate.
9389 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9390                                  QualType DestType, bool TakingAddress) {
9391   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9392     return;
9393 
9394   std::string FnDesc;
9395   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9396   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9397                              << (unsigned) K << Fn << FnDesc;
9398 
9399   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9400   Diag(Fn->getLocation(), PD);
9401   MaybeEmitInheritedConstructorNote(*this, Found);
9402 }
9403 
9404 // Notes the location of all overload candidates designated through
9405 // OverloadedExpr
9406 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9407                                      bool TakingAddress) {
9408   assert(OverloadedExpr->getType() == Context.OverloadTy);
9409 
9410   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9411   OverloadExpr *OvlExpr = Ovl.Expression;
9412 
9413   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9414                             IEnd = OvlExpr->decls_end();
9415        I != IEnd; ++I) {
9416     if (FunctionTemplateDecl *FunTmpl =
9417                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9418       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9419                             TakingAddress);
9420     } else if (FunctionDecl *Fun
9421                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9422       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9423     }
9424   }
9425 }
9426 
9427 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9428 /// "lead" diagnostic; it will be given two arguments, the source and
9429 /// target types of the conversion.
9430 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9431                                  Sema &S,
9432                                  SourceLocation CaretLoc,
9433                                  const PartialDiagnostic &PDiag) const {
9434   S.Diag(CaretLoc, PDiag)
9435     << Ambiguous.getFromType() << Ambiguous.getToType();
9436   // FIXME: The note limiting machinery is borrowed from
9437   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9438   // refactoring here.
9439   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9440   unsigned CandsShown = 0;
9441   AmbiguousConversionSequence::const_iterator I, E;
9442   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9443     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9444       break;
9445     ++CandsShown;
9446     S.NoteOverloadCandidate(I->first, I->second);
9447   }
9448   if (I != E)
9449     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9450 }
9451 
9452 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9453                                   unsigned I, bool TakingCandidateAddress) {
9454   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9455   assert(Conv.isBad());
9456   assert(Cand->Function && "for now, candidate must be a function");
9457   FunctionDecl *Fn = Cand->Function;
9458 
9459   // There's a conversion slot for the object argument if this is a
9460   // non-constructor method.  Note that 'I' corresponds the
9461   // conversion-slot index.
9462   bool isObjectArgument = false;
9463   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9464     if (I == 0)
9465       isObjectArgument = true;
9466     else
9467       I--;
9468   }
9469 
9470   std::string FnDesc;
9471   OverloadCandidateKind FnKind =
9472       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9473 
9474   Expr *FromExpr = Conv.Bad.FromExpr;
9475   QualType FromTy = Conv.Bad.getFromType();
9476   QualType ToTy = Conv.Bad.getToType();
9477 
9478   if (FromTy == S.Context.OverloadTy) {
9479     assert(FromExpr && "overload set argument came from implicit argument?");
9480     Expr *E = FromExpr->IgnoreParens();
9481     if (isa<UnaryOperator>(E))
9482       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9483     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9484 
9485     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9486       << (unsigned) FnKind << FnDesc
9487       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9488       << ToTy << Name << I+1;
9489     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9490     return;
9491   }
9492 
9493   // Do some hand-waving analysis to see if the non-viability is due
9494   // to a qualifier mismatch.
9495   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9496   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9497   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9498     CToTy = RT->getPointeeType();
9499   else {
9500     // TODO: detect and diagnose the full richness of const mismatches.
9501     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9502       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9503         CFromTy = FromPT->getPointeeType();
9504         CToTy = ToPT->getPointeeType();
9505       }
9506   }
9507 
9508   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9509       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9510     Qualifiers FromQs = CFromTy.getQualifiers();
9511     Qualifiers ToQs = CToTy.getQualifiers();
9512 
9513     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9514       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9515         << (unsigned) FnKind << FnDesc
9516         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9517         << FromTy
9518         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9519         << (unsigned) isObjectArgument << I+1;
9520       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9521       return;
9522     }
9523 
9524     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9525       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9526         << (unsigned) FnKind << FnDesc
9527         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9528         << FromTy
9529         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9530         << (unsigned) isObjectArgument << I+1;
9531       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9532       return;
9533     }
9534 
9535     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9536       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9537       << (unsigned) FnKind << FnDesc
9538       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9539       << FromTy
9540       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9541       << (unsigned) isObjectArgument << I+1;
9542       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9543       return;
9544     }
9545 
9546     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9547       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9548         << (unsigned) FnKind << FnDesc
9549         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9550         << FromTy << FromQs.hasUnaligned() << I+1;
9551       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9552       return;
9553     }
9554 
9555     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9556     assert(CVR && "unexpected qualifiers mismatch");
9557 
9558     if (isObjectArgument) {
9559       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9560         << (unsigned) FnKind << FnDesc
9561         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9562         << FromTy << (CVR - 1);
9563     } else {
9564       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9565         << (unsigned) FnKind << FnDesc
9566         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9567         << FromTy << (CVR - 1) << I+1;
9568     }
9569     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9570     return;
9571   }
9572 
9573   // Special diagnostic for failure to convert an initializer list, since
9574   // telling the user that it has type void is not useful.
9575   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9576     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9577       << (unsigned) FnKind << FnDesc
9578       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9579       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9580     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9581     return;
9582   }
9583 
9584   // Diagnose references or pointers to incomplete types differently,
9585   // since it's far from impossible that the incompleteness triggered
9586   // the failure.
9587   QualType TempFromTy = FromTy.getNonReferenceType();
9588   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9589     TempFromTy = PTy->getPointeeType();
9590   if (TempFromTy->isIncompleteType()) {
9591     // Emit the generic diagnostic and, optionally, add the hints to it.
9592     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9593       << (unsigned) FnKind << FnDesc
9594       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9595       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9596       << (unsigned) (Cand->Fix.Kind);
9597 
9598     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9599     return;
9600   }
9601 
9602   // Diagnose base -> derived pointer conversions.
9603   unsigned BaseToDerivedConversion = 0;
9604   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9605     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9606       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9607                                                FromPtrTy->getPointeeType()) &&
9608           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9609           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9610           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9611                           FromPtrTy->getPointeeType()))
9612         BaseToDerivedConversion = 1;
9613     }
9614   } else if (const ObjCObjectPointerType *FromPtrTy
9615                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9616     if (const ObjCObjectPointerType *ToPtrTy
9617                                         = ToTy->getAs<ObjCObjectPointerType>())
9618       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9619         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9620           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9621                                                 FromPtrTy->getPointeeType()) &&
9622               FromIface->isSuperClassOf(ToIface))
9623             BaseToDerivedConversion = 2;
9624   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9625     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9626         !FromTy->isIncompleteType() &&
9627         !ToRefTy->getPointeeType()->isIncompleteType() &&
9628         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9629       BaseToDerivedConversion = 3;
9630     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9631                ToTy.getNonReferenceType().getCanonicalType() ==
9632                FromTy.getNonReferenceType().getCanonicalType()) {
9633       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9634         << (unsigned) FnKind << FnDesc
9635         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9636         << (unsigned) isObjectArgument << I + 1;
9637       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9638       return;
9639     }
9640   }
9641 
9642   if (BaseToDerivedConversion) {
9643     S.Diag(Fn->getLocation(),
9644            diag::note_ovl_candidate_bad_base_to_derived_conv)
9645       << (unsigned) FnKind << FnDesc
9646       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9647       << (BaseToDerivedConversion - 1)
9648       << FromTy << ToTy << I+1;
9649     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9650     return;
9651   }
9652 
9653   if (isa<ObjCObjectPointerType>(CFromTy) &&
9654       isa<PointerType>(CToTy)) {
9655       Qualifiers FromQs = CFromTy.getQualifiers();
9656       Qualifiers ToQs = CToTy.getQualifiers();
9657       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9658         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9659         << (unsigned) FnKind << FnDesc
9660         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9661         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9662         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9663         return;
9664       }
9665   }
9666 
9667   if (TakingCandidateAddress &&
9668       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9669     return;
9670 
9671   // Emit the generic diagnostic and, optionally, add the hints to it.
9672   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9673   FDiag << (unsigned) FnKind << FnDesc
9674     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9675     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9676     << (unsigned) (Cand->Fix.Kind);
9677 
9678   // If we can fix the conversion, suggest the FixIts.
9679   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9680        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9681     FDiag << *HI;
9682   S.Diag(Fn->getLocation(), FDiag);
9683 
9684   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9685 }
9686 
9687 /// Additional arity mismatch diagnosis specific to a function overload
9688 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9689 /// over a candidate in any candidate set.
9690 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9691                                unsigned NumArgs) {
9692   FunctionDecl *Fn = Cand->Function;
9693   unsigned MinParams = Fn->getMinRequiredArguments();
9694 
9695   // With invalid overloaded operators, it's possible that we think we
9696   // have an arity mismatch when in fact it looks like we have the
9697   // right number of arguments, because only overloaded operators have
9698   // the weird behavior of overloading member and non-member functions.
9699   // Just don't report anything.
9700   if (Fn->isInvalidDecl() &&
9701       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9702     return true;
9703 
9704   if (NumArgs < MinParams) {
9705     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9706            (Cand->FailureKind == ovl_fail_bad_deduction &&
9707             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9708   } else {
9709     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9710            (Cand->FailureKind == ovl_fail_bad_deduction &&
9711             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9712   }
9713 
9714   return false;
9715 }
9716 
9717 /// General arity mismatch diagnosis over a candidate in a candidate set.
9718 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9719                                   unsigned NumFormalArgs) {
9720   assert(isa<FunctionDecl>(D) &&
9721       "The templated declaration should at least be a function"
9722       " when diagnosing bad template argument deduction due to too many"
9723       " or too few arguments");
9724 
9725   FunctionDecl *Fn = cast<FunctionDecl>(D);
9726 
9727   // TODO: treat calls to a missing default constructor as a special case
9728   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9729   unsigned MinParams = Fn->getMinRequiredArguments();
9730 
9731   // at least / at most / exactly
9732   unsigned mode, modeCount;
9733   if (NumFormalArgs < MinParams) {
9734     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9735         FnTy->isTemplateVariadic())
9736       mode = 0; // "at least"
9737     else
9738       mode = 2; // "exactly"
9739     modeCount = MinParams;
9740   } else {
9741     if (MinParams != FnTy->getNumParams())
9742       mode = 1; // "at most"
9743     else
9744       mode = 2; // "exactly"
9745     modeCount = FnTy->getNumParams();
9746   }
9747 
9748   std::string Description;
9749   OverloadCandidateKind FnKind =
9750       ClassifyOverloadCandidate(S, Found, Fn, Description);
9751 
9752   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9753     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9754       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9755       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9756   else
9757     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9758       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9759       << mode << modeCount << NumFormalArgs;
9760   MaybeEmitInheritedConstructorNote(S, Found);
9761 }
9762 
9763 /// Arity mismatch diagnosis specific to a function overload candidate.
9764 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9765                                   unsigned NumFormalArgs) {
9766   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9767     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9768 }
9769 
9770 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9771   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9772     return TD;
9773   llvm_unreachable("Unsupported: Getting the described template declaration"
9774                    " for bad deduction diagnosis");
9775 }
9776 
9777 /// Diagnose a failed template-argument deduction.
9778 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9779                                  DeductionFailureInfo &DeductionFailure,
9780                                  unsigned NumArgs,
9781                                  bool TakingCandidateAddress) {
9782   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9783   NamedDecl *ParamD;
9784   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9785   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9786   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9787   switch (DeductionFailure.Result) {
9788   case Sema::TDK_Success:
9789     llvm_unreachable("TDK_success while diagnosing bad deduction");
9790 
9791   case Sema::TDK_Incomplete: {
9792     assert(ParamD && "no parameter found for incomplete deduction result");
9793     S.Diag(Templated->getLocation(),
9794            diag::note_ovl_candidate_incomplete_deduction)
9795         << ParamD->getDeclName();
9796     MaybeEmitInheritedConstructorNote(S, Found);
9797     return;
9798   }
9799 
9800   case Sema::TDK_Underqualified: {
9801     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9802     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9803 
9804     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9805 
9806     // Param will have been canonicalized, but it should just be a
9807     // qualified version of ParamD, so move the qualifiers to that.
9808     QualifierCollector Qs;
9809     Qs.strip(Param);
9810     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9811     assert(S.Context.hasSameType(Param, NonCanonParam));
9812 
9813     // Arg has also been canonicalized, but there's nothing we can do
9814     // about that.  It also doesn't matter as much, because it won't
9815     // have any template parameters in it (because deduction isn't
9816     // done on dependent types).
9817     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9818 
9819     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9820         << ParamD->getDeclName() << Arg << NonCanonParam;
9821     MaybeEmitInheritedConstructorNote(S, Found);
9822     return;
9823   }
9824 
9825   case Sema::TDK_Inconsistent: {
9826     assert(ParamD && "no parameter found for inconsistent deduction result");
9827     int which = 0;
9828     if (isa<TemplateTypeParmDecl>(ParamD))
9829       which = 0;
9830     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9831       // Deduction might have failed because we deduced arguments of two
9832       // different types for a non-type template parameter.
9833       // FIXME: Use a different TDK value for this.
9834       QualType T1 =
9835           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9836       QualType T2 =
9837           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9838       if (!S.Context.hasSameType(T1, T2)) {
9839         S.Diag(Templated->getLocation(),
9840                diag::note_ovl_candidate_inconsistent_deduction_types)
9841           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9842           << *DeductionFailure.getSecondArg() << T2;
9843         MaybeEmitInheritedConstructorNote(S, Found);
9844         return;
9845       }
9846 
9847       which = 1;
9848     } else {
9849       which = 2;
9850     }
9851 
9852     S.Diag(Templated->getLocation(),
9853            diag::note_ovl_candidate_inconsistent_deduction)
9854         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9855         << *DeductionFailure.getSecondArg();
9856     MaybeEmitInheritedConstructorNote(S, Found);
9857     return;
9858   }
9859 
9860   case Sema::TDK_InvalidExplicitArguments:
9861     assert(ParamD && "no parameter found for invalid explicit arguments");
9862     if (ParamD->getDeclName())
9863       S.Diag(Templated->getLocation(),
9864              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9865           << ParamD->getDeclName();
9866     else {
9867       int index = 0;
9868       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9869         index = TTP->getIndex();
9870       else if (NonTypeTemplateParmDecl *NTTP
9871                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9872         index = NTTP->getIndex();
9873       else
9874         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9875       S.Diag(Templated->getLocation(),
9876              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9877           << (index + 1);
9878     }
9879     MaybeEmitInheritedConstructorNote(S, Found);
9880     return;
9881 
9882   case Sema::TDK_TooManyArguments:
9883   case Sema::TDK_TooFewArguments:
9884     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9885     return;
9886 
9887   case Sema::TDK_InstantiationDepth:
9888     S.Diag(Templated->getLocation(),
9889            diag::note_ovl_candidate_instantiation_depth);
9890     MaybeEmitInheritedConstructorNote(S, Found);
9891     return;
9892 
9893   case Sema::TDK_SubstitutionFailure: {
9894     // Format the template argument list into the argument string.
9895     SmallString<128> TemplateArgString;
9896     if (TemplateArgumentList *Args =
9897             DeductionFailure.getTemplateArgumentList()) {
9898       TemplateArgString = " ";
9899       TemplateArgString += S.getTemplateArgumentBindingsText(
9900           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9901     }
9902 
9903     // If this candidate was disabled by enable_if, say so.
9904     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9905     if (PDiag && PDiag->second.getDiagID() ==
9906           diag::err_typename_nested_not_found_enable_if) {
9907       // FIXME: Use the source range of the condition, and the fully-qualified
9908       //        name of the enable_if template. These are both present in PDiag.
9909       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9910         << "'enable_if'" << TemplateArgString;
9911       return;
9912     }
9913 
9914     // Format the SFINAE diagnostic into the argument string.
9915     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9916     //        formatted message in another diagnostic.
9917     SmallString<128> SFINAEArgString;
9918     SourceRange R;
9919     if (PDiag) {
9920       SFINAEArgString = ": ";
9921       R = SourceRange(PDiag->first, PDiag->first);
9922       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9923     }
9924 
9925     S.Diag(Templated->getLocation(),
9926            diag::note_ovl_candidate_substitution_failure)
9927         << TemplateArgString << SFINAEArgString << R;
9928     MaybeEmitInheritedConstructorNote(S, Found);
9929     return;
9930   }
9931 
9932   case Sema::TDK_DeducedMismatch:
9933   case Sema::TDK_DeducedMismatchNested: {
9934     // Format the template argument list into the argument string.
9935     SmallString<128> TemplateArgString;
9936     if (TemplateArgumentList *Args =
9937             DeductionFailure.getTemplateArgumentList()) {
9938       TemplateArgString = " ";
9939       TemplateArgString += S.getTemplateArgumentBindingsText(
9940           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9941     }
9942 
9943     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9944         << (*DeductionFailure.getCallArgIndex() + 1)
9945         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9946         << TemplateArgString
9947         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9948     break;
9949   }
9950 
9951   case Sema::TDK_NonDeducedMismatch: {
9952     // FIXME: Provide a source location to indicate what we couldn't match.
9953     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9954     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9955     if (FirstTA.getKind() == TemplateArgument::Template &&
9956         SecondTA.getKind() == TemplateArgument::Template) {
9957       TemplateName FirstTN = FirstTA.getAsTemplate();
9958       TemplateName SecondTN = SecondTA.getAsTemplate();
9959       if (FirstTN.getKind() == TemplateName::Template &&
9960           SecondTN.getKind() == TemplateName::Template) {
9961         if (FirstTN.getAsTemplateDecl()->getName() ==
9962             SecondTN.getAsTemplateDecl()->getName()) {
9963           // FIXME: This fixes a bad diagnostic where both templates are named
9964           // the same.  This particular case is a bit difficult since:
9965           // 1) It is passed as a string to the diagnostic printer.
9966           // 2) The diagnostic printer only attempts to find a better
9967           //    name for types, not decls.
9968           // Ideally, this should folded into the diagnostic printer.
9969           S.Diag(Templated->getLocation(),
9970                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9971               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9972           return;
9973         }
9974       }
9975     }
9976 
9977     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9978         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9979       return;
9980 
9981     // FIXME: For generic lambda parameters, check if the function is a lambda
9982     // call operator, and if so, emit a prettier and more informative
9983     // diagnostic that mentions 'auto' and lambda in addition to
9984     // (or instead of?) the canonical template type parameters.
9985     S.Diag(Templated->getLocation(),
9986            diag::note_ovl_candidate_non_deduced_mismatch)
9987         << FirstTA << SecondTA;
9988     return;
9989   }
9990   // TODO: diagnose these individually, then kill off
9991   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9992   case Sema::TDK_MiscellaneousDeductionFailure:
9993     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9994     MaybeEmitInheritedConstructorNote(S, Found);
9995     return;
9996   case Sema::TDK_CUDATargetMismatch:
9997     S.Diag(Templated->getLocation(),
9998            diag::note_cuda_ovl_candidate_target_mismatch);
9999     return;
10000   }
10001 }
10002 
10003 /// Diagnose a failed template-argument deduction, for function calls.
10004 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10005                                  unsigned NumArgs,
10006                                  bool TakingCandidateAddress) {
10007   unsigned TDK = Cand->DeductionFailure.Result;
10008   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10009     if (CheckArityMismatch(S, Cand, NumArgs))
10010       return;
10011   }
10012   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10013                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10014 }
10015 
10016 /// CUDA: diagnose an invalid call across targets.
10017 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10018   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10019   FunctionDecl *Callee = Cand->Function;
10020 
10021   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10022                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10023 
10024   std::string FnDesc;
10025   OverloadCandidateKind FnKind =
10026       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10027 
10028   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10029       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10030 
10031   // This could be an implicit constructor for which we could not infer the
10032   // target due to a collsion. Diagnose that case.
10033   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10034   if (Meth != nullptr && Meth->isImplicit()) {
10035     CXXRecordDecl *ParentClass = Meth->getParent();
10036     Sema::CXXSpecialMember CSM;
10037 
10038     switch (FnKind) {
10039     default:
10040       return;
10041     case oc_implicit_default_constructor:
10042       CSM = Sema::CXXDefaultConstructor;
10043       break;
10044     case oc_implicit_copy_constructor:
10045       CSM = Sema::CXXCopyConstructor;
10046       break;
10047     case oc_implicit_move_constructor:
10048       CSM = Sema::CXXMoveConstructor;
10049       break;
10050     case oc_implicit_copy_assignment:
10051       CSM = Sema::CXXCopyAssignment;
10052       break;
10053     case oc_implicit_move_assignment:
10054       CSM = Sema::CXXMoveAssignment;
10055       break;
10056     };
10057 
10058     bool ConstRHS = false;
10059     if (Meth->getNumParams()) {
10060       if (const ReferenceType *RT =
10061               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10062         ConstRHS = RT->getPointeeType().isConstQualified();
10063       }
10064     }
10065 
10066     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10067                                               /* ConstRHS */ ConstRHS,
10068                                               /* Diagnose */ true);
10069   }
10070 }
10071 
10072 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10073   FunctionDecl *Callee = Cand->Function;
10074   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10075 
10076   S.Diag(Callee->getLocation(),
10077          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10078       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10079 }
10080 
10081 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10082   FunctionDecl *Callee = Cand->Function;
10083 
10084   S.Diag(Callee->getLocation(),
10085          diag::note_ovl_candidate_disabled_by_extension);
10086 }
10087 
10088 /// Generates a 'note' diagnostic for an overload candidate.  We've
10089 /// already generated a primary error at the call site.
10090 ///
10091 /// It really does need to be a single diagnostic with its caret
10092 /// pointed at the candidate declaration.  Yes, this creates some
10093 /// major challenges of technical writing.  Yes, this makes pointing
10094 /// out problems with specific arguments quite awkward.  It's still
10095 /// better than generating twenty screens of text for every failed
10096 /// overload.
10097 ///
10098 /// It would be great to be able to express per-candidate problems
10099 /// more richly for those diagnostic clients that cared, but we'd
10100 /// still have to be just as careful with the default diagnostics.
10101 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10102                                   unsigned NumArgs,
10103                                   bool TakingCandidateAddress) {
10104   FunctionDecl *Fn = Cand->Function;
10105 
10106   // Note deleted candidates, but only if they're viable.
10107   if (Cand->Viable) {
10108     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10109       std::string FnDesc;
10110       OverloadCandidateKind FnKind =
10111         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10112 
10113       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10114         << FnKind << FnDesc
10115         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10116       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10117       return;
10118     }
10119 
10120     // We don't really have anything else to say about viable candidates.
10121     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10122     return;
10123   }
10124 
10125   switch (Cand->FailureKind) {
10126   case ovl_fail_too_many_arguments:
10127   case ovl_fail_too_few_arguments:
10128     return DiagnoseArityMismatch(S, Cand, NumArgs);
10129 
10130   case ovl_fail_bad_deduction:
10131     return DiagnoseBadDeduction(S, Cand, NumArgs,
10132                                 TakingCandidateAddress);
10133 
10134   case ovl_fail_illegal_constructor: {
10135     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10136       << (Fn->getPrimaryTemplate() ? 1 : 0);
10137     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10138     return;
10139   }
10140 
10141   case ovl_fail_trivial_conversion:
10142   case ovl_fail_bad_final_conversion:
10143   case ovl_fail_final_conversion_not_exact:
10144     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10145 
10146   case ovl_fail_bad_conversion: {
10147     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10148     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10149       if (Cand->Conversions[I].isBad())
10150         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10151 
10152     // FIXME: this currently happens when we're called from SemaInit
10153     // when user-conversion overload fails.  Figure out how to handle
10154     // those conditions and diagnose them well.
10155     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10156   }
10157 
10158   case ovl_fail_bad_target:
10159     return DiagnoseBadTarget(S, Cand);
10160 
10161   case ovl_fail_enable_if:
10162     return DiagnoseFailedEnableIfAttr(S, Cand);
10163 
10164   case ovl_fail_ext_disabled:
10165     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10166 
10167   case ovl_fail_inhctor_slice:
10168     // It's generally not interesting to note copy/move constructors here.
10169     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10170       return;
10171     S.Diag(Fn->getLocation(),
10172            diag::note_ovl_candidate_inherited_constructor_slice)
10173       << (Fn->getPrimaryTemplate() ? 1 : 0)
10174       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10175     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10176     return;
10177 
10178   case ovl_fail_addr_not_available: {
10179     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10180     (void)Available;
10181     assert(!Available);
10182     break;
10183   }
10184   }
10185 }
10186 
10187 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10188   // Desugar the type of the surrogate down to a function type,
10189   // retaining as many typedefs as possible while still showing
10190   // the function type (and, therefore, its parameter types).
10191   QualType FnType = Cand->Surrogate->getConversionType();
10192   bool isLValueReference = false;
10193   bool isRValueReference = false;
10194   bool isPointer = false;
10195   if (const LValueReferenceType *FnTypeRef =
10196         FnType->getAs<LValueReferenceType>()) {
10197     FnType = FnTypeRef->getPointeeType();
10198     isLValueReference = true;
10199   } else if (const RValueReferenceType *FnTypeRef =
10200                FnType->getAs<RValueReferenceType>()) {
10201     FnType = FnTypeRef->getPointeeType();
10202     isRValueReference = true;
10203   }
10204   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10205     FnType = FnTypePtr->getPointeeType();
10206     isPointer = true;
10207   }
10208   // Desugar down to a function type.
10209   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10210   // Reconstruct the pointer/reference as appropriate.
10211   if (isPointer) FnType = S.Context.getPointerType(FnType);
10212   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10213   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10214 
10215   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10216     << FnType;
10217 }
10218 
10219 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10220                                          SourceLocation OpLoc,
10221                                          OverloadCandidate *Cand) {
10222   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10223   std::string TypeStr("operator");
10224   TypeStr += Opc;
10225   TypeStr += "(";
10226   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
10227   if (Cand->Conversions.size() == 1) {
10228     TypeStr += ")";
10229     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10230   } else {
10231     TypeStr += ", ";
10232     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10233     TypeStr += ")";
10234     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10235   }
10236 }
10237 
10238 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10239                                          OverloadCandidate *Cand) {
10240   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10241     if (ICS.isBad()) break; // all meaningless after first invalid
10242     if (!ICS.isAmbiguous()) continue;
10243 
10244     ICS.DiagnoseAmbiguousConversion(
10245         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10246   }
10247 }
10248 
10249 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10250   if (Cand->Function)
10251     return Cand->Function->getLocation();
10252   if (Cand->IsSurrogate)
10253     return Cand->Surrogate->getLocation();
10254   return SourceLocation();
10255 }
10256 
10257 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10258   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10259   case Sema::TDK_Success:
10260   case Sema::TDK_NonDependentConversionFailure:
10261     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10262 
10263   case Sema::TDK_Invalid:
10264   case Sema::TDK_Incomplete:
10265     return 1;
10266 
10267   case Sema::TDK_Underqualified:
10268   case Sema::TDK_Inconsistent:
10269     return 2;
10270 
10271   case Sema::TDK_SubstitutionFailure:
10272   case Sema::TDK_DeducedMismatch:
10273   case Sema::TDK_DeducedMismatchNested:
10274   case Sema::TDK_NonDeducedMismatch:
10275   case Sema::TDK_MiscellaneousDeductionFailure:
10276   case Sema::TDK_CUDATargetMismatch:
10277     return 3;
10278 
10279   case Sema::TDK_InstantiationDepth:
10280     return 4;
10281 
10282   case Sema::TDK_InvalidExplicitArguments:
10283     return 5;
10284 
10285   case Sema::TDK_TooManyArguments:
10286   case Sema::TDK_TooFewArguments:
10287     return 6;
10288   }
10289   llvm_unreachable("Unhandled deduction result");
10290 }
10291 
10292 namespace {
10293 struct CompareOverloadCandidatesForDisplay {
10294   Sema &S;
10295   SourceLocation Loc;
10296   size_t NumArgs;
10297 
10298   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
10299       : S(S), NumArgs(nArgs) {}
10300 
10301   bool operator()(const OverloadCandidate *L,
10302                   const OverloadCandidate *R) {
10303     // Fast-path this check.
10304     if (L == R) return false;
10305 
10306     // Order first by viability.
10307     if (L->Viable) {
10308       if (!R->Viable) return true;
10309 
10310       // TODO: introduce a tri-valued comparison for overload
10311       // candidates.  Would be more worthwhile if we had a sort
10312       // that could exploit it.
10313       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10314       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10315     } else if (R->Viable)
10316       return false;
10317 
10318     assert(L->Viable == R->Viable);
10319 
10320     // Criteria by which we can sort non-viable candidates:
10321     if (!L->Viable) {
10322       // 1. Arity mismatches come after other candidates.
10323       if (L->FailureKind == ovl_fail_too_many_arguments ||
10324           L->FailureKind == ovl_fail_too_few_arguments) {
10325         if (R->FailureKind == ovl_fail_too_many_arguments ||
10326             R->FailureKind == ovl_fail_too_few_arguments) {
10327           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10328           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10329           if (LDist == RDist) {
10330             if (L->FailureKind == R->FailureKind)
10331               // Sort non-surrogates before surrogates.
10332               return !L->IsSurrogate && R->IsSurrogate;
10333             // Sort candidates requiring fewer parameters than there were
10334             // arguments given after candidates requiring more parameters
10335             // than there were arguments given.
10336             return L->FailureKind == ovl_fail_too_many_arguments;
10337           }
10338           return LDist < RDist;
10339         }
10340         return false;
10341       }
10342       if (R->FailureKind == ovl_fail_too_many_arguments ||
10343           R->FailureKind == ovl_fail_too_few_arguments)
10344         return true;
10345 
10346       // 2. Bad conversions come first and are ordered by the number
10347       // of bad conversions and quality of good conversions.
10348       if (L->FailureKind == ovl_fail_bad_conversion) {
10349         if (R->FailureKind != ovl_fail_bad_conversion)
10350           return true;
10351 
10352         // The conversion that can be fixed with a smaller number of changes,
10353         // comes first.
10354         unsigned numLFixes = L->Fix.NumConversionsFixed;
10355         unsigned numRFixes = R->Fix.NumConversionsFixed;
10356         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10357         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10358         if (numLFixes != numRFixes) {
10359           return numLFixes < numRFixes;
10360         }
10361 
10362         // If there's any ordering between the defined conversions...
10363         // FIXME: this might not be transitive.
10364         assert(L->Conversions.size() == R->Conversions.size());
10365 
10366         int leftBetter = 0;
10367         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10368         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10369           switch (CompareImplicitConversionSequences(S, Loc,
10370                                                      L->Conversions[I],
10371                                                      R->Conversions[I])) {
10372           case ImplicitConversionSequence::Better:
10373             leftBetter++;
10374             break;
10375 
10376           case ImplicitConversionSequence::Worse:
10377             leftBetter--;
10378             break;
10379 
10380           case ImplicitConversionSequence::Indistinguishable:
10381             break;
10382           }
10383         }
10384         if (leftBetter > 0) return true;
10385         if (leftBetter < 0) return false;
10386 
10387       } else if (R->FailureKind == ovl_fail_bad_conversion)
10388         return false;
10389 
10390       if (L->FailureKind == ovl_fail_bad_deduction) {
10391         if (R->FailureKind != ovl_fail_bad_deduction)
10392           return true;
10393 
10394         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10395           return RankDeductionFailure(L->DeductionFailure)
10396                < RankDeductionFailure(R->DeductionFailure);
10397       } else if (R->FailureKind == ovl_fail_bad_deduction)
10398         return false;
10399 
10400       // TODO: others?
10401     }
10402 
10403     // Sort everything else by location.
10404     SourceLocation LLoc = GetLocationForCandidate(L);
10405     SourceLocation RLoc = GetLocationForCandidate(R);
10406 
10407     // Put candidates without locations (e.g. builtins) at the end.
10408     if (LLoc.isInvalid()) return false;
10409     if (RLoc.isInvalid()) return true;
10410 
10411     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10412   }
10413 };
10414 }
10415 
10416 /// CompleteNonViableCandidate - Normally, overload resolution only
10417 /// computes up to the first bad conversion. Produces the FixIt set if
10418 /// possible.
10419 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10420                                        ArrayRef<Expr *> Args) {
10421   assert(!Cand->Viable);
10422 
10423   // Don't do anything on failures other than bad conversion.
10424   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10425 
10426   // We only want the FixIts if all the arguments can be corrected.
10427   bool Unfixable = false;
10428   // Use a implicit copy initialization to check conversion fixes.
10429   Cand->Fix.setConversionChecker(TryCopyInitialization);
10430 
10431   // Attempt to fix the bad conversion.
10432   unsigned ConvCount = Cand->Conversions.size();
10433   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10434        ++ConvIdx) {
10435     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10436     if (Cand->Conversions[ConvIdx].isInitialized() &&
10437         Cand->Conversions[ConvIdx].isBad()) {
10438       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10439       break;
10440     }
10441   }
10442 
10443   // FIXME: this should probably be preserved from the overload
10444   // operation somehow.
10445   bool SuppressUserConversions = false;
10446 
10447   unsigned ConvIdx = 0;
10448   ArrayRef<QualType> ParamTypes;
10449 
10450   if (Cand->IsSurrogate) {
10451     QualType ConvType
10452       = Cand->Surrogate->getConversionType().getNonReferenceType();
10453     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10454       ConvType = ConvPtrType->getPointeeType();
10455     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10456     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10457     ConvIdx = 1;
10458   } else if (Cand->Function) {
10459     ParamTypes =
10460         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10461     if (isa<CXXMethodDecl>(Cand->Function) &&
10462         !isa<CXXConstructorDecl>(Cand->Function)) {
10463       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10464       ConvIdx = 1;
10465     }
10466   } else {
10467     // Builtin operator.
10468     assert(ConvCount <= 3);
10469     ParamTypes = Cand->BuiltinTypes.ParamTypes;
10470   }
10471 
10472   // Fill in the rest of the conversions.
10473   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10474     if (Cand->Conversions[ConvIdx].isInitialized()) {
10475       // We've already checked this conversion.
10476     } else if (ArgIdx < ParamTypes.size()) {
10477       if (ParamTypes[ArgIdx]->isDependentType())
10478         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10479             Args[ArgIdx]->getType());
10480       else {
10481         Cand->Conversions[ConvIdx] =
10482             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10483                                   SuppressUserConversions,
10484                                   /*InOverloadResolution=*/true,
10485                                   /*AllowObjCWritebackConversion=*/
10486                                   S.getLangOpts().ObjCAutoRefCount);
10487         // Store the FixIt in the candidate if it exists.
10488         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10489           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10490       }
10491     } else
10492       Cand->Conversions[ConvIdx].setEllipsis();
10493   }
10494 }
10495 
10496 /// PrintOverloadCandidates - When overload resolution fails, prints
10497 /// diagnostic messages containing the candidates in the candidate
10498 /// set.
10499 void OverloadCandidateSet::NoteCandidates(
10500     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10501     StringRef Opc, SourceLocation OpLoc,
10502     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10503   // Sort the candidates by viability and position.  Sorting directly would
10504   // be prohibitive, so we make a set of pointers and sort those.
10505   SmallVector<OverloadCandidate*, 32> Cands;
10506   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10507   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10508     if (!Filter(*Cand))
10509       continue;
10510     if (Cand->Viable)
10511       Cands.push_back(Cand);
10512     else if (OCD == OCD_AllCandidates) {
10513       CompleteNonViableCandidate(S, Cand, Args);
10514       if (Cand->Function || Cand->IsSurrogate)
10515         Cands.push_back(Cand);
10516       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10517       // want to list every possible builtin candidate.
10518     }
10519   }
10520 
10521   std::sort(Cands.begin(), Cands.end(),
10522             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10523 
10524   bool ReportedAmbiguousConversions = false;
10525 
10526   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10527   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10528   unsigned CandsShown = 0;
10529   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10530     OverloadCandidate *Cand = *I;
10531 
10532     // Set an arbitrary limit on the number of candidate functions we'll spam
10533     // the user with.  FIXME: This limit should depend on details of the
10534     // candidate list.
10535     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10536       break;
10537     }
10538     ++CandsShown;
10539 
10540     if (Cand->Function)
10541       NoteFunctionCandidate(S, Cand, Args.size(),
10542                             /*TakingCandidateAddress=*/false);
10543     else if (Cand->IsSurrogate)
10544       NoteSurrogateCandidate(S, Cand);
10545     else {
10546       assert(Cand->Viable &&
10547              "Non-viable built-in candidates are not added to Cands.");
10548       // Generally we only see ambiguities including viable builtin
10549       // operators if overload resolution got screwed up by an
10550       // ambiguous user-defined conversion.
10551       //
10552       // FIXME: It's quite possible for different conversions to see
10553       // different ambiguities, though.
10554       if (!ReportedAmbiguousConversions) {
10555         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10556         ReportedAmbiguousConversions = true;
10557       }
10558 
10559       // If this is a viable builtin, print it.
10560       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10561     }
10562   }
10563 
10564   if (I != E)
10565     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10566 }
10567 
10568 static SourceLocation
10569 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10570   return Cand->Specialization ? Cand->Specialization->getLocation()
10571                               : SourceLocation();
10572 }
10573 
10574 namespace {
10575 struct CompareTemplateSpecCandidatesForDisplay {
10576   Sema &S;
10577   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10578 
10579   bool operator()(const TemplateSpecCandidate *L,
10580                   const TemplateSpecCandidate *R) {
10581     // Fast-path this check.
10582     if (L == R)
10583       return false;
10584 
10585     // Assuming that both candidates are not matches...
10586 
10587     // Sort by the ranking of deduction failures.
10588     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10589       return RankDeductionFailure(L->DeductionFailure) <
10590              RankDeductionFailure(R->DeductionFailure);
10591 
10592     // Sort everything else by location.
10593     SourceLocation LLoc = GetLocationForCandidate(L);
10594     SourceLocation RLoc = GetLocationForCandidate(R);
10595 
10596     // Put candidates without locations (e.g. builtins) at the end.
10597     if (LLoc.isInvalid())
10598       return false;
10599     if (RLoc.isInvalid())
10600       return true;
10601 
10602     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10603   }
10604 };
10605 }
10606 
10607 /// Diagnose a template argument deduction failure.
10608 /// We are treating these failures as overload failures due to bad
10609 /// deductions.
10610 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10611                                                  bool ForTakingAddress) {
10612   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10613                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10614 }
10615 
10616 void TemplateSpecCandidateSet::destroyCandidates() {
10617   for (iterator i = begin(), e = end(); i != e; ++i) {
10618     i->DeductionFailure.Destroy();
10619   }
10620 }
10621 
10622 void TemplateSpecCandidateSet::clear() {
10623   destroyCandidates();
10624   Candidates.clear();
10625 }
10626 
10627 /// NoteCandidates - When no template specialization match is found, prints
10628 /// diagnostic messages containing the non-matching specializations that form
10629 /// the candidate set.
10630 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10631 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10632 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10633   // Sort the candidates by position (assuming no candidate is a match).
10634   // Sorting directly would be prohibitive, so we make a set of pointers
10635   // and sort those.
10636   SmallVector<TemplateSpecCandidate *, 32> Cands;
10637   Cands.reserve(size());
10638   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10639     if (Cand->Specialization)
10640       Cands.push_back(Cand);
10641     // Otherwise, this is a non-matching builtin candidate.  We do not,
10642     // in general, want to list every possible builtin candidate.
10643   }
10644 
10645   std::sort(Cands.begin(), Cands.end(),
10646             CompareTemplateSpecCandidatesForDisplay(S));
10647 
10648   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10649   // for generalization purposes (?).
10650   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10651 
10652   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10653   unsigned CandsShown = 0;
10654   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10655     TemplateSpecCandidate *Cand = *I;
10656 
10657     // Set an arbitrary limit on the number of candidates we'll spam
10658     // the user with.  FIXME: This limit should depend on details of the
10659     // candidate list.
10660     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10661       break;
10662     ++CandsShown;
10663 
10664     assert(Cand->Specialization &&
10665            "Non-matching built-in candidates are not added to Cands.");
10666     Cand->NoteDeductionFailure(S, ForTakingAddress);
10667   }
10668 
10669   if (I != E)
10670     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10671 }
10672 
10673 // [PossiblyAFunctionType]  -->   [Return]
10674 // NonFunctionType --> NonFunctionType
10675 // R (A) --> R(A)
10676 // R (*)(A) --> R (A)
10677 // R (&)(A) --> R (A)
10678 // R (S::*)(A) --> R (A)
10679 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10680   QualType Ret = PossiblyAFunctionType;
10681   if (const PointerType *ToTypePtr =
10682     PossiblyAFunctionType->getAs<PointerType>())
10683     Ret = ToTypePtr->getPointeeType();
10684   else if (const ReferenceType *ToTypeRef =
10685     PossiblyAFunctionType->getAs<ReferenceType>())
10686     Ret = ToTypeRef->getPointeeType();
10687   else if (const MemberPointerType *MemTypePtr =
10688     PossiblyAFunctionType->getAs<MemberPointerType>())
10689     Ret = MemTypePtr->getPointeeType();
10690   Ret =
10691     Context.getCanonicalType(Ret).getUnqualifiedType();
10692   return Ret;
10693 }
10694 
10695 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10696                                  bool Complain = true) {
10697   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10698       S.DeduceReturnType(FD, Loc, Complain))
10699     return true;
10700 
10701   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10702   if (S.getLangOpts().CPlusPlus1z &&
10703       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10704       !S.ResolveExceptionSpec(Loc, FPT))
10705     return true;
10706 
10707   return false;
10708 }
10709 
10710 namespace {
10711 // A helper class to help with address of function resolution
10712 // - allows us to avoid passing around all those ugly parameters
10713 class AddressOfFunctionResolver {
10714   Sema& S;
10715   Expr* SourceExpr;
10716   const QualType& TargetType;
10717   QualType TargetFunctionType; // Extracted function type from target type
10718 
10719   bool Complain;
10720   //DeclAccessPair& ResultFunctionAccessPair;
10721   ASTContext& Context;
10722 
10723   bool TargetTypeIsNonStaticMemberFunction;
10724   bool FoundNonTemplateFunction;
10725   bool StaticMemberFunctionFromBoundPointer;
10726   bool HasComplained;
10727 
10728   OverloadExpr::FindResult OvlExprInfo;
10729   OverloadExpr *OvlExpr;
10730   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10731   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10732   TemplateSpecCandidateSet FailedCandidates;
10733 
10734 public:
10735   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10736                             const QualType &TargetType, bool Complain)
10737       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10738         Complain(Complain), Context(S.getASTContext()),
10739         TargetTypeIsNonStaticMemberFunction(
10740             !!TargetType->getAs<MemberPointerType>()),
10741         FoundNonTemplateFunction(false),
10742         StaticMemberFunctionFromBoundPointer(false),
10743         HasComplained(false),
10744         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10745         OvlExpr(OvlExprInfo.Expression),
10746         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10747     ExtractUnqualifiedFunctionTypeFromTargetType();
10748 
10749     if (TargetFunctionType->isFunctionType()) {
10750       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10751         if (!UME->isImplicitAccess() &&
10752             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10753           StaticMemberFunctionFromBoundPointer = true;
10754     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10755       DeclAccessPair dap;
10756       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10757               OvlExpr, false, &dap)) {
10758         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10759           if (!Method->isStatic()) {
10760             // If the target type is a non-function type and the function found
10761             // is a non-static member function, pretend as if that was the
10762             // target, it's the only possible type to end up with.
10763             TargetTypeIsNonStaticMemberFunction = true;
10764 
10765             // And skip adding the function if its not in the proper form.
10766             // We'll diagnose this due to an empty set of functions.
10767             if (!OvlExprInfo.HasFormOfMemberPointer)
10768               return;
10769           }
10770 
10771         Matches.push_back(std::make_pair(dap, Fn));
10772       }
10773       return;
10774     }
10775 
10776     if (OvlExpr->hasExplicitTemplateArgs())
10777       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10778 
10779     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10780       // C++ [over.over]p4:
10781       //   If more than one function is selected, [...]
10782       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10783         if (FoundNonTemplateFunction)
10784           EliminateAllTemplateMatches();
10785         else
10786           EliminateAllExceptMostSpecializedTemplate();
10787       }
10788     }
10789 
10790     if (S.getLangOpts().CUDA && Matches.size() > 1)
10791       EliminateSuboptimalCudaMatches();
10792   }
10793 
10794   bool hasComplained() const { return HasComplained; }
10795 
10796 private:
10797   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10798     QualType Discard;
10799     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10800            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10801   }
10802 
10803   /// \return true if A is considered a better overload candidate for the
10804   /// desired type than B.
10805   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10806     // If A doesn't have exactly the correct type, we don't want to classify it
10807     // as "better" than anything else. This way, the user is required to
10808     // disambiguate for us if there are multiple candidates and no exact match.
10809     return candidateHasExactlyCorrectType(A) &&
10810            (!candidateHasExactlyCorrectType(B) ||
10811             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10812   }
10813 
10814   /// \return true if we were able to eliminate all but one overload candidate,
10815   /// false otherwise.
10816   bool eliminiateSuboptimalOverloadCandidates() {
10817     // Same algorithm as overload resolution -- one pass to pick the "best",
10818     // another pass to be sure that nothing is better than the best.
10819     auto Best = Matches.begin();
10820     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10821       if (isBetterCandidate(I->second, Best->second))
10822         Best = I;
10823 
10824     const FunctionDecl *BestFn = Best->second;
10825     auto IsBestOrInferiorToBest = [this, BestFn](
10826         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10827       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10828     };
10829 
10830     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10831     // option, so we can potentially give the user a better error
10832     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10833       return false;
10834     Matches[0] = *Best;
10835     Matches.resize(1);
10836     return true;
10837   }
10838 
10839   bool isTargetTypeAFunction() const {
10840     return TargetFunctionType->isFunctionType();
10841   }
10842 
10843   // [ToType]     [Return]
10844 
10845   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10846   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10847   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10848   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10849     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10850   }
10851 
10852   // return true if any matching specializations were found
10853   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10854                                    const DeclAccessPair& CurAccessFunPair) {
10855     if (CXXMethodDecl *Method
10856               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10857       // Skip non-static function templates when converting to pointer, and
10858       // static when converting to member pointer.
10859       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10860         return false;
10861     }
10862     else if (TargetTypeIsNonStaticMemberFunction)
10863       return false;
10864 
10865     // C++ [over.over]p2:
10866     //   If the name is a function template, template argument deduction is
10867     //   done (14.8.2.2), and if the argument deduction succeeds, the
10868     //   resulting template argument list is used to generate a single
10869     //   function template specialization, which is added to the set of
10870     //   overloaded functions considered.
10871     FunctionDecl *Specialization = nullptr;
10872     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10873     if (Sema::TemplateDeductionResult Result
10874           = S.DeduceTemplateArguments(FunctionTemplate,
10875                                       &OvlExplicitTemplateArgs,
10876                                       TargetFunctionType, Specialization,
10877                                       Info, /*IsAddressOfFunction*/true)) {
10878       // Make a note of the failed deduction for diagnostics.
10879       FailedCandidates.addCandidate()
10880           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10881                MakeDeductionFailureInfo(Context, Result, Info));
10882       return false;
10883     }
10884 
10885     // Template argument deduction ensures that we have an exact match or
10886     // compatible pointer-to-function arguments that would be adjusted by ICS.
10887     // This function template specicalization works.
10888     assert(S.isSameOrCompatibleFunctionType(
10889               Context.getCanonicalType(Specialization->getType()),
10890               Context.getCanonicalType(TargetFunctionType)));
10891 
10892     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10893       return false;
10894 
10895     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10896     return true;
10897   }
10898 
10899   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10900                                       const DeclAccessPair& CurAccessFunPair) {
10901     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10902       // Skip non-static functions when converting to pointer, and static
10903       // when converting to member pointer.
10904       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10905         return false;
10906     }
10907     else if (TargetTypeIsNonStaticMemberFunction)
10908       return false;
10909 
10910     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10911       if (S.getLangOpts().CUDA)
10912         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10913           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10914             return false;
10915 
10916       // If any candidate has a placeholder return type, trigger its deduction
10917       // now.
10918       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10919                                Complain)) {
10920         HasComplained |= Complain;
10921         return false;
10922       }
10923 
10924       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10925         return false;
10926 
10927       // If we're in C, we need to support types that aren't exactly identical.
10928       if (!S.getLangOpts().CPlusPlus ||
10929           candidateHasExactlyCorrectType(FunDecl)) {
10930         Matches.push_back(std::make_pair(
10931             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10932         FoundNonTemplateFunction = true;
10933         return true;
10934       }
10935     }
10936 
10937     return false;
10938   }
10939 
10940   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10941     bool Ret = false;
10942 
10943     // If the overload expression doesn't have the form of a pointer to
10944     // member, don't try to convert it to a pointer-to-member type.
10945     if (IsInvalidFormOfPointerToMemberFunction())
10946       return false;
10947 
10948     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10949                                E = OvlExpr->decls_end();
10950          I != E; ++I) {
10951       // Look through any using declarations to find the underlying function.
10952       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10953 
10954       // C++ [over.over]p3:
10955       //   Non-member functions and static member functions match
10956       //   targets of type "pointer-to-function" or "reference-to-function."
10957       //   Nonstatic member functions match targets of
10958       //   type "pointer-to-member-function."
10959       // Note that according to DR 247, the containing class does not matter.
10960       if (FunctionTemplateDecl *FunctionTemplate
10961                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10962         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10963           Ret = true;
10964       }
10965       // If we have explicit template arguments supplied, skip non-templates.
10966       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10967                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10968         Ret = true;
10969     }
10970     assert(Ret || Matches.empty());
10971     return Ret;
10972   }
10973 
10974   void EliminateAllExceptMostSpecializedTemplate() {
10975     //   [...] and any given function template specialization F1 is
10976     //   eliminated if the set contains a second function template
10977     //   specialization whose function template is more specialized
10978     //   than the function template of F1 according to the partial
10979     //   ordering rules of 14.5.5.2.
10980 
10981     // The algorithm specified above is quadratic. We instead use a
10982     // two-pass algorithm (similar to the one used to identify the
10983     // best viable function in an overload set) that identifies the
10984     // best function template (if it exists).
10985 
10986     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10987     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10988       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10989 
10990     // TODO: It looks like FailedCandidates does not serve much purpose
10991     // here, since the no_viable diagnostic has index 0.
10992     UnresolvedSetIterator Result = S.getMostSpecialized(
10993         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10994         SourceExpr->getLocStart(), S.PDiag(),
10995         S.PDiag(diag::err_addr_ovl_ambiguous)
10996           << Matches[0].second->getDeclName(),
10997         S.PDiag(diag::note_ovl_candidate)
10998           << (unsigned)oc_function_template,
10999         Complain, TargetFunctionType);
11000 
11001     if (Result != MatchesCopy.end()) {
11002       // Make it the first and only element
11003       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11004       Matches[0].second = cast<FunctionDecl>(*Result);
11005       Matches.resize(1);
11006     } else
11007       HasComplained |= Complain;
11008   }
11009 
11010   void EliminateAllTemplateMatches() {
11011     //   [...] any function template specializations in the set are
11012     //   eliminated if the set also contains a non-template function, [...]
11013     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11014       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11015         ++I;
11016       else {
11017         Matches[I] = Matches[--N];
11018         Matches.resize(N);
11019       }
11020     }
11021   }
11022 
11023   void EliminateSuboptimalCudaMatches() {
11024     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11025   }
11026 
11027 public:
11028   void ComplainNoMatchesFound() const {
11029     assert(Matches.empty());
11030     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11031         << OvlExpr->getName() << TargetFunctionType
11032         << OvlExpr->getSourceRange();
11033     if (FailedCandidates.empty())
11034       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11035                                   /*TakingAddress=*/true);
11036     else {
11037       // We have some deduction failure messages. Use them to diagnose
11038       // the function templates, and diagnose the non-template candidates
11039       // normally.
11040       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11041                                  IEnd = OvlExpr->decls_end();
11042            I != IEnd; ++I)
11043         if (FunctionDecl *Fun =
11044                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11045           if (!functionHasPassObjectSizeParams(Fun))
11046             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11047                                     /*TakingAddress=*/true);
11048       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11049     }
11050   }
11051 
11052   bool IsInvalidFormOfPointerToMemberFunction() const {
11053     return TargetTypeIsNonStaticMemberFunction &&
11054       !OvlExprInfo.HasFormOfMemberPointer;
11055   }
11056 
11057   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11058       // TODO: Should we condition this on whether any functions might
11059       // have matched, or is it more appropriate to do that in callers?
11060       // TODO: a fixit wouldn't hurt.
11061       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11062         << TargetType << OvlExpr->getSourceRange();
11063   }
11064 
11065   bool IsStaticMemberFunctionFromBoundPointer() const {
11066     return StaticMemberFunctionFromBoundPointer;
11067   }
11068 
11069   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11070     S.Diag(OvlExpr->getLocStart(),
11071            diag::err_invalid_form_pointer_member_function)
11072       << OvlExpr->getSourceRange();
11073   }
11074 
11075   void ComplainOfInvalidConversion() const {
11076     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11077       << OvlExpr->getName() << TargetType;
11078   }
11079 
11080   void ComplainMultipleMatchesFound() const {
11081     assert(Matches.size() > 1);
11082     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11083       << OvlExpr->getName()
11084       << OvlExpr->getSourceRange();
11085     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11086                                 /*TakingAddress=*/true);
11087   }
11088 
11089   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11090 
11091   int getNumMatches() const { return Matches.size(); }
11092 
11093   FunctionDecl* getMatchingFunctionDecl() const {
11094     if (Matches.size() != 1) return nullptr;
11095     return Matches[0].second;
11096   }
11097 
11098   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11099     if (Matches.size() != 1) return nullptr;
11100     return &Matches[0].first;
11101   }
11102 };
11103 }
11104 
11105 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11106 /// an overloaded function (C++ [over.over]), where @p From is an
11107 /// expression with overloaded function type and @p ToType is the type
11108 /// we're trying to resolve to. For example:
11109 ///
11110 /// @code
11111 /// int f(double);
11112 /// int f(int);
11113 ///
11114 /// int (*pfd)(double) = f; // selects f(double)
11115 /// @endcode
11116 ///
11117 /// This routine returns the resulting FunctionDecl if it could be
11118 /// resolved, and NULL otherwise. When @p Complain is true, this
11119 /// routine will emit diagnostics if there is an error.
11120 FunctionDecl *
11121 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11122                                          QualType TargetType,
11123                                          bool Complain,
11124                                          DeclAccessPair &FoundResult,
11125                                          bool *pHadMultipleCandidates) {
11126   assert(AddressOfExpr->getType() == Context.OverloadTy);
11127 
11128   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11129                                      Complain);
11130   int NumMatches = Resolver.getNumMatches();
11131   FunctionDecl *Fn = nullptr;
11132   bool ShouldComplain = Complain && !Resolver.hasComplained();
11133   if (NumMatches == 0 && ShouldComplain) {
11134     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11135       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11136     else
11137       Resolver.ComplainNoMatchesFound();
11138   }
11139   else if (NumMatches > 1 && ShouldComplain)
11140     Resolver.ComplainMultipleMatchesFound();
11141   else if (NumMatches == 1) {
11142     Fn = Resolver.getMatchingFunctionDecl();
11143     assert(Fn);
11144     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11145       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11146     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11147     if (Complain) {
11148       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11149         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11150       else
11151         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11152     }
11153   }
11154 
11155   if (pHadMultipleCandidates)
11156     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11157   return Fn;
11158 }
11159 
11160 /// \brief Given an expression that refers to an overloaded function, try to
11161 /// resolve that function to a single function that can have its address taken.
11162 /// This will modify `Pair` iff it returns non-null.
11163 ///
11164 /// This routine can only realistically succeed if all but one candidates in the
11165 /// overload set for SrcExpr cannot have their addresses taken.
11166 FunctionDecl *
11167 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11168                                                   DeclAccessPair &Pair) {
11169   OverloadExpr::FindResult R = OverloadExpr::find(E);
11170   OverloadExpr *Ovl = R.Expression;
11171   FunctionDecl *Result = nullptr;
11172   DeclAccessPair DAP;
11173   // Don't use the AddressOfResolver because we're specifically looking for
11174   // cases where we have one overload candidate that lacks
11175   // enable_if/pass_object_size/...
11176   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11177     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11178     if (!FD)
11179       return nullptr;
11180 
11181     if (!checkAddressOfFunctionIsAvailable(FD))
11182       continue;
11183 
11184     // We have more than one result; quit.
11185     if (Result)
11186       return nullptr;
11187     DAP = I.getPair();
11188     Result = FD;
11189   }
11190 
11191   if (Result)
11192     Pair = DAP;
11193   return Result;
11194 }
11195 
11196 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11197 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11198 /// will perform access checks, diagnose the use of the resultant decl, and, if
11199 /// necessary, perform a function-to-pointer decay.
11200 ///
11201 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11202 /// Otherwise, returns true. This may emit diagnostics and return true.
11203 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11204     ExprResult &SrcExpr) {
11205   Expr *E = SrcExpr.get();
11206   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11207 
11208   DeclAccessPair DAP;
11209   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11210   if (!Found)
11211     return false;
11212 
11213   // Emitting multiple diagnostics for a function that is both inaccessible and
11214   // unavailable is consistent with our behavior elsewhere. So, always check
11215   // for both.
11216   DiagnoseUseOfDecl(Found, E->getExprLoc());
11217   CheckAddressOfMemberAccess(E, DAP);
11218   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11219   if (Fixed->getType()->isFunctionType())
11220     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11221   else
11222     SrcExpr = Fixed;
11223   return true;
11224 }
11225 
11226 /// \brief Given an expression that refers to an overloaded function, try to
11227 /// resolve that overloaded function expression down to a single function.
11228 ///
11229 /// This routine can only resolve template-ids that refer to a single function
11230 /// template, where that template-id refers to a single template whose template
11231 /// arguments are either provided by the template-id or have defaults,
11232 /// as described in C++0x [temp.arg.explicit]p3.
11233 ///
11234 /// If no template-ids are found, no diagnostics are emitted and NULL is
11235 /// returned.
11236 FunctionDecl *
11237 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11238                                                   bool Complain,
11239                                                   DeclAccessPair *FoundResult) {
11240   // C++ [over.over]p1:
11241   //   [...] [Note: any redundant set of parentheses surrounding the
11242   //   overloaded function name is ignored (5.1). ]
11243   // C++ [over.over]p1:
11244   //   [...] The overloaded function name can be preceded by the &
11245   //   operator.
11246 
11247   // If we didn't actually find any template-ids, we're done.
11248   if (!ovl->hasExplicitTemplateArgs())
11249     return nullptr;
11250 
11251   TemplateArgumentListInfo ExplicitTemplateArgs;
11252   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11253   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11254 
11255   // Look through all of the overloaded functions, searching for one
11256   // whose type matches exactly.
11257   FunctionDecl *Matched = nullptr;
11258   for (UnresolvedSetIterator I = ovl->decls_begin(),
11259          E = ovl->decls_end(); I != E; ++I) {
11260     // C++0x [temp.arg.explicit]p3:
11261     //   [...] In contexts where deduction is done and fails, or in contexts
11262     //   where deduction is not done, if a template argument list is
11263     //   specified and it, along with any default template arguments,
11264     //   identifies a single function template specialization, then the
11265     //   template-id is an lvalue for the function template specialization.
11266     FunctionTemplateDecl *FunctionTemplate
11267       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11268 
11269     // C++ [over.over]p2:
11270     //   If the name is a function template, template argument deduction is
11271     //   done (14.8.2.2), and if the argument deduction succeeds, the
11272     //   resulting template argument list is used to generate a single
11273     //   function template specialization, which is added to the set of
11274     //   overloaded functions considered.
11275     FunctionDecl *Specialization = nullptr;
11276     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11277     if (TemplateDeductionResult Result
11278           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11279                                     Specialization, Info,
11280                                     /*IsAddressOfFunction*/true)) {
11281       // Make a note of the failed deduction for diagnostics.
11282       // TODO: Actually use the failed-deduction info?
11283       FailedCandidates.addCandidate()
11284           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11285                MakeDeductionFailureInfo(Context, Result, Info));
11286       continue;
11287     }
11288 
11289     assert(Specialization && "no specialization and no error?");
11290 
11291     // Multiple matches; we can't resolve to a single declaration.
11292     if (Matched) {
11293       if (Complain) {
11294         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11295           << ovl->getName();
11296         NoteAllOverloadCandidates(ovl);
11297       }
11298       return nullptr;
11299     }
11300 
11301     Matched = Specialization;
11302     if (FoundResult) *FoundResult = I.getPair();
11303   }
11304 
11305   if (Matched &&
11306       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11307     return nullptr;
11308 
11309   return Matched;
11310 }
11311 
11312 
11313 
11314 
11315 // Resolve and fix an overloaded expression that can be resolved
11316 // because it identifies a single function template specialization.
11317 //
11318 // Last three arguments should only be supplied if Complain = true
11319 //
11320 // Return true if it was logically possible to so resolve the
11321 // expression, regardless of whether or not it succeeded.  Always
11322 // returns true if 'complain' is set.
11323 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11324                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11325                       bool complain, SourceRange OpRangeForComplaining,
11326                                            QualType DestTypeForComplaining,
11327                                             unsigned DiagIDForComplaining) {
11328   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11329 
11330   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11331 
11332   DeclAccessPair found;
11333   ExprResult SingleFunctionExpression;
11334   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11335                            ovl.Expression, /*complain*/ false, &found)) {
11336     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11337       SrcExpr = ExprError();
11338       return true;
11339     }
11340 
11341     // It is only correct to resolve to an instance method if we're
11342     // resolving a form that's permitted to be a pointer to member.
11343     // Otherwise we'll end up making a bound member expression, which
11344     // is illegal in all the contexts we resolve like this.
11345     if (!ovl.HasFormOfMemberPointer &&
11346         isa<CXXMethodDecl>(fn) &&
11347         cast<CXXMethodDecl>(fn)->isInstance()) {
11348       if (!complain) return false;
11349 
11350       Diag(ovl.Expression->getExprLoc(),
11351            diag::err_bound_member_function)
11352         << 0 << ovl.Expression->getSourceRange();
11353 
11354       // TODO: I believe we only end up here if there's a mix of
11355       // static and non-static candidates (otherwise the expression
11356       // would have 'bound member' type, not 'overload' type).
11357       // Ideally we would note which candidate was chosen and why
11358       // the static candidates were rejected.
11359       SrcExpr = ExprError();
11360       return true;
11361     }
11362 
11363     // Fix the expression to refer to 'fn'.
11364     SingleFunctionExpression =
11365         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11366 
11367     // If desired, do function-to-pointer decay.
11368     if (doFunctionPointerConverion) {
11369       SingleFunctionExpression =
11370         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11371       if (SingleFunctionExpression.isInvalid()) {
11372         SrcExpr = ExprError();
11373         return true;
11374       }
11375     }
11376   }
11377 
11378   if (!SingleFunctionExpression.isUsable()) {
11379     if (complain) {
11380       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11381         << ovl.Expression->getName()
11382         << DestTypeForComplaining
11383         << OpRangeForComplaining
11384         << ovl.Expression->getQualifierLoc().getSourceRange();
11385       NoteAllOverloadCandidates(SrcExpr.get());
11386 
11387       SrcExpr = ExprError();
11388       return true;
11389     }
11390 
11391     return false;
11392   }
11393 
11394   SrcExpr = SingleFunctionExpression;
11395   return true;
11396 }
11397 
11398 /// \brief Add a single candidate to the overload set.
11399 static void AddOverloadedCallCandidate(Sema &S,
11400                                        DeclAccessPair FoundDecl,
11401                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11402                                        ArrayRef<Expr *> Args,
11403                                        OverloadCandidateSet &CandidateSet,
11404                                        bool PartialOverloading,
11405                                        bool KnownValid) {
11406   NamedDecl *Callee = FoundDecl.getDecl();
11407   if (isa<UsingShadowDecl>(Callee))
11408     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11409 
11410   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11411     if (ExplicitTemplateArgs) {
11412       assert(!KnownValid && "Explicit template arguments?");
11413       return;
11414     }
11415     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11416                            /*SuppressUsedConversions=*/false,
11417                            PartialOverloading);
11418     return;
11419   }
11420 
11421   if (FunctionTemplateDecl *FuncTemplate
11422       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11423     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11424                                    ExplicitTemplateArgs, Args, CandidateSet,
11425                                    /*SuppressUsedConversions=*/false,
11426                                    PartialOverloading);
11427     return;
11428   }
11429 
11430   assert(!KnownValid && "unhandled case in overloaded call candidate");
11431 }
11432 
11433 /// \brief Add the overload candidates named by callee and/or found by argument
11434 /// dependent lookup to the given overload set.
11435 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11436                                        ArrayRef<Expr *> Args,
11437                                        OverloadCandidateSet &CandidateSet,
11438                                        bool PartialOverloading) {
11439 
11440 #ifndef NDEBUG
11441   // Verify that ArgumentDependentLookup is consistent with the rules
11442   // in C++0x [basic.lookup.argdep]p3:
11443   //
11444   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11445   //   and let Y be the lookup set produced by argument dependent
11446   //   lookup (defined as follows). If X contains
11447   //
11448   //     -- a declaration of a class member, or
11449   //
11450   //     -- a block-scope function declaration that is not a
11451   //        using-declaration, or
11452   //
11453   //     -- a declaration that is neither a function or a function
11454   //        template
11455   //
11456   //   then Y is empty.
11457 
11458   if (ULE->requiresADL()) {
11459     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11460            E = ULE->decls_end(); I != E; ++I) {
11461       assert(!(*I)->getDeclContext()->isRecord());
11462       assert(isa<UsingShadowDecl>(*I) ||
11463              !(*I)->getDeclContext()->isFunctionOrMethod());
11464       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11465     }
11466   }
11467 #endif
11468 
11469   // It would be nice to avoid this copy.
11470   TemplateArgumentListInfo TABuffer;
11471   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11472   if (ULE->hasExplicitTemplateArgs()) {
11473     ULE->copyTemplateArgumentsInto(TABuffer);
11474     ExplicitTemplateArgs = &TABuffer;
11475   }
11476 
11477   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11478          E = ULE->decls_end(); I != E; ++I)
11479     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11480                                CandidateSet, PartialOverloading,
11481                                /*KnownValid*/ true);
11482 
11483   if (ULE->requiresADL())
11484     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11485                                          Args, ExplicitTemplateArgs,
11486                                          CandidateSet, PartialOverloading);
11487 }
11488 
11489 /// Determine whether a declaration with the specified name could be moved into
11490 /// a different namespace.
11491 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11492   switch (Name.getCXXOverloadedOperator()) {
11493   case OO_New: case OO_Array_New:
11494   case OO_Delete: case OO_Array_Delete:
11495     return false;
11496 
11497   default:
11498     return true;
11499   }
11500 }
11501 
11502 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11503 /// template, where the non-dependent name was declared after the template
11504 /// was defined. This is common in code written for a compilers which do not
11505 /// correctly implement two-stage name lookup.
11506 ///
11507 /// Returns true if a viable candidate was found and a diagnostic was issued.
11508 static bool
11509 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11510                        const CXXScopeSpec &SS, LookupResult &R,
11511                        OverloadCandidateSet::CandidateSetKind CSK,
11512                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11513                        ArrayRef<Expr *> Args,
11514                        bool *DoDiagnoseEmptyLookup = nullptr) {
11515   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11516     return false;
11517 
11518   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11519     if (DC->isTransparentContext())
11520       continue;
11521 
11522     SemaRef.LookupQualifiedName(R, DC);
11523 
11524     if (!R.empty()) {
11525       R.suppressDiagnostics();
11526 
11527       if (isa<CXXRecordDecl>(DC)) {
11528         // Don't diagnose names we find in classes; we get much better
11529         // diagnostics for these from DiagnoseEmptyLookup.
11530         R.clear();
11531         if (DoDiagnoseEmptyLookup)
11532           *DoDiagnoseEmptyLookup = true;
11533         return false;
11534       }
11535 
11536       OverloadCandidateSet Candidates(FnLoc, CSK);
11537       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11538         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11539                                    ExplicitTemplateArgs, Args,
11540                                    Candidates, false, /*KnownValid*/ false);
11541 
11542       OverloadCandidateSet::iterator Best;
11543       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11544         // No viable functions. Don't bother the user with notes for functions
11545         // which don't work and shouldn't be found anyway.
11546         R.clear();
11547         return false;
11548       }
11549 
11550       // Find the namespaces where ADL would have looked, and suggest
11551       // declaring the function there instead.
11552       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11553       Sema::AssociatedClassSet AssociatedClasses;
11554       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11555                                                  AssociatedNamespaces,
11556                                                  AssociatedClasses);
11557       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11558       if (canBeDeclaredInNamespace(R.getLookupName())) {
11559         DeclContext *Std = SemaRef.getStdNamespace();
11560         for (Sema::AssociatedNamespaceSet::iterator
11561                it = AssociatedNamespaces.begin(),
11562                end = AssociatedNamespaces.end(); it != end; ++it) {
11563           // Never suggest declaring a function within namespace 'std'.
11564           if (Std && Std->Encloses(*it))
11565             continue;
11566 
11567           // Never suggest declaring a function within a namespace with a
11568           // reserved name, like __gnu_cxx.
11569           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11570           if (NS &&
11571               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11572             continue;
11573 
11574           SuggestedNamespaces.insert(*it);
11575         }
11576       }
11577 
11578       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11579         << R.getLookupName();
11580       if (SuggestedNamespaces.empty()) {
11581         SemaRef.Diag(Best->Function->getLocation(),
11582                      diag::note_not_found_by_two_phase_lookup)
11583           << R.getLookupName() << 0;
11584       } else if (SuggestedNamespaces.size() == 1) {
11585         SemaRef.Diag(Best->Function->getLocation(),
11586                      diag::note_not_found_by_two_phase_lookup)
11587           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11588       } else {
11589         // FIXME: It would be useful to list the associated namespaces here,
11590         // but the diagnostics infrastructure doesn't provide a way to produce
11591         // a localized representation of a list of items.
11592         SemaRef.Diag(Best->Function->getLocation(),
11593                      diag::note_not_found_by_two_phase_lookup)
11594           << R.getLookupName() << 2;
11595       }
11596 
11597       // Try to recover by calling this function.
11598       return true;
11599     }
11600 
11601     R.clear();
11602   }
11603 
11604   return false;
11605 }
11606 
11607 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11608 /// template, where the non-dependent operator was declared after the template
11609 /// was defined.
11610 ///
11611 /// Returns true if a viable candidate was found and a diagnostic was issued.
11612 static bool
11613 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11614                                SourceLocation OpLoc,
11615                                ArrayRef<Expr *> Args) {
11616   DeclarationName OpName =
11617     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11618   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11619   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11620                                 OverloadCandidateSet::CSK_Operator,
11621                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11622 }
11623 
11624 namespace {
11625 class BuildRecoveryCallExprRAII {
11626   Sema &SemaRef;
11627 public:
11628   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11629     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11630     SemaRef.IsBuildingRecoveryCallExpr = true;
11631   }
11632 
11633   ~BuildRecoveryCallExprRAII() {
11634     SemaRef.IsBuildingRecoveryCallExpr = false;
11635   }
11636 };
11637 
11638 }
11639 
11640 static std::unique_ptr<CorrectionCandidateCallback>
11641 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11642               bool HasTemplateArgs, bool AllowTypoCorrection) {
11643   if (!AllowTypoCorrection)
11644     return llvm::make_unique<NoTypoCorrectionCCC>();
11645   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11646                                                   HasTemplateArgs, ME);
11647 }
11648 
11649 /// Attempts to recover from a call where no functions were found.
11650 ///
11651 /// Returns true if new candidates were found.
11652 static ExprResult
11653 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11654                       UnresolvedLookupExpr *ULE,
11655                       SourceLocation LParenLoc,
11656                       MutableArrayRef<Expr *> Args,
11657                       SourceLocation RParenLoc,
11658                       bool EmptyLookup, bool AllowTypoCorrection) {
11659   // Do not try to recover if it is already building a recovery call.
11660   // This stops infinite loops for template instantiations like
11661   //
11662   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11663   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11664   //
11665   if (SemaRef.IsBuildingRecoveryCallExpr)
11666     return ExprError();
11667   BuildRecoveryCallExprRAII RCE(SemaRef);
11668 
11669   CXXScopeSpec SS;
11670   SS.Adopt(ULE->getQualifierLoc());
11671   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11672 
11673   TemplateArgumentListInfo TABuffer;
11674   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11675   if (ULE->hasExplicitTemplateArgs()) {
11676     ULE->copyTemplateArgumentsInto(TABuffer);
11677     ExplicitTemplateArgs = &TABuffer;
11678   }
11679 
11680   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11681                  Sema::LookupOrdinaryName);
11682   bool DoDiagnoseEmptyLookup = EmptyLookup;
11683   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11684                               OverloadCandidateSet::CSK_Normal,
11685                               ExplicitTemplateArgs, Args,
11686                               &DoDiagnoseEmptyLookup) &&
11687     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11688         S, SS, R,
11689         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11690                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11691         ExplicitTemplateArgs, Args)))
11692     return ExprError();
11693 
11694   assert(!R.empty() && "lookup results empty despite recovery");
11695 
11696   // If recovery created an ambiguity, just bail out.
11697   if (R.isAmbiguous()) {
11698     R.suppressDiagnostics();
11699     return ExprError();
11700   }
11701 
11702   // Build an implicit member call if appropriate.  Just drop the
11703   // casts and such from the call, we don't really care.
11704   ExprResult NewFn = ExprError();
11705   if ((*R.begin())->isCXXClassMember())
11706     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11707                                                     ExplicitTemplateArgs, S);
11708   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11709     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11710                                         ExplicitTemplateArgs);
11711   else
11712     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11713 
11714   if (NewFn.isInvalid())
11715     return ExprError();
11716 
11717   // This shouldn't cause an infinite loop because we're giving it
11718   // an expression with viable lookup results, which should never
11719   // end up here.
11720   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11721                                MultiExprArg(Args.data(), Args.size()),
11722                                RParenLoc);
11723 }
11724 
11725 /// \brief Constructs and populates an OverloadedCandidateSet from
11726 /// the given function.
11727 /// \returns true when an the ExprResult output parameter has been set.
11728 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11729                                   UnresolvedLookupExpr *ULE,
11730                                   MultiExprArg Args,
11731                                   SourceLocation RParenLoc,
11732                                   OverloadCandidateSet *CandidateSet,
11733                                   ExprResult *Result) {
11734 #ifndef NDEBUG
11735   if (ULE->requiresADL()) {
11736     // To do ADL, we must have found an unqualified name.
11737     assert(!ULE->getQualifier() && "qualified name with ADL");
11738 
11739     // We don't perform ADL for implicit declarations of builtins.
11740     // Verify that this was correctly set up.
11741     FunctionDecl *F;
11742     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11743         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11744         F->getBuiltinID() && F->isImplicit())
11745       llvm_unreachable("performing ADL for builtin");
11746 
11747     // We don't perform ADL in C.
11748     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11749   }
11750 #endif
11751 
11752   UnbridgedCastsSet UnbridgedCasts;
11753   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11754     *Result = ExprError();
11755     return true;
11756   }
11757 
11758   // Add the functions denoted by the callee to the set of candidate
11759   // functions, including those from argument-dependent lookup.
11760   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11761 
11762   if (getLangOpts().MSVCCompat &&
11763       CurContext->isDependentContext() && !isSFINAEContext() &&
11764       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11765 
11766     OverloadCandidateSet::iterator Best;
11767     if (CandidateSet->empty() ||
11768         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11769             OR_No_Viable_Function) {
11770       // In Microsoft mode, if we are inside a template class member function then
11771       // create a type dependent CallExpr. The goal is to postpone name lookup
11772       // to instantiation time to be able to search into type dependent base
11773       // classes.
11774       CallExpr *CE = new (Context) CallExpr(
11775           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11776       CE->setTypeDependent(true);
11777       CE->setValueDependent(true);
11778       CE->setInstantiationDependent(true);
11779       *Result = CE;
11780       return true;
11781     }
11782   }
11783 
11784   if (CandidateSet->empty())
11785     return false;
11786 
11787   UnbridgedCasts.restore();
11788   return false;
11789 }
11790 
11791 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11792 /// the completed call expression. If overload resolution fails, emits
11793 /// diagnostics and returns ExprError()
11794 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11795                                            UnresolvedLookupExpr *ULE,
11796                                            SourceLocation LParenLoc,
11797                                            MultiExprArg Args,
11798                                            SourceLocation RParenLoc,
11799                                            Expr *ExecConfig,
11800                                            OverloadCandidateSet *CandidateSet,
11801                                            OverloadCandidateSet::iterator *Best,
11802                                            OverloadingResult OverloadResult,
11803                                            bool AllowTypoCorrection) {
11804   if (CandidateSet->empty())
11805     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11806                                  RParenLoc, /*EmptyLookup=*/true,
11807                                  AllowTypoCorrection);
11808 
11809   switch (OverloadResult) {
11810   case OR_Success: {
11811     FunctionDecl *FDecl = (*Best)->Function;
11812     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11813     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11814       return ExprError();
11815     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11816     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11817                                          ExecConfig);
11818   }
11819 
11820   case OR_No_Viable_Function: {
11821     // Try to recover by looking for viable functions which the user might
11822     // have meant to call.
11823     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11824                                                 Args, RParenLoc,
11825                                                 /*EmptyLookup=*/false,
11826                                                 AllowTypoCorrection);
11827     if (!Recovery.isInvalid())
11828       return Recovery;
11829 
11830     // If the user passes in a function that we can't take the address of, we
11831     // generally end up emitting really bad error messages. Here, we attempt to
11832     // emit better ones.
11833     for (const Expr *Arg : Args) {
11834       if (!Arg->getType()->isFunctionType())
11835         continue;
11836       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11837         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11838         if (FD &&
11839             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11840                                                        Arg->getExprLoc()))
11841           return ExprError();
11842       }
11843     }
11844 
11845     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11846         << ULE->getName() << Fn->getSourceRange();
11847     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11848     break;
11849   }
11850 
11851   case OR_Ambiguous:
11852     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11853       << ULE->getName() << Fn->getSourceRange();
11854     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11855     break;
11856 
11857   case OR_Deleted: {
11858     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11859       << (*Best)->Function->isDeleted()
11860       << ULE->getName()
11861       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11862       << Fn->getSourceRange();
11863     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11864 
11865     // We emitted an error for the unvailable/deleted function call but keep
11866     // the call in the AST.
11867     FunctionDecl *FDecl = (*Best)->Function;
11868     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11869     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11870                                          ExecConfig);
11871   }
11872   }
11873 
11874   // Overload resolution failed.
11875   return ExprError();
11876 }
11877 
11878 static void markUnaddressableCandidatesUnviable(Sema &S,
11879                                                 OverloadCandidateSet &CS) {
11880   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11881     if (I->Viable &&
11882         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11883       I->Viable = false;
11884       I->FailureKind = ovl_fail_addr_not_available;
11885     }
11886   }
11887 }
11888 
11889 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11890 /// (which eventually refers to the declaration Func) and the call
11891 /// arguments Args/NumArgs, attempt to resolve the function call down
11892 /// to a specific function. If overload resolution succeeds, returns
11893 /// the call expression produced by overload resolution.
11894 /// Otherwise, emits diagnostics and returns ExprError.
11895 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11896                                          UnresolvedLookupExpr *ULE,
11897                                          SourceLocation LParenLoc,
11898                                          MultiExprArg Args,
11899                                          SourceLocation RParenLoc,
11900                                          Expr *ExecConfig,
11901                                          bool AllowTypoCorrection,
11902                                          bool CalleesAddressIsTaken) {
11903   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11904                                     OverloadCandidateSet::CSK_Normal);
11905   ExprResult result;
11906 
11907   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11908                              &result))
11909     return result;
11910 
11911   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11912   // functions that aren't addressible are considered unviable.
11913   if (CalleesAddressIsTaken)
11914     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11915 
11916   OverloadCandidateSet::iterator Best;
11917   OverloadingResult OverloadResult =
11918       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11919 
11920   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11921                                   RParenLoc, ExecConfig, &CandidateSet,
11922                                   &Best, OverloadResult,
11923                                   AllowTypoCorrection);
11924 }
11925 
11926 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11927   return Functions.size() > 1 ||
11928     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11929 }
11930 
11931 /// \brief Create a unary operation that may resolve to an overloaded
11932 /// operator.
11933 ///
11934 /// \param OpLoc The location of the operator itself (e.g., '*').
11935 ///
11936 /// \param Opc The UnaryOperatorKind that describes this operator.
11937 ///
11938 /// \param Fns The set of non-member functions that will be
11939 /// considered by overload resolution. The caller needs to build this
11940 /// set based on the context using, e.g.,
11941 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11942 /// set should not contain any member functions; those will be added
11943 /// by CreateOverloadedUnaryOp().
11944 ///
11945 /// \param Input The input argument.
11946 ExprResult
11947 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11948                               const UnresolvedSetImpl &Fns,
11949                               Expr *Input) {
11950   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11951   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11952   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11953   // TODO: provide better source location info.
11954   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11955 
11956   if (checkPlaceholderForOverload(*this, Input))
11957     return ExprError();
11958 
11959   Expr *Args[2] = { Input, nullptr };
11960   unsigned NumArgs = 1;
11961 
11962   // For post-increment and post-decrement, add the implicit '0' as
11963   // the second argument, so that we know this is a post-increment or
11964   // post-decrement.
11965   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11966     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11967     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11968                                      SourceLocation());
11969     NumArgs = 2;
11970   }
11971 
11972   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11973 
11974   if (Input->isTypeDependent()) {
11975     if (Fns.empty())
11976       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11977                                          VK_RValue, OK_Ordinary, OpLoc);
11978 
11979     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11980     UnresolvedLookupExpr *Fn
11981       = UnresolvedLookupExpr::Create(Context, NamingClass,
11982                                      NestedNameSpecifierLoc(), OpNameInfo,
11983                                      /*ADL*/ true, IsOverloaded(Fns),
11984                                      Fns.begin(), Fns.end());
11985     return new (Context)
11986         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11987                             VK_RValue, OpLoc, FPOptions());
11988   }
11989 
11990   // Build an empty overload set.
11991   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11992 
11993   // Add the candidates from the given function set.
11994   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11995 
11996   // Add operator candidates that are member functions.
11997   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11998 
11999   // Add candidates from ADL.
12000   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12001                                        /*ExplicitTemplateArgs*/nullptr,
12002                                        CandidateSet);
12003 
12004   // Add builtin operator candidates.
12005   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12006 
12007   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12008 
12009   // Perform overload resolution.
12010   OverloadCandidateSet::iterator Best;
12011   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12012   case OR_Success: {
12013     // We found a built-in operator or an overloaded operator.
12014     FunctionDecl *FnDecl = Best->Function;
12015 
12016     if (FnDecl) {
12017       // We matched an overloaded operator. Build a call to that
12018       // operator.
12019 
12020       // Convert the arguments.
12021       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12022         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12023 
12024         ExprResult InputRes =
12025           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12026                                               Best->FoundDecl, Method);
12027         if (InputRes.isInvalid())
12028           return ExprError();
12029         Input = InputRes.get();
12030       } else {
12031         // Convert the arguments.
12032         ExprResult InputInit
12033           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12034                                                       Context,
12035                                                       FnDecl->getParamDecl(0)),
12036                                       SourceLocation(),
12037                                       Input);
12038         if (InputInit.isInvalid())
12039           return ExprError();
12040         Input = InputInit.get();
12041       }
12042 
12043       // Build the actual expression node.
12044       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12045                                                 HadMultipleCandidates, OpLoc);
12046       if (FnExpr.isInvalid())
12047         return ExprError();
12048 
12049       // Determine the result type.
12050       QualType ResultTy = FnDecl->getReturnType();
12051       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12052       ResultTy = ResultTy.getNonLValueExprType(Context);
12053 
12054       Args[0] = Input;
12055       CallExpr *TheCall =
12056         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12057                                           ResultTy, VK, OpLoc, FPOptions());
12058 
12059       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12060         return ExprError();
12061 
12062       if (CheckFunctionCall(FnDecl, TheCall,
12063                             FnDecl->getType()->castAs<FunctionProtoType>()))
12064         return ExprError();
12065 
12066       return MaybeBindToTemporary(TheCall);
12067     } else {
12068       // We matched a built-in operator. Convert the arguments, then
12069       // break out so that we will build the appropriate built-in
12070       // operator node.
12071       ExprResult InputRes =
12072         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
12073                                   Best->Conversions[0], AA_Passing);
12074       if (InputRes.isInvalid())
12075         return ExprError();
12076       Input = InputRes.get();
12077       break;
12078     }
12079   }
12080 
12081   case OR_No_Viable_Function:
12082     // This is an erroneous use of an operator which can be overloaded by
12083     // a non-member function. Check for non-member operators which were
12084     // defined too late to be candidates.
12085     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12086       // FIXME: Recover by calling the found function.
12087       return ExprError();
12088 
12089     // No viable function; fall through to handling this as a
12090     // built-in operator, which will produce an error message for us.
12091     break;
12092 
12093   case OR_Ambiguous:
12094     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12095         << UnaryOperator::getOpcodeStr(Opc)
12096         << Input->getType()
12097         << Input->getSourceRange();
12098     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12099                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12100     return ExprError();
12101 
12102   case OR_Deleted:
12103     Diag(OpLoc, diag::err_ovl_deleted_oper)
12104       << Best->Function->isDeleted()
12105       << UnaryOperator::getOpcodeStr(Opc)
12106       << getDeletedOrUnavailableSuffix(Best->Function)
12107       << Input->getSourceRange();
12108     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12109                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12110     return ExprError();
12111   }
12112 
12113   // Either we found no viable overloaded operator or we matched a
12114   // built-in operator. In either case, fall through to trying to
12115   // build a built-in operation.
12116   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12117 }
12118 
12119 /// \brief Create a binary operation that may resolve to an overloaded
12120 /// operator.
12121 ///
12122 /// \param OpLoc The location of the operator itself (e.g., '+').
12123 ///
12124 /// \param Opc The BinaryOperatorKind that describes this operator.
12125 ///
12126 /// \param Fns The set of non-member functions that will be
12127 /// considered by overload resolution. The caller needs to build this
12128 /// set based on the context using, e.g.,
12129 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12130 /// set should not contain any member functions; those will be added
12131 /// by CreateOverloadedBinOp().
12132 ///
12133 /// \param LHS Left-hand argument.
12134 /// \param RHS Right-hand argument.
12135 ExprResult
12136 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12137                             BinaryOperatorKind Opc,
12138                             const UnresolvedSetImpl &Fns,
12139                             Expr *LHS, Expr *RHS) {
12140   Expr *Args[2] = { LHS, RHS };
12141   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12142 
12143   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12144   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12145 
12146   // If either side is type-dependent, create an appropriate dependent
12147   // expression.
12148   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12149     if (Fns.empty()) {
12150       // If there are no functions to store, just build a dependent
12151       // BinaryOperator or CompoundAssignment.
12152       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12153         return new (Context) BinaryOperator(
12154             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12155             OpLoc, FPFeatures);
12156 
12157       return new (Context) CompoundAssignOperator(
12158           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12159           Context.DependentTy, Context.DependentTy, OpLoc,
12160           FPFeatures);
12161     }
12162 
12163     // FIXME: save results of ADL from here?
12164     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12165     // TODO: provide better source location info in DNLoc component.
12166     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12167     UnresolvedLookupExpr *Fn
12168       = UnresolvedLookupExpr::Create(Context, NamingClass,
12169                                      NestedNameSpecifierLoc(), OpNameInfo,
12170                                      /*ADL*/ true, IsOverloaded(Fns),
12171                                      Fns.begin(), Fns.end());
12172     return new (Context)
12173         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12174                             VK_RValue, OpLoc, FPFeatures);
12175   }
12176 
12177   // Always do placeholder-like conversions on the RHS.
12178   if (checkPlaceholderForOverload(*this, Args[1]))
12179     return ExprError();
12180 
12181   // Do placeholder-like conversion on the LHS; note that we should
12182   // not get here with a PseudoObject LHS.
12183   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12184   if (checkPlaceholderForOverload(*this, Args[0]))
12185     return ExprError();
12186 
12187   // If this is the assignment operator, we only perform overload resolution
12188   // if the left-hand side is a class or enumeration type. This is actually
12189   // a hack. The standard requires that we do overload resolution between the
12190   // various built-in candidates, but as DR507 points out, this can lead to
12191   // problems. So we do it this way, which pretty much follows what GCC does.
12192   // Note that we go the traditional code path for compound assignment forms.
12193   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12194     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12195 
12196   // If this is the .* operator, which is not overloadable, just
12197   // create a built-in binary operator.
12198   if (Opc == BO_PtrMemD)
12199     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12200 
12201   // Build an empty overload set.
12202   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12203 
12204   // Add the candidates from the given function set.
12205   AddFunctionCandidates(Fns, Args, CandidateSet);
12206 
12207   // Add operator candidates that are member functions.
12208   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12209 
12210   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12211   // performed for an assignment operator (nor for operator[] nor operator->,
12212   // which don't get here).
12213   if (Opc != BO_Assign)
12214     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12215                                          /*ExplicitTemplateArgs*/ nullptr,
12216                                          CandidateSet);
12217 
12218   // Add builtin operator candidates.
12219   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12220 
12221   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12222 
12223   // Perform overload resolution.
12224   OverloadCandidateSet::iterator Best;
12225   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12226     case OR_Success: {
12227       // We found a built-in operator or an overloaded operator.
12228       FunctionDecl *FnDecl = Best->Function;
12229 
12230       if (FnDecl) {
12231         // We matched an overloaded operator. Build a call to that
12232         // operator.
12233 
12234         // Convert the arguments.
12235         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12236           // Best->Access is only meaningful for class members.
12237           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12238 
12239           ExprResult Arg1 =
12240             PerformCopyInitialization(
12241               InitializedEntity::InitializeParameter(Context,
12242                                                      FnDecl->getParamDecl(0)),
12243               SourceLocation(), Args[1]);
12244           if (Arg1.isInvalid())
12245             return ExprError();
12246 
12247           ExprResult Arg0 =
12248             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12249                                                 Best->FoundDecl, Method);
12250           if (Arg0.isInvalid())
12251             return ExprError();
12252           Args[0] = Arg0.getAs<Expr>();
12253           Args[1] = RHS = Arg1.getAs<Expr>();
12254         } else {
12255           // Convert the arguments.
12256           ExprResult Arg0 = PerformCopyInitialization(
12257             InitializedEntity::InitializeParameter(Context,
12258                                                    FnDecl->getParamDecl(0)),
12259             SourceLocation(), Args[0]);
12260           if (Arg0.isInvalid())
12261             return ExprError();
12262 
12263           ExprResult Arg1 =
12264             PerformCopyInitialization(
12265               InitializedEntity::InitializeParameter(Context,
12266                                                      FnDecl->getParamDecl(1)),
12267               SourceLocation(), Args[1]);
12268           if (Arg1.isInvalid())
12269             return ExprError();
12270           Args[0] = LHS = Arg0.getAs<Expr>();
12271           Args[1] = RHS = Arg1.getAs<Expr>();
12272         }
12273 
12274         // Build the actual expression node.
12275         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12276                                                   Best->FoundDecl,
12277                                                   HadMultipleCandidates, OpLoc);
12278         if (FnExpr.isInvalid())
12279           return ExprError();
12280 
12281         // Determine the result type.
12282         QualType ResultTy = FnDecl->getReturnType();
12283         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12284         ResultTy = ResultTy.getNonLValueExprType(Context);
12285 
12286         CXXOperatorCallExpr *TheCall =
12287           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12288                                             Args, ResultTy, VK, OpLoc,
12289                                             FPFeatures);
12290 
12291         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12292                                 FnDecl))
12293           return ExprError();
12294 
12295         ArrayRef<const Expr *> ArgsArray(Args, 2);
12296         const Expr *ImplicitThis = nullptr;
12297         // Cut off the implicit 'this'.
12298         if (isa<CXXMethodDecl>(FnDecl)) {
12299           ImplicitThis = ArgsArray[0];
12300           ArgsArray = ArgsArray.slice(1);
12301         }
12302 
12303         // Check for a self move.
12304         if (Op == OO_Equal)
12305           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12306 
12307         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12308                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12309                   VariadicDoesNotApply);
12310 
12311         return MaybeBindToTemporary(TheCall);
12312       } else {
12313         // We matched a built-in operator. Convert the arguments, then
12314         // break out so that we will build the appropriate built-in
12315         // operator node.
12316         ExprResult ArgsRes0 =
12317           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12318                                     Best->Conversions[0], AA_Passing);
12319         if (ArgsRes0.isInvalid())
12320           return ExprError();
12321         Args[0] = ArgsRes0.get();
12322 
12323         ExprResult ArgsRes1 =
12324           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12325                                     Best->Conversions[1], AA_Passing);
12326         if (ArgsRes1.isInvalid())
12327           return ExprError();
12328         Args[1] = ArgsRes1.get();
12329         break;
12330       }
12331     }
12332 
12333     case OR_No_Viable_Function: {
12334       // C++ [over.match.oper]p9:
12335       //   If the operator is the operator , [...] and there are no
12336       //   viable functions, then the operator is assumed to be the
12337       //   built-in operator and interpreted according to clause 5.
12338       if (Opc == BO_Comma)
12339         break;
12340 
12341       // For class as left operand for assignment or compound assigment
12342       // operator do not fall through to handling in built-in, but report that
12343       // no overloaded assignment operator found
12344       ExprResult Result = ExprError();
12345       if (Args[0]->getType()->isRecordType() &&
12346           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12347         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12348              << BinaryOperator::getOpcodeStr(Opc)
12349              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12350         if (Args[0]->getType()->isIncompleteType()) {
12351           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12352             << Args[0]->getType()
12353             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12354         }
12355       } else {
12356         // This is an erroneous use of an operator which can be overloaded by
12357         // a non-member function. Check for non-member operators which were
12358         // defined too late to be candidates.
12359         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12360           // FIXME: Recover by calling the found function.
12361           return ExprError();
12362 
12363         // No viable function; try to create a built-in operation, which will
12364         // produce an error. Then, show the non-viable candidates.
12365         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12366       }
12367       assert(Result.isInvalid() &&
12368              "C++ binary operator overloading is missing candidates!");
12369       if (Result.isInvalid())
12370         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12371                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12372       return Result;
12373     }
12374 
12375     case OR_Ambiguous:
12376       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12377           << BinaryOperator::getOpcodeStr(Opc)
12378           << Args[0]->getType() << Args[1]->getType()
12379           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12380       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12381                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12382       return ExprError();
12383 
12384     case OR_Deleted:
12385       if (isImplicitlyDeleted(Best->Function)) {
12386         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12387         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12388           << Context.getRecordType(Method->getParent())
12389           << getSpecialMember(Method);
12390 
12391         // The user probably meant to call this special member. Just
12392         // explain why it's deleted.
12393         NoteDeletedFunction(Method);
12394         return ExprError();
12395       } else {
12396         Diag(OpLoc, diag::err_ovl_deleted_oper)
12397           << Best->Function->isDeleted()
12398           << BinaryOperator::getOpcodeStr(Opc)
12399           << getDeletedOrUnavailableSuffix(Best->Function)
12400           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12401       }
12402       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12403                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12404       return ExprError();
12405   }
12406 
12407   // We matched a built-in operator; build it.
12408   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12409 }
12410 
12411 ExprResult
12412 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12413                                          SourceLocation RLoc,
12414                                          Expr *Base, Expr *Idx) {
12415   Expr *Args[2] = { Base, Idx };
12416   DeclarationName OpName =
12417       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12418 
12419   // If either side is type-dependent, create an appropriate dependent
12420   // expression.
12421   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12422 
12423     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12424     // CHECKME: no 'operator' keyword?
12425     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12426     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12427     UnresolvedLookupExpr *Fn
12428       = UnresolvedLookupExpr::Create(Context, NamingClass,
12429                                      NestedNameSpecifierLoc(), OpNameInfo,
12430                                      /*ADL*/ true, /*Overloaded*/ false,
12431                                      UnresolvedSetIterator(),
12432                                      UnresolvedSetIterator());
12433     // Can't add any actual overloads yet
12434 
12435     return new (Context)
12436         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12437                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12438   }
12439 
12440   // Handle placeholders on both operands.
12441   if (checkPlaceholderForOverload(*this, Args[0]))
12442     return ExprError();
12443   if (checkPlaceholderForOverload(*this, Args[1]))
12444     return ExprError();
12445 
12446   // Build an empty overload set.
12447   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12448 
12449   // Subscript can only be overloaded as a member function.
12450 
12451   // Add operator candidates that are member functions.
12452   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12453 
12454   // Add builtin operator candidates.
12455   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12456 
12457   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12458 
12459   // Perform overload resolution.
12460   OverloadCandidateSet::iterator Best;
12461   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12462     case OR_Success: {
12463       // We found a built-in operator or an overloaded operator.
12464       FunctionDecl *FnDecl = Best->Function;
12465 
12466       if (FnDecl) {
12467         // We matched an overloaded operator. Build a call to that
12468         // operator.
12469 
12470         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12471 
12472         // Convert the arguments.
12473         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12474         ExprResult Arg0 =
12475           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12476                                               Best->FoundDecl, Method);
12477         if (Arg0.isInvalid())
12478           return ExprError();
12479         Args[0] = Arg0.get();
12480 
12481         // Convert the arguments.
12482         ExprResult InputInit
12483           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12484                                                       Context,
12485                                                       FnDecl->getParamDecl(0)),
12486                                       SourceLocation(),
12487                                       Args[1]);
12488         if (InputInit.isInvalid())
12489           return ExprError();
12490 
12491         Args[1] = InputInit.getAs<Expr>();
12492 
12493         // Build the actual expression node.
12494         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12495         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12496         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12497                                                   Best->FoundDecl,
12498                                                   HadMultipleCandidates,
12499                                                   OpLocInfo.getLoc(),
12500                                                   OpLocInfo.getInfo());
12501         if (FnExpr.isInvalid())
12502           return ExprError();
12503 
12504         // Determine the result type
12505         QualType ResultTy = FnDecl->getReturnType();
12506         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12507         ResultTy = ResultTy.getNonLValueExprType(Context);
12508 
12509         CXXOperatorCallExpr *TheCall =
12510           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12511                                             FnExpr.get(), Args,
12512                                             ResultTy, VK, RLoc,
12513                                             FPOptions());
12514 
12515         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12516           return ExprError();
12517 
12518         if (CheckFunctionCall(Method, TheCall,
12519                               Method->getType()->castAs<FunctionProtoType>()))
12520           return ExprError();
12521 
12522         return MaybeBindToTemporary(TheCall);
12523       } else {
12524         // We matched a built-in operator. Convert the arguments, then
12525         // break out so that we will build the appropriate built-in
12526         // operator node.
12527         ExprResult ArgsRes0 =
12528           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12529                                     Best->Conversions[0], AA_Passing);
12530         if (ArgsRes0.isInvalid())
12531           return ExprError();
12532         Args[0] = ArgsRes0.get();
12533 
12534         ExprResult ArgsRes1 =
12535           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12536                                     Best->Conversions[1], AA_Passing);
12537         if (ArgsRes1.isInvalid())
12538           return ExprError();
12539         Args[1] = ArgsRes1.get();
12540 
12541         break;
12542       }
12543     }
12544 
12545     case OR_No_Viable_Function: {
12546       if (CandidateSet.empty())
12547         Diag(LLoc, diag::err_ovl_no_oper)
12548           << Args[0]->getType() << /*subscript*/ 0
12549           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12550       else
12551         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12552           << Args[0]->getType()
12553           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12554       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12555                                   "[]", LLoc);
12556       return ExprError();
12557     }
12558 
12559     case OR_Ambiguous:
12560       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12561           << "[]"
12562           << Args[0]->getType() << Args[1]->getType()
12563           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12564       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12565                                   "[]", LLoc);
12566       return ExprError();
12567 
12568     case OR_Deleted:
12569       Diag(LLoc, diag::err_ovl_deleted_oper)
12570         << Best->Function->isDeleted() << "[]"
12571         << getDeletedOrUnavailableSuffix(Best->Function)
12572         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12573       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12574                                   "[]", LLoc);
12575       return ExprError();
12576     }
12577 
12578   // We matched a built-in operator; build it.
12579   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12580 }
12581 
12582 /// BuildCallToMemberFunction - Build a call to a member
12583 /// function. MemExpr is the expression that refers to the member
12584 /// function (and includes the object parameter), Args/NumArgs are the
12585 /// arguments to the function call (not including the object
12586 /// parameter). The caller needs to validate that the member
12587 /// expression refers to a non-static member function or an overloaded
12588 /// member function.
12589 ExprResult
12590 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12591                                 SourceLocation LParenLoc,
12592                                 MultiExprArg Args,
12593                                 SourceLocation RParenLoc) {
12594   assert(MemExprE->getType() == Context.BoundMemberTy ||
12595          MemExprE->getType() == Context.OverloadTy);
12596 
12597   // Dig out the member expression. This holds both the object
12598   // argument and the member function we're referring to.
12599   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12600 
12601   // Determine whether this is a call to a pointer-to-member function.
12602   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12603     assert(op->getType() == Context.BoundMemberTy);
12604     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12605 
12606     QualType fnType =
12607       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12608 
12609     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12610     QualType resultType = proto->getCallResultType(Context);
12611     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12612 
12613     // Check that the object type isn't more qualified than the
12614     // member function we're calling.
12615     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12616 
12617     QualType objectType = op->getLHS()->getType();
12618     if (op->getOpcode() == BO_PtrMemI)
12619       objectType = objectType->castAs<PointerType>()->getPointeeType();
12620     Qualifiers objectQuals = objectType.getQualifiers();
12621 
12622     Qualifiers difference = objectQuals - funcQuals;
12623     difference.removeObjCGCAttr();
12624     difference.removeAddressSpace();
12625     if (difference) {
12626       std::string qualsString = difference.getAsString();
12627       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12628         << fnType.getUnqualifiedType()
12629         << qualsString
12630         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12631     }
12632 
12633     CXXMemberCallExpr *call
12634       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12635                                         resultType, valueKind, RParenLoc);
12636 
12637     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12638                             call, nullptr))
12639       return ExprError();
12640 
12641     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12642       return ExprError();
12643 
12644     if (CheckOtherCall(call, proto))
12645       return ExprError();
12646 
12647     return MaybeBindToTemporary(call);
12648   }
12649 
12650   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12651     return new (Context)
12652         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12653 
12654   UnbridgedCastsSet UnbridgedCasts;
12655   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12656     return ExprError();
12657 
12658   MemberExpr *MemExpr;
12659   CXXMethodDecl *Method = nullptr;
12660   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12661   NestedNameSpecifier *Qualifier = nullptr;
12662   if (isa<MemberExpr>(NakedMemExpr)) {
12663     MemExpr = cast<MemberExpr>(NakedMemExpr);
12664     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12665     FoundDecl = MemExpr->getFoundDecl();
12666     Qualifier = MemExpr->getQualifier();
12667     UnbridgedCasts.restore();
12668   } else {
12669     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12670     Qualifier = UnresExpr->getQualifier();
12671 
12672     QualType ObjectType = UnresExpr->getBaseType();
12673     Expr::Classification ObjectClassification
12674       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12675                             : UnresExpr->getBase()->Classify(Context);
12676 
12677     // Add overload candidates
12678     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12679                                       OverloadCandidateSet::CSK_Normal);
12680 
12681     // FIXME: avoid copy.
12682     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12683     if (UnresExpr->hasExplicitTemplateArgs()) {
12684       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12685       TemplateArgs = &TemplateArgsBuffer;
12686     }
12687 
12688     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12689            E = UnresExpr->decls_end(); I != E; ++I) {
12690 
12691       NamedDecl *Func = *I;
12692       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12693       if (isa<UsingShadowDecl>(Func))
12694         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12695 
12696 
12697       // Microsoft supports direct constructor calls.
12698       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12699         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12700                              Args, CandidateSet);
12701       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12702         // If explicit template arguments were provided, we can't call a
12703         // non-template member function.
12704         if (TemplateArgs)
12705           continue;
12706 
12707         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12708                            ObjectClassification, Args, CandidateSet,
12709                            /*SuppressUserConversions=*/false);
12710       } else {
12711         AddMethodTemplateCandidate(
12712             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12713             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12714             /*SuppressUsedConversions=*/false);
12715       }
12716     }
12717 
12718     DeclarationName DeclName = UnresExpr->getMemberName();
12719 
12720     UnbridgedCasts.restore();
12721 
12722     OverloadCandidateSet::iterator Best;
12723     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12724                                             Best)) {
12725     case OR_Success:
12726       Method = cast<CXXMethodDecl>(Best->Function);
12727       FoundDecl = Best->FoundDecl;
12728       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12729       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12730         return ExprError();
12731       // If FoundDecl is different from Method (such as if one is a template
12732       // and the other a specialization), make sure DiagnoseUseOfDecl is
12733       // called on both.
12734       // FIXME: This would be more comprehensively addressed by modifying
12735       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12736       // being used.
12737       if (Method != FoundDecl.getDecl() &&
12738                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12739         return ExprError();
12740       break;
12741 
12742     case OR_No_Viable_Function:
12743       Diag(UnresExpr->getMemberLoc(),
12744            diag::err_ovl_no_viable_member_function_in_call)
12745         << DeclName << MemExprE->getSourceRange();
12746       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12747       // FIXME: Leaking incoming expressions!
12748       return ExprError();
12749 
12750     case OR_Ambiguous:
12751       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12752         << DeclName << MemExprE->getSourceRange();
12753       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12754       // FIXME: Leaking incoming expressions!
12755       return ExprError();
12756 
12757     case OR_Deleted:
12758       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12759         << Best->Function->isDeleted()
12760         << DeclName
12761         << getDeletedOrUnavailableSuffix(Best->Function)
12762         << MemExprE->getSourceRange();
12763       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12764       // FIXME: Leaking incoming expressions!
12765       return ExprError();
12766     }
12767 
12768     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12769 
12770     // If overload resolution picked a static member, build a
12771     // non-member call based on that function.
12772     if (Method->isStatic()) {
12773       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12774                                    RParenLoc);
12775     }
12776 
12777     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12778   }
12779 
12780   QualType ResultType = Method->getReturnType();
12781   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12782   ResultType = ResultType.getNonLValueExprType(Context);
12783 
12784   assert(Method && "Member call to something that isn't a method?");
12785   CXXMemberCallExpr *TheCall =
12786     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12787                                     ResultType, VK, RParenLoc);
12788 
12789   // Check for a valid return type.
12790   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12791                           TheCall, Method))
12792     return ExprError();
12793 
12794   // Convert the object argument (for a non-static member function call).
12795   // We only need to do this if there was actually an overload; otherwise
12796   // it was done at lookup.
12797   if (!Method->isStatic()) {
12798     ExprResult ObjectArg =
12799       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12800                                           FoundDecl, Method);
12801     if (ObjectArg.isInvalid())
12802       return ExprError();
12803     MemExpr->setBase(ObjectArg.get());
12804   }
12805 
12806   // Convert the rest of the arguments
12807   const FunctionProtoType *Proto =
12808     Method->getType()->getAs<FunctionProtoType>();
12809   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12810                               RParenLoc))
12811     return ExprError();
12812 
12813   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12814 
12815   if (CheckFunctionCall(Method, TheCall, Proto))
12816     return ExprError();
12817 
12818   // In the case the method to call was not selected by the overloading
12819   // resolution process, we still need to handle the enable_if attribute. Do
12820   // that here, so it will not hide previous -- and more relevant -- errors.
12821   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12822     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12823       Diag(MemE->getMemberLoc(),
12824            diag::err_ovl_no_viable_member_function_in_call)
12825           << Method << Method->getSourceRange();
12826       Diag(Method->getLocation(),
12827            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12828           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12829       return ExprError();
12830     }
12831   }
12832 
12833   if ((isa<CXXConstructorDecl>(CurContext) ||
12834        isa<CXXDestructorDecl>(CurContext)) &&
12835       TheCall->getMethodDecl()->isPure()) {
12836     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12837 
12838     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12839         MemExpr->performsVirtualDispatch(getLangOpts())) {
12840       Diag(MemExpr->getLocStart(),
12841            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12842         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12843         << MD->getParent()->getDeclName();
12844 
12845       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12846       if (getLangOpts().AppleKext)
12847         Diag(MemExpr->getLocStart(),
12848              diag::note_pure_qualified_call_kext)
12849              << MD->getParent()->getDeclName()
12850              << MD->getDeclName();
12851     }
12852   }
12853 
12854   if (CXXDestructorDecl *DD =
12855           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12856     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12857     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12858     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12859                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12860                          MemExpr->getMemberLoc());
12861   }
12862 
12863   return MaybeBindToTemporary(TheCall);
12864 }
12865 
12866 /// BuildCallToObjectOfClassType - Build a call to an object of class
12867 /// type (C++ [over.call.object]), which can end up invoking an
12868 /// overloaded function call operator (@c operator()) or performing a
12869 /// user-defined conversion on the object argument.
12870 ExprResult
12871 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12872                                    SourceLocation LParenLoc,
12873                                    MultiExprArg Args,
12874                                    SourceLocation RParenLoc) {
12875   if (checkPlaceholderForOverload(*this, Obj))
12876     return ExprError();
12877   ExprResult Object = Obj;
12878 
12879   UnbridgedCastsSet UnbridgedCasts;
12880   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12881     return ExprError();
12882 
12883   assert(Object.get()->getType()->isRecordType() &&
12884          "Requires object type argument");
12885   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12886 
12887   // C++ [over.call.object]p1:
12888   //  If the primary-expression E in the function call syntax
12889   //  evaluates to a class object of type "cv T", then the set of
12890   //  candidate functions includes at least the function call
12891   //  operators of T. The function call operators of T are obtained by
12892   //  ordinary lookup of the name operator() in the context of
12893   //  (E).operator().
12894   OverloadCandidateSet CandidateSet(LParenLoc,
12895                                     OverloadCandidateSet::CSK_Operator);
12896   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12897 
12898   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12899                           diag::err_incomplete_object_call, Object.get()))
12900     return true;
12901 
12902   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12903   LookupQualifiedName(R, Record->getDecl());
12904   R.suppressDiagnostics();
12905 
12906   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12907        Oper != OperEnd; ++Oper) {
12908     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12909                        Object.get()->Classify(Context), Args, CandidateSet,
12910                        /*SuppressUserConversions=*/false);
12911   }
12912 
12913   // C++ [over.call.object]p2:
12914   //   In addition, for each (non-explicit in C++0x) conversion function
12915   //   declared in T of the form
12916   //
12917   //        operator conversion-type-id () cv-qualifier;
12918   //
12919   //   where cv-qualifier is the same cv-qualification as, or a
12920   //   greater cv-qualification than, cv, and where conversion-type-id
12921   //   denotes the type "pointer to function of (P1,...,Pn) returning
12922   //   R", or the type "reference to pointer to function of
12923   //   (P1,...,Pn) returning R", or the type "reference to function
12924   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12925   //   is also considered as a candidate function. Similarly,
12926   //   surrogate call functions are added to the set of candidate
12927   //   functions for each conversion function declared in an
12928   //   accessible base class provided the function is not hidden
12929   //   within T by another intervening declaration.
12930   const auto &Conversions =
12931       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12932   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12933     NamedDecl *D = *I;
12934     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12935     if (isa<UsingShadowDecl>(D))
12936       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12937 
12938     // Skip over templated conversion functions; they aren't
12939     // surrogates.
12940     if (isa<FunctionTemplateDecl>(D))
12941       continue;
12942 
12943     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12944     if (!Conv->isExplicit()) {
12945       // Strip the reference type (if any) and then the pointer type (if
12946       // any) to get down to what might be a function type.
12947       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12948       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12949         ConvType = ConvPtrType->getPointeeType();
12950 
12951       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12952       {
12953         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12954                               Object.get(), Args, CandidateSet);
12955       }
12956     }
12957   }
12958 
12959   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12960 
12961   // Perform overload resolution.
12962   OverloadCandidateSet::iterator Best;
12963   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12964                              Best)) {
12965   case OR_Success:
12966     // Overload resolution succeeded; we'll build the appropriate call
12967     // below.
12968     break;
12969 
12970   case OR_No_Viable_Function:
12971     if (CandidateSet.empty())
12972       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12973         << Object.get()->getType() << /*call*/ 1
12974         << Object.get()->getSourceRange();
12975     else
12976       Diag(Object.get()->getLocStart(),
12977            diag::err_ovl_no_viable_object_call)
12978         << Object.get()->getType() << Object.get()->getSourceRange();
12979     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12980     break;
12981 
12982   case OR_Ambiguous:
12983     Diag(Object.get()->getLocStart(),
12984          diag::err_ovl_ambiguous_object_call)
12985       << Object.get()->getType() << Object.get()->getSourceRange();
12986     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12987     break;
12988 
12989   case OR_Deleted:
12990     Diag(Object.get()->getLocStart(),
12991          diag::err_ovl_deleted_object_call)
12992       << Best->Function->isDeleted()
12993       << Object.get()->getType()
12994       << getDeletedOrUnavailableSuffix(Best->Function)
12995       << Object.get()->getSourceRange();
12996     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12997     break;
12998   }
12999 
13000   if (Best == CandidateSet.end())
13001     return true;
13002 
13003   UnbridgedCasts.restore();
13004 
13005   if (Best->Function == nullptr) {
13006     // Since there is no function declaration, this is one of the
13007     // surrogate candidates. Dig out the conversion function.
13008     CXXConversionDecl *Conv
13009       = cast<CXXConversionDecl>(
13010                          Best->Conversions[0].UserDefined.ConversionFunction);
13011 
13012     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13013                               Best->FoundDecl);
13014     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13015       return ExprError();
13016     assert(Conv == Best->FoundDecl.getDecl() &&
13017              "Found Decl & conversion-to-functionptr should be same, right?!");
13018     // We selected one of the surrogate functions that converts the
13019     // object parameter to a function pointer. Perform the conversion
13020     // on the object argument, then let ActOnCallExpr finish the job.
13021 
13022     // Create an implicit member expr to refer to the conversion operator.
13023     // and then call it.
13024     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13025                                              Conv, HadMultipleCandidates);
13026     if (Call.isInvalid())
13027       return ExprError();
13028     // Record usage of conversion in an implicit cast.
13029     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13030                                     CK_UserDefinedConversion, Call.get(),
13031                                     nullptr, VK_RValue);
13032 
13033     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13034   }
13035 
13036   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13037 
13038   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13039   // that calls this method, using Object for the implicit object
13040   // parameter and passing along the remaining arguments.
13041   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13042 
13043   // An error diagnostic has already been printed when parsing the declaration.
13044   if (Method->isInvalidDecl())
13045     return ExprError();
13046 
13047   const FunctionProtoType *Proto =
13048     Method->getType()->getAs<FunctionProtoType>();
13049 
13050   unsigned NumParams = Proto->getNumParams();
13051 
13052   DeclarationNameInfo OpLocInfo(
13053                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13054   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13055   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13056                                            HadMultipleCandidates,
13057                                            OpLocInfo.getLoc(),
13058                                            OpLocInfo.getInfo());
13059   if (NewFn.isInvalid())
13060     return true;
13061 
13062   // Build the full argument list for the method call (the implicit object
13063   // parameter is placed at the beginning of the list).
13064   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13065   MethodArgs[0] = Object.get();
13066   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13067 
13068   // Once we've built TheCall, all of the expressions are properly
13069   // owned.
13070   QualType ResultTy = Method->getReturnType();
13071   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13072   ResultTy = ResultTy.getNonLValueExprType(Context);
13073 
13074   CXXOperatorCallExpr *TheCall = new (Context)
13075       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13076                           VK, RParenLoc, FPOptions());
13077 
13078   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13079     return true;
13080 
13081   // We may have default arguments. If so, we need to allocate more
13082   // slots in the call for them.
13083   if (Args.size() < NumParams)
13084     TheCall->setNumArgs(Context, NumParams + 1);
13085 
13086   bool IsError = false;
13087 
13088   // Initialize the implicit object parameter.
13089   ExprResult ObjRes =
13090     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13091                                         Best->FoundDecl, Method);
13092   if (ObjRes.isInvalid())
13093     IsError = true;
13094   else
13095     Object = ObjRes;
13096   TheCall->setArg(0, Object.get());
13097 
13098   // Check the argument types.
13099   for (unsigned i = 0; i != NumParams; i++) {
13100     Expr *Arg;
13101     if (i < Args.size()) {
13102       Arg = Args[i];
13103 
13104       // Pass the argument.
13105 
13106       ExprResult InputInit
13107         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13108                                                     Context,
13109                                                     Method->getParamDecl(i)),
13110                                     SourceLocation(), Arg);
13111 
13112       IsError |= InputInit.isInvalid();
13113       Arg = InputInit.getAs<Expr>();
13114     } else {
13115       ExprResult DefArg
13116         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13117       if (DefArg.isInvalid()) {
13118         IsError = true;
13119         break;
13120       }
13121 
13122       Arg = DefArg.getAs<Expr>();
13123     }
13124 
13125     TheCall->setArg(i + 1, Arg);
13126   }
13127 
13128   // If this is a variadic call, handle args passed through "...".
13129   if (Proto->isVariadic()) {
13130     // Promote the arguments (C99 6.5.2.2p7).
13131     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13132       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13133                                                         nullptr);
13134       IsError |= Arg.isInvalid();
13135       TheCall->setArg(i + 1, Arg.get());
13136     }
13137   }
13138 
13139   if (IsError) return true;
13140 
13141   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13142 
13143   if (CheckFunctionCall(Method, TheCall, Proto))
13144     return true;
13145 
13146   return MaybeBindToTemporary(TheCall);
13147 }
13148 
13149 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13150 ///  (if one exists), where @c Base is an expression of class type and
13151 /// @c Member is the name of the member we're trying to find.
13152 ExprResult
13153 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13154                                bool *NoArrowOperatorFound) {
13155   assert(Base->getType()->isRecordType() &&
13156          "left-hand side must have class type");
13157 
13158   if (checkPlaceholderForOverload(*this, Base))
13159     return ExprError();
13160 
13161   SourceLocation Loc = Base->getExprLoc();
13162 
13163   // C++ [over.ref]p1:
13164   //
13165   //   [...] An expression x->m is interpreted as (x.operator->())->m
13166   //   for a class object x of type T if T::operator->() exists and if
13167   //   the operator is selected as the best match function by the
13168   //   overload resolution mechanism (13.3).
13169   DeclarationName OpName =
13170     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13171   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13172   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13173 
13174   if (RequireCompleteType(Loc, Base->getType(),
13175                           diag::err_typecheck_incomplete_tag, Base))
13176     return ExprError();
13177 
13178   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13179   LookupQualifiedName(R, BaseRecord->getDecl());
13180   R.suppressDiagnostics();
13181 
13182   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13183        Oper != OperEnd; ++Oper) {
13184     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13185                        None, CandidateSet, /*SuppressUserConversions=*/false);
13186   }
13187 
13188   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13189 
13190   // Perform overload resolution.
13191   OverloadCandidateSet::iterator Best;
13192   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13193   case OR_Success:
13194     // Overload resolution succeeded; we'll build the call below.
13195     break;
13196 
13197   case OR_No_Viable_Function:
13198     if (CandidateSet.empty()) {
13199       QualType BaseType = Base->getType();
13200       if (NoArrowOperatorFound) {
13201         // Report this specific error to the caller instead of emitting a
13202         // diagnostic, as requested.
13203         *NoArrowOperatorFound = true;
13204         return ExprError();
13205       }
13206       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13207         << BaseType << Base->getSourceRange();
13208       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13209         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13210           << FixItHint::CreateReplacement(OpLoc, ".");
13211       }
13212     } else
13213       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13214         << "operator->" << Base->getSourceRange();
13215     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13216     return ExprError();
13217 
13218   case OR_Ambiguous:
13219     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13220       << "->" << Base->getType() << Base->getSourceRange();
13221     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13222     return ExprError();
13223 
13224   case OR_Deleted:
13225     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13226       << Best->Function->isDeleted()
13227       << "->"
13228       << getDeletedOrUnavailableSuffix(Best->Function)
13229       << Base->getSourceRange();
13230     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13231     return ExprError();
13232   }
13233 
13234   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13235 
13236   // Convert the object parameter.
13237   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13238   ExprResult BaseResult =
13239     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13240                                         Best->FoundDecl, Method);
13241   if (BaseResult.isInvalid())
13242     return ExprError();
13243   Base = BaseResult.get();
13244 
13245   // Build the operator call.
13246   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13247                                             HadMultipleCandidates, OpLoc);
13248   if (FnExpr.isInvalid())
13249     return ExprError();
13250 
13251   QualType ResultTy = Method->getReturnType();
13252   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13253   ResultTy = ResultTy.getNonLValueExprType(Context);
13254   CXXOperatorCallExpr *TheCall =
13255     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13256                                       Base, ResultTy, VK, OpLoc, FPOptions());
13257 
13258   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13259     return ExprError();
13260 
13261   if (CheckFunctionCall(Method, TheCall,
13262                         Method->getType()->castAs<FunctionProtoType>()))
13263     return ExprError();
13264 
13265   return MaybeBindToTemporary(TheCall);
13266 }
13267 
13268 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13269 /// a literal operator described by the provided lookup results.
13270 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13271                                           DeclarationNameInfo &SuffixInfo,
13272                                           ArrayRef<Expr*> Args,
13273                                           SourceLocation LitEndLoc,
13274                                        TemplateArgumentListInfo *TemplateArgs) {
13275   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13276 
13277   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13278                                     OverloadCandidateSet::CSK_Normal);
13279   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13280                         /*SuppressUserConversions=*/true);
13281 
13282   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13283 
13284   // Perform overload resolution. This will usually be trivial, but might need
13285   // to perform substitutions for a literal operator template.
13286   OverloadCandidateSet::iterator Best;
13287   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13288   case OR_Success:
13289   case OR_Deleted:
13290     break;
13291 
13292   case OR_No_Viable_Function:
13293     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13294       << R.getLookupName();
13295     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13296     return ExprError();
13297 
13298   case OR_Ambiguous:
13299     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13300     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13301     return ExprError();
13302   }
13303 
13304   FunctionDecl *FD = Best->Function;
13305   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13306                                         HadMultipleCandidates,
13307                                         SuffixInfo.getLoc(),
13308                                         SuffixInfo.getInfo());
13309   if (Fn.isInvalid())
13310     return true;
13311 
13312   // Check the argument types. This should almost always be a no-op, except
13313   // that array-to-pointer decay is applied to string literals.
13314   Expr *ConvArgs[2];
13315   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13316     ExprResult InputInit = PerformCopyInitialization(
13317       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13318       SourceLocation(), Args[ArgIdx]);
13319     if (InputInit.isInvalid())
13320       return true;
13321     ConvArgs[ArgIdx] = InputInit.get();
13322   }
13323 
13324   QualType ResultTy = FD->getReturnType();
13325   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13326   ResultTy = ResultTy.getNonLValueExprType(Context);
13327 
13328   UserDefinedLiteral *UDL =
13329     new (Context) UserDefinedLiteral(Context, Fn.get(),
13330                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13331                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13332 
13333   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13334     return ExprError();
13335 
13336   if (CheckFunctionCall(FD, UDL, nullptr))
13337     return ExprError();
13338 
13339   return MaybeBindToTemporary(UDL);
13340 }
13341 
13342 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13343 /// given LookupResult is non-empty, it is assumed to describe a member which
13344 /// will be invoked. Otherwise, the function will be found via argument
13345 /// dependent lookup.
13346 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13347 /// otherwise CallExpr is set to ExprError() and some non-success value
13348 /// is returned.
13349 Sema::ForRangeStatus
13350 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13351                                 SourceLocation RangeLoc,
13352                                 const DeclarationNameInfo &NameInfo,
13353                                 LookupResult &MemberLookup,
13354                                 OverloadCandidateSet *CandidateSet,
13355                                 Expr *Range, ExprResult *CallExpr) {
13356   Scope *S = nullptr;
13357 
13358   CandidateSet->clear();
13359   if (!MemberLookup.empty()) {
13360     ExprResult MemberRef =
13361         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13362                                  /*IsPtr=*/false, CXXScopeSpec(),
13363                                  /*TemplateKWLoc=*/SourceLocation(),
13364                                  /*FirstQualifierInScope=*/nullptr,
13365                                  MemberLookup,
13366                                  /*TemplateArgs=*/nullptr, S);
13367     if (MemberRef.isInvalid()) {
13368       *CallExpr = ExprError();
13369       return FRS_DiagnosticIssued;
13370     }
13371     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13372     if (CallExpr->isInvalid()) {
13373       *CallExpr = ExprError();
13374       return FRS_DiagnosticIssued;
13375     }
13376   } else {
13377     UnresolvedSet<0> FoundNames;
13378     UnresolvedLookupExpr *Fn =
13379       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13380                                    NestedNameSpecifierLoc(), NameInfo,
13381                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13382                                    FoundNames.begin(), FoundNames.end());
13383 
13384     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13385                                                     CandidateSet, CallExpr);
13386     if (CandidateSet->empty() || CandidateSetError) {
13387       *CallExpr = ExprError();
13388       return FRS_NoViableFunction;
13389     }
13390     OverloadCandidateSet::iterator Best;
13391     OverloadingResult OverloadResult =
13392         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13393 
13394     if (OverloadResult == OR_No_Viable_Function) {
13395       *CallExpr = ExprError();
13396       return FRS_NoViableFunction;
13397     }
13398     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13399                                          Loc, nullptr, CandidateSet, &Best,
13400                                          OverloadResult,
13401                                          /*AllowTypoCorrection=*/false);
13402     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13403       *CallExpr = ExprError();
13404       return FRS_DiagnosticIssued;
13405     }
13406   }
13407   return FRS_Success;
13408 }
13409 
13410 
13411 /// FixOverloadedFunctionReference - E is an expression that refers to
13412 /// a C++ overloaded function (possibly with some parentheses and
13413 /// perhaps a '&' around it). We have resolved the overloaded function
13414 /// to the function declaration Fn, so patch up the expression E to
13415 /// refer (possibly indirectly) to Fn. Returns the new expr.
13416 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13417                                            FunctionDecl *Fn) {
13418   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13419     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13420                                                    Found, Fn);
13421     if (SubExpr == PE->getSubExpr())
13422       return PE;
13423 
13424     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13425   }
13426 
13427   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13428     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13429                                                    Found, Fn);
13430     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13431                                SubExpr->getType()) &&
13432            "Implicit cast type cannot be determined from overload");
13433     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13434     if (SubExpr == ICE->getSubExpr())
13435       return ICE;
13436 
13437     return ImplicitCastExpr::Create(Context, ICE->getType(),
13438                                     ICE->getCastKind(),
13439                                     SubExpr, nullptr,
13440                                     ICE->getValueKind());
13441   }
13442 
13443   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13444     if (!GSE->isResultDependent()) {
13445       Expr *SubExpr =
13446           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13447       if (SubExpr == GSE->getResultExpr())
13448         return GSE;
13449 
13450       // Replace the resulting type information before rebuilding the generic
13451       // selection expression.
13452       ArrayRef<Expr *> A = GSE->getAssocExprs();
13453       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13454       unsigned ResultIdx = GSE->getResultIndex();
13455       AssocExprs[ResultIdx] = SubExpr;
13456 
13457       return new (Context) GenericSelectionExpr(
13458           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13459           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13460           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13461           ResultIdx);
13462     }
13463     // Rather than fall through to the unreachable, return the original generic
13464     // selection expression.
13465     return GSE;
13466   }
13467 
13468   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13469     assert(UnOp->getOpcode() == UO_AddrOf &&
13470            "Can only take the address of an overloaded function");
13471     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13472       if (Method->isStatic()) {
13473         // Do nothing: static member functions aren't any different
13474         // from non-member functions.
13475       } else {
13476         // Fix the subexpression, which really has to be an
13477         // UnresolvedLookupExpr holding an overloaded member function
13478         // or template.
13479         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13480                                                        Found, Fn);
13481         if (SubExpr == UnOp->getSubExpr())
13482           return UnOp;
13483 
13484         assert(isa<DeclRefExpr>(SubExpr)
13485                && "fixed to something other than a decl ref");
13486         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13487                && "fixed to a member ref with no nested name qualifier");
13488 
13489         // We have taken the address of a pointer to member
13490         // function. Perform the computation here so that we get the
13491         // appropriate pointer to member type.
13492         QualType ClassType
13493           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13494         QualType MemPtrType
13495           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13496         // Under the MS ABI, lock down the inheritance model now.
13497         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13498           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13499 
13500         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13501                                            VK_RValue, OK_Ordinary,
13502                                            UnOp->getOperatorLoc());
13503       }
13504     }
13505     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13506                                                    Found, Fn);
13507     if (SubExpr == UnOp->getSubExpr())
13508       return UnOp;
13509 
13510     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13511                                      Context.getPointerType(SubExpr->getType()),
13512                                        VK_RValue, OK_Ordinary,
13513                                        UnOp->getOperatorLoc());
13514   }
13515 
13516   // C++ [except.spec]p17:
13517   //   An exception-specification is considered to be needed when:
13518   //   - in an expression the function is the unique lookup result or the
13519   //     selected member of a set of overloaded functions
13520   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13521     ResolveExceptionSpec(E->getExprLoc(), FPT);
13522 
13523   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13524     // FIXME: avoid copy.
13525     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13526     if (ULE->hasExplicitTemplateArgs()) {
13527       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13528       TemplateArgs = &TemplateArgsBuffer;
13529     }
13530 
13531     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13532                                            ULE->getQualifierLoc(),
13533                                            ULE->getTemplateKeywordLoc(),
13534                                            Fn,
13535                                            /*enclosing*/ false, // FIXME?
13536                                            ULE->getNameLoc(),
13537                                            Fn->getType(),
13538                                            VK_LValue,
13539                                            Found.getDecl(),
13540                                            TemplateArgs);
13541     MarkDeclRefReferenced(DRE);
13542     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13543     return DRE;
13544   }
13545 
13546   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13547     // FIXME: avoid copy.
13548     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13549     if (MemExpr->hasExplicitTemplateArgs()) {
13550       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13551       TemplateArgs = &TemplateArgsBuffer;
13552     }
13553 
13554     Expr *Base;
13555 
13556     // If we're filling in a static method where we used to have an
13557     // implicit member access, rewrite to a simple decl ref.
13558     if (MemExpr->isImplicitAccess()) {
13559       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13560         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13561                                                MemExpr->getQualifierLoc(),
13562                                                MemExpr->getTemplateKeywordLoc(),
13563                                                Fn,
13564                                                /*enclosing*/ false,
13565                                                MemExpr->getMemberLoc(),
13566                                                Fn->getType(),
13567                                                VK_LValue,
13568                                                Found.getDecl(),
13569                                                TemplateArgs);
13570         MarkDeclRefReferenced(DRE);
13571         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13572         return DRE;
13573       } else {
13574         SourceLocation Loc = MemExpr->getMemberLoc();
13575         if (MemExpr->getQualifier())
13576           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13577         CheckCXXThisCapture(Loc);
13578         Base = new (Context) CXXThisExpr(Loc,
13579                                          MemExpr->getBaseType(),
13580                                          /*isImplicit=*/true);
13581       }
13582     } else
13583       Base = MemExpr->getBase();
13584 
13585     ExprValueKind valueKind;
13586     QualType type;
13587     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13588       valueKind = VK_LValue;
13589       type = Fn->getType();
13590     } else {
13591       valueKind = VK_RValue;
13592       type = Context.BoundMemberTy;
13593     }
13594 
13595     MemberExpr *ME = MemberExpr::Create(
13596         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13597         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13598         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13599         OK_Ordinary);
13600     ME->setHadMultipleCandidates(true);
13601     MarkMemberReferenced(ME);
13602     return ME;
13603   }
13604 
13605   llvm_unreachable("Invalid reference to overloaded function");
13606 }
13607 
13608 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13609                                                 DeclAccessPair Found,
13610                                                 FunctionDecl *Fn) {
13611   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13612 }
13613