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/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 /// A convenience routine for creating a decayed reference to a function.
42 static ExprResult
43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44                       bool HadMultipleCandidates,
45                       SourceLocation Loc = SourceLocation(),
46                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
47   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
48     return ExprError();
49   // If FoundDecl is different from Fn (such as if one is a template
50   // and the other a specialization), make sure DiagnoseUseOfDecl is
51   // called on both.
52   // FIXME: This would be more comprehensively addressed by modifying
53   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54   // being used.
55   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
56     return ExprError();
57   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
58                                                  VK_LValue, Loc, LocInfo);
59   if (HadMultipleCandidates)
60     DRE->setHadMultipleCandidates(true);
61 
62   S.MarkDeclRefReferenced(DRE);
63 
64   ExprResult E = DRE;
65   E = S.DefaultFunctionArrayConversion(E.get());
66   if (E.isInvalid())
67     return ExprError();
68   return E;
69 }
70 
71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72                                  bool InOverloadResolution,
73                                  StandardConversionSequence &SCS,
74                                  bool CStyle,
75                                  bool AllowObjCWritebackConversion);
76 
77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78                                                  QualType &ToType,
79                                                  bool InOverloadResolution,
80                                                  StandardConversionSequence &SCS,
81                                                  bool CStyle);
82 static OverloadingResult
83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84                         UserDefinedConversionSequence& User,
85                         OverloadCandidateSet& Conversions,
86                         bool AllowExplicit,
87                         bool AllowObjCConversionOnExplicit);
88 
89 
90 static ImplicitConversionSequence::CompareKind
91 CompareStandardConversionSequences(Sema &S,
92                                    const StandardConversionSequence& SCS1,
93                                    const StandardConversionSequence& SCS2);
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareQualificationConversions(Sema &S,
97                                 const StandardConversionSequence& SCS1,
98                                 const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareDerivedToBaseConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 /// GetConversionRank - Retrieve the implicit conversion rank
106 /// corresponding to the given implicit conversion kind.
107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
108   static const ImplicitConversionRank
109     Rank[(int)ICK_Num_Conversion_Kinds] = {
110     ICR_Exact_Match,
111     ICR_Exact_Match,
112     ICR_Exact_Match,
113     ICR_Exact_Match,
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Promotion,
117     ICR_Promotion,
118     ICR_Promotion,
119     ICR_Conversion,
120     ICR_Conversion,
121     ICR_Conversion,
122     ICR_Conversion,
123     ICR_Conversion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Complex_Real_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Writeback_Conversion
134   };
135   return Rank[(int)Kind];
136 }
137 
138 /// GetImplicitConversionName - Return the name of this kind of
139 /// implicit conversion.
140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
141   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
142     "No conversion",
143     "Lvalue-to-rvalue",
144     "Array-to-pointer",
145     "Function-to-pointer",
146     "Noreturn adjustment",
147     "Qualification",
148     "Integral promotion",
149     "Floating point promotion",
150     "Complex promotion",
151     "Integral conversion",
152     "Floating conversion",
153     "Complex conversion",
154     "Floating-integral conversion",
155     "Pointer conversion",
156     "Pointer-to-member conversion",
157     "Boolean conversion",
158     "Compatible-types conversion",
159     "Derived-to-base conversion",
160     "Vector conversion",
161     "Vector splat",
162     "Complex-real conversion",
163     "Block Pointer conversion",
164     "Transparent Union Conversion",
165     "Writeback conversion"
166   };
167   return Name[Kind];
168 }
169 
170 /// StandardConversionSequence - Set the standard conversion
171 /// sequence to the identity conversion.
172 void StandardConversionSequence::setAsIdentityConversion() {
173   First = ICK_Identity;
174   Second = ICK_Identity;
175   Third = ICK_Identity;
176   DeprecatedStringLiteralToCharPtr = false;
177   QualificationIncludesObjCLifetime = false;
178   ReferenceBinding = false;
179   DirectBinding = false;
180   IsLvalueReference = true;
181   BindsToFunctionLvalue = false;
182   BindsToRvalue = false;
183   BindsImplicitObjectArgumentWithoutRefQualifier = false;
184   ObjCLifetimeConversionBinding = false;
185   CopyConstructor = nullptr;
186 }
187 
188 /// getRank - Retrieve the rank of this standard conversion sequence
189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190 /// implicit conversions.
191 ImplicitConversionRank StandardConversionSequence::getRank() const {
192   ImplicitConversionRank Rank = ICR_Exact_Match;
193   if  (GetConversionRank(First) > Rank)
194     Rank = GetConversionRank(First);
195   if  (GetConversionRank(Second) > Rank)
196     Rank = GetConversionRank(Second);
197   if  (GetConversionRank(Third) > Rank)
198     Rank = GetConversionRank(Third);
199   return Rank;
200 }
201 
202 /// isPointerConversionToBool - Determines whether this conversion is
203 /// a conversion of a pointer or pointer-to-member to bool. This is
204 /// used as part of the ranking of standard conversion sequences
205 /// (C++ 13.3.3.2p4).
206 bool StandardConversionSequence::isPointerConversionToBool() const {
207   // Note that FromType has not necessarily been transformed by the
208   // array-to-pointer or function-to-pointer implicit conversions, so
209   // check for their presence as well as checking whether FromType is
210   // a pointer.
211   if (getToType(1)->isBooleanType() &&
212       (getFromType()->isPointerType() ||
213        getFromType()->isObjCObjectPointerType() ||
214        getFromType()->isBlockPointerType() ||
215        getFromType()->isNullPtrType() ||
216        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
217     return true;
218 
219   return false;
220 }
221 
222 /// isPointerConversionToVoidPointer - Determines whether this
223 /// conversion is a conversion of a pointer to a void pointer. This is
224 /// used as part of the ranking of standard conversion sequences (C++
225 /// 13.3.3.2p4).
226 bool
227 StandardConversionSequence::
228 isPointerConversionToVoidPointer(ASTContext& Context) const {
229   QualType FromType = getFromType();
230   QualType ToType = getToType(1);
231 
232   // Note that FromType has not necessarily been transformed by the
233   // array-to-pointer implicit conversion, so check for its presence
234   // and redo the conversion to get a pointer.
235   if (First == ICK_Array_To_Pointer)
236     FromType = Context.getArrayDecayedType(FromType);
237 
238   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
239     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
240       return ToPtrType->getPointeeType()->isVoidType();
241 
242   return false;
243 }
244 
245 /// Skip any implicit casts which could be either part of a narrowing conversion
246 /// or after one in an implicit conversion.
247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249     switch (ICE->getCastKind()) {
250     case CK_NoOp:
251     case CK_IntegralCast:
252     case CK_IntegralToBoolean:
253     case CK_IntegralToFloating:
254     case CK_FloatingToIntegral:
255     case CK_FloatingToBoolean:
256     case CK_FloatingCast:
257       Converted = ICE->getSubExpr();
258       continue;
259 
260     default:
261       return Converted;
262     }
263   }
264 
265   return Converted;
266 }
267 
268 /// Check if this standard conversion sequence represents a narrowing
269 /// conversion, according to C++11 [dcl.init.list]p7.
270 ///
271 /// \param Ctx  The AST context.
272 /// \param Converted  The result of applying this standard conversion sequence.
273 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
274 ///        value of the expression prior to the narrowing conversion.
275 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
276 ///        type of the expression prior to the narrowing conversion.
277 NarrowingKind
278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279                                              const Expr *Converted,
280                                              APValue &ConstantValue,
281                                              QualType &ConstantType) const {
282   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
283 
284   // C++11 [dcl.init.list]p7:
285   //   A narrowing conversion is an implicit conversion ...
286   QualType FromType = getToType(0);
287   QualType ToType = getToType(1);
288   switch (Second) {
289   // -- from a floating-point type to an integer type, or
290   //
291   // -- from an integer type or unscoped enumeration type to a floating-point
292   //    type, except where the source is a constant expression and the actual
293   //    value after conversion will fit into the target type and will produce
294   //    the original value when converted back to the original type, or
295   case ICK_Floating_Integral:
296     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
297       return NK_Type_Narrowing;
298     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
299       llvm::APSInt IntConstantValue;
300       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
301       if (Initializer &&
302           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
303         // Convert the integer to the floating type.
304         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
305         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
306                                 llvm::APFloat::rmNearestTiesToEven);
307         // And back.
308         llvm::APSInt ConvertedValue = IntConstantValue;
309         bool ignored;
310         Result.convertToInteger(ConvertedValue,
311                                 llvm::APFloat::rmTowardZero, &ignored);
312         // If the resulting value is different, this was a narrowing conversion.
313         if (IntConstantValue != ConvertedValue) {
314           ConstantValue = APValue(IntConstantValue);
315           ConstantType = Initializer->getType();
316           return NK_Constant_Narrowing;
317         }
318       } else {
319         // Variables are always narrowings.
320         return NK_Variable_Narrowing;
321       }
322     }
323     return NK_Not_Narrowing;
324 
325   // -- from long double to double or float, or from double to float, except
326   //    where the source is a constant expression and the actual value after
327   //    conversion is within the range of values that can be represented (even
328   //    if it cannot be represented exactly), or
329   case ICK_Floating_Conversion:
330     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
331         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
332       // FromType is larger than ToType.
333       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
335         // Constant!
336         assert(ConstantValue.isFloat());
337         llvm::APFloat FloatVal = ConstantValue.getFloat();
338         // Convert the source value into the target type.
339         bool ignored;
340         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
341           Ctx.getFloatTypeSemantics(ToType),
342           llvm::APFloat::rmNearestTiesToEven, &ignored);
343         // If there was no overflow, the source value is within the range of
344         // values that can be represented.
345         if (ConvertStatus & llvm::APFloat::opOverflow) {
346           ConstantType = Initializer->getType();
347           return NK_Constant_Narrowing;
348         }
349       } else {
350         return NK_Variable_Narrowing;
351       }
352     }
353     return NK_Not_Narrowing;
354 
355   // -- from an integer type or unscoped enumeration type to an integer type
356   //    that cannot represent all the values of the original type, except where
357   //    the source is a constant expression and the actual value after
358   //    conversion will fit into the target type and will produce the original
359   //    value when converted back to the original type.
360   case ICK_Boolean_Conversion:  // Bools are integers too.
361     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
362       // Boolean conversions can be from pointers and pointers to members
363       // [conv.bool], and those aren't considered narrowing conversions.
364       return NK_Not_Narrowing;
365     }  // Otherwise, fall through to the integral case.
366   case ICK_Integral_Conversion: {
367     assert(FromType->isIntegralOrUnscopedEnumerationType());
368     assert(ToType->isIntegralOrUnscopedEnumerationType());
369     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
370     const unsigned FromWidth = Ctx.getIntWidth(FromType);
371     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
372     const unsigned ToWidth = Ctx.getIntWidth(ToType);
373 
374     if (FromWidth > ToWidth ||
375         (FromWidth == ToWidth && FromSigned != ToSigned) ||
376         (FromSigned && !ToSigned)) {
377       // Not all values of FromType can be represented in ToType.
378       llvm::APSInt InitializerValue;
379       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
380       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
381         // Such conversions on variables are always narrowing.
382         return NK_Variable_Narrowing;
383       }
384       bool Narrowing = false;
385       if (FromWidth < ToWidth) {
386         // Negative -> unsigned is narrowing. Otherwise, more bits is never
387         // narrowing.
388         if (InitializerValue.isSigned() && InitializerValue.isNegative())
389           Narrowing = true;
390       } else {
391         // Add a bit to the InitializerValue so we don't have to worry about
392         // signed vs. unsigned comparisons.
393         InitializerValue = InitializerValue.extend(
394           InitializerValue.getBitWidth() + 1);
395         // Convert the initializer to and from the target width and signed-ness.
396         llvm::APSInt ConvertedValue = InitializerValue;
397         ConvertedValue = ConvertedValue.trunc(ToWidth);
398         ConvertedValue.setIsSigned(ToSigned);
399         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
400         ConvertedValue.setIsSigned(InitializerValue.isSigned());
401         // If the result is different, this was a narrowing conversion.
402         if (ConvertedValue != InitializerValue)
403           Narrowing = true;
404       }
405       if (Narrowing) {
406         ConstantType = Initializer->getType();
407         ConstantValue = APValue(InitializerValue);
408         return NK_Constant_Narrowing;
409       }
410     }
411     return NK_Not_Narrowing;
412   }
413 
414   default:
415     // Other kinds of conversions are not narrowings.
416     return NK_Not_Narrowing;
417   }
418 }
419 
420 /// dump - Print this standard conversion sequence to standard
421 /// error. Useful for debugging overloading issues.
422 void StandardConversionSequence::dump() const {
423   raw_ostream &OS = llvm::errs();
424   bool PrintedSomething = false;
425   if (First != ICK_Identity) {
426     OS << GetImplicitConversionName(First);
427     PrintedSomething = true;
428   }
429 
430   if (Second != ICK_Identity) {
431     if (PrintedSomething) {
432       OS << " -> ";
433     }
434     OS << GetImplicitConversionName(Second);
435 
436     if (CopyConstructor) {
437       OS << " (by copy constructor)";
438     } else if (DirectBinding) {
439       OS << " (direct reference binding)";
440     } else if (ReferenceBinding) {
441       OS << " (reference binding)";
442     }
443     PrintedSomething = true;
444   }
445 
446   if (Third != ICK_Identity) {
447     if (PrintedSomething) {
448       OS << " -> ";
449     }
450     OS << GetImplicitConversionName(Third);
451     PrintedSomething = true;
452   }
453 
454   if (!PrintedSomething) {
455     OS << "No conversions required";
456   }
457 }
458 
459 /// dump - Print this user-defined conversion sequence to standard
460 /// error. Useful for debugging overloading issues.
461 void UserDefinedConversionSequence::dump() const {
462   raw_ostream &OS = llvm::errs();
463   if (Before.First || Before.Second || Before.Third) {
464     Before.dump();
465     OS << " -> ";
466   }
467   if (ConversionFunction)
468     OS << '\'' << *ConversionFunction << '\'';
469   else
470     OS << "aggregate initialization";
471   if (After.First || After.Second || After.Third) {
472     OS << " -> ";
473     After.dump();
474   }
475 }
476 
477 /// dump - Print this implicit conversion sequence to standard
478 /// error. Useful for debugging overloading issues.
479 void ImplicitConversionSequence::dump() const {
480   raw_ostream &OS = llvm::errs();
481   if (isStdInitializerListElement())
482     OS << "Worst std::initializer_list element conversion: ";
483   switch (ConversionKind) {
484   case StandardConversion:
485     OS << "Standard conversion: ";
486     Standard.dump();
487     break;
488   case UserDefinedConversion:
489     OS << "User-defined conversion: ";
490     UserDefined.dump();
491     break;
492   case EllipsisConversion:
493     OS << "Ellipsis conversion";
494     break;
495   case AmbiguousConversion:
496     OS << "Ambiguous conversion";
497     break;
498   case BadConversion:
499     OS << "Bad conversion";
500     break;
501   }
502 
503   OS << "\n";
504 }
505 
506 void AmbiguousConversionSequence::construct() {
507   new (&conversions()) ConversionSet();
508 }
509 
510 void AmbiguousConversionSequence::destruct() {
511   conversions().~ConversionSet();
512 }
513 
514 void
515 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
516   FromTypePtr = O.FromTypePtr;
517   ToTypePtr = O.ToTypePtr;
518   new (&conversions()) ConversionSet(O.conversions());
519 }
520 
521 namespace {
522   // Structure used by DeductionFailureInfo to store
523   // template argument information.
524   struct DFIArguments {
525     TemplateArgument FirstArg;
526     TemplateArgument SecondArg;
527   };
528   // Structure used by DeductionFailureInfo to store
529   // template parameter and template argument information.
530   struct DFIParamWithArguments : DFIArguments {
531     TemplateParameter Param;
532   };
533 }
534 
535 /// \brief Convert from Sema's representation of template deduction information
536 /// to the form used in overload-candidate information.
537 DeductionFailureInfo
538 clang::MakeDeductionFailureInfo(ASTContext &Context,
539                                 Sema::TemplateDeductionResult TDK,
540                                 TemplateDeductionInfo &Info) {
541   DeductionFailureInfo Result;
542   Result.Result = static_cast<unsigned>(TDK);
543   Result.HasDiagnostic = false;
544   Result.Data = nullptr;
545   switch (TDK) {
546   case Sema::TDK_Success:
547   case Sema::TDK_Invalid:
548   case Sema::TDK_InstantiationDepth:
549   case Sema::TDK_TooManyArguments:
550   case Sema::TDK_TooFewArguments:
551     break;
552 
553   case Sema::TDK_Incomplete:
554   case Sema::TDK_InvalidExplicitArguments:
555     Result.Data = Info.Param.getOpaqueValue();
556     break;
557 
558   case Sema::TDK_NonDeducedMismatch: {
559     // FIXME: Should allocate from normal heap so that we can free this later.
560     DFIArguments *Saved = new (Context) DFIArguments;
561     Saved->FirstArg = Info.FirstArg;
562     Saved->SecondArg = Info.SecondArg;
563     Result.Data = Saved;
564     break;
565   }
566 
567   case Sema::TDK_Inconsistent:
568   case Sema::TDK_Underqualified: {
569     // FIXME: Should allocate from normal heap so that we can free this later.
570     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
571     Saved->Param = Info.Param;
572     Saved->FirstArg = Info.FirstArg;
573     Saved->SecondArg = Info.SecondArg;
574     Result.Data = Saved;
575     break;
576   }
577 
578   case Sema::TDK_SubstitutionFailure:
579     Result.Data = Info.take();
580     if (Info.hasSFINAEDiagnostic()) {
581       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
582           SourceLocation(), PartialDiagnostic::NullDiagnostic());
583       Info.takeSFINAEDiagnostic(*Diag);
584       Result.HasDiagnostic = true;
585     }
586     break;
587 
588   case Sema::TDK_FailedOverloadResolution:
589     Result.Data = Info.Expression;
590     break;
591 
592   case Sema::TDK_MiscellaneousDeductionFailure:
593     break;
594   }
595 
596   return Result;
597 }
598 
599 void DeductionFailureInfo::Destroy() {
600   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601   case Sema::TDK_Success:
602   case Sema::TDK_Invalid:
603   case Sema::TDK_InstantiationDepth:
604   case Sema::TDK_Incomplete:
605   case Sema::TDK_TooManyArguments:
606   case Sema::TDK_TooFewArguments:
607   case Sema::TDK_InvalidExplicitArguments:
608   case Sema::TDK_FailedOverloadResolution:
609     break;
610 
611   case Sema::TDK_Inconsistent:
612   case Sema::TDK_Underqualified:
613   case Sema::TDK_NonDeducedMismatch:
614     // FIXME: Destroy the data?
615     Data = nullptr;
616     break;
617 
618   case Sema::TDK_SubstitutionFailure:
619     // FIXME: Destroy the template argument list?
620     Data = nullptr;
621     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
622       Diag->~PartialDiagnosticAt();
623       HasDiagnostic = false;
624     }
625     break;
626 
627   // Unhandled
628   case Sema::TDK_MiscellaneousDeductionFailure:
629     break;
630   }
631 }
632 
633 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
634   if (HasDiagnostic)
635     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636   return nullptr;
637 }
638 
639 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
640   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641   case Sema::TDK_Success:
642   case Sema::TDK_Invalid:
643   case Sema::TDK_InstantiationDepth:
644   case Sema::TDK_TooManyArguments:
645   case Sema::TDK_TooFewArguments:
646   case Sema::TDK_SubstitutionFailure:
647   case Sema::TDK_NonDeducedMismatch:
648   case Sema::TDK_FailedOverloadResolution:
649     return TemplateParameter();
650 
651   case Sema::TDK_Incomplete:
652   case Sema::TDK_InvalidExplicitArguments:
653     return TemplateParameter::getFromOpaqueValue(Data);
654 
655   case Sema::TDK_Inconsistent:
656   case Sema::TDK_Underqualified:
657     return static_cast<DFIParamWithArguments*>(Data)->Param;
658 
659   // Unhandled
660   case Sema::TDK_MiscellaneousDeductionFailure:
661     break;
662   }
663 
664   return TemplateParameter();
665 }
666 
667 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
668   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
669   case Sema::TDK_Success:
670   case Sema::TDK_Invalid:
671   case Sema::TDK_InstantiationDepth:
672   case Sema::TDK_TooManyArguments:
673   case Sema::TDK_TooFewArguments:
674   case Sema::TDK_Incomplete:
675   case Sema::TDK_InvalidExplicitArguments:
676   case Sema::TDK_Inconsistent:
677   case Sema::TDK_Underqualified:
678   case Sema::TDK_NonDeducedMismatch:
679   case Sema::TDK_FailedOverloadResolution:
680     return nullptr;
681 
682   case Sema::TDK_SubstitutionFailure:
683     return static_cast<TemplateArgumentList*>(Data);
684 
685   // Unhandled
686   case Sema::TDK_MiscellaneousDeductionFailure:
687     break;
688   }
689 
690   return nullptr;
691 }
692 
693 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
694   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695   case Sema::TDK_Success:
696   case Sema::TDK_Invalid:
697   case Sema::TDK_InstantiationDepth:
698   case Sema::TDK_Incomplete:
699   case Sema::TDK_TooManyArguments:
700   case Sema::TDK_TooFewArguments:
701   case Sema::TDK_InvalidExplicitArguments:
702   case Sema::TDK_SubstitutionFailure:
703   case Sema::TDK_FailedOverloadResolution:
704     return nullptr;
705 
706   case Sema::TDK_Inconsistent:
707   case Sema::TDK_Underqualified:
708   case Sema::TDK_NonDeducedMismatch:
709     return &static_cast<DFIArguments*>(Data)->FirstArg;
710 
711   // Unhandled
712   case Sema::TDK_MiscellaneousDeductionFailure:
713     break;
714   }
715 
716   return nullptr;
717 }
718 
719 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
720   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721   case Sema::TDK_Success:
722   case Sema::TDK_Invalid:
723   case Sema::TDK_InstantiationDepth:
724   case Sema::TDK_Incomplete:
725   case Sema::TDK_TooManyArguments:
726   case Sema::TDK_TooFewArguments:
727   case Sema::TDK_InvalidExplicitArguments:
728   case Sema::TDK_SubstitutionFailure:
729   case Sema::TDK_FailedOverloadResolution:
730     return nullptr;
731 
732   case Sema::TDK_Inconsistent:
733   case Sema::TDK_Underqualified:
734   case Sema::TDK_NonDeducedMismatch:
735     return &static_cast<DFIArguments*>(Data)->SecondArg;
736 
737   // Unhandled
738   case Sema::TDK_MiscellaneousDeductionFailure:
739     break;
740   }
741 
742   return nullptr;
743 }
744 
745 Expr *DeductionFailureInfo::getExpr() {
746   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
747         Sema::TDK_FailedOverloadResolution)
748     return static_cast<Expr*>(Data);
749 
750   return nullptr;
751 }
752 
753 void OverloadCandidateSet::destroyCandidates() {
754   for (iterator i = begin(), e = end(); i != e; ++i) {
755     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
756       i->Conversions[ii].~ImplicitConversionSequence();
757     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
758       i->DeductionFailure.Destroy();
759   }
760 }
761 
762 void OverloadCandidateSet::clear() {
763   destroyCandidates();
764   NumInlineSequences = 0;
765   Candidates.clear();
766   Functions.clear();
767 }
768 
769 namespace {
770   class UnbridgedCastsSet {
771     struct Entry {
772       Expr **Addr;
773       Expr *Saved;
774     };
775     SmallVector<Entry, 2> Entries;
776 
777   public:
778     void save(Sema &S, Expr *&E) {
779       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
780       Entry entry = { &E, E };
781       Entries.push_back(entry);
782       E = S.stripARCUnbridgedCast(E);
783     }
784 
785     void restore() {
786       for (SmallVectorImpl<Entry>::iterator
787              i = Entries.begin(), e = Entries.end(); i != e; ++i)
788         *i->Addr = i->Saved;
789     }
790   };
791 }
792 
793 /// checkPlaceholderForOverload - Do any interesting placeholder-like
794 /// preprocessing on the given expression.
795 ///
796 /// \param unbridgedCasts a collection to which to add unbridged casts;
797 ///   without this, they will be immediately diagnosed as errors
798 ///
799 /// Return true on unrecoverable error.
800 static bool
801 checkPlaceholderForOverload(Sema &S, Expr *&E,
802                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
803   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
804     // We can't handle overloaded expressions here because overload
805     // resolution might reasonably tweak them.
806     if (placeholder->getKind() == BuiltinType::Overload) return false;
807 
808     // If the context potentially accepts unbridged ARC casts, strip
809     // the unbridged cast and add it to the collection for later restoration.
810     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
811         unbridgedCasts) {
812       unbridgedCasts->save(S, E);
813       return false;
814     }
815 
816     // Go ahead and check everything else.
817     ExprResult result = S.CheckPlaceholderExpr(E);
818     if (result.isInvalid())
819       return true;
820 
821     E = result.get();
822     return false;
823   }
824 
825   // Nothing to do.
826   return false;
827 }
828 
829 /// checkArgPlaceholdersForOverload - Check a set of call operands for
830 /// placeholders.
831 static bool checkArgPlaceholdersForOverload(Sema &S,
832                                             MultiExprArg Args,
833                                             UnbridgedCastsSet &unbridged) {
834   for (unsigned i = 0, e = Args.size(); i != e; ++i)
835     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
836       return true;
837 
838   return false;
839 }
840 
841 // IsOverload - Determine whether the given New declaration is an
842 // overload of the declarations in Old. This routine returns false if
843 // New and Old cannot be overloaded, e.g., if New has the same
844 // signature as some function in Old (C++ 1.3.10) or if the Old
845 // declarations aren't functions (or function templates) at all. When
846 // it does return false, MatchedDecl will point to the decl that New
847 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
848 // top of the underlying declaration.
849 //
850 // Example: Given the following input:
851 //
852 //   void f(int, float); // #1
853 //   void f(int, int); // #2
854 //   int f(int, int); // #3
855 //
856 // When we process #1, there is no previous declaration of "f",
857 // so IsOverload will not be used.
858 //
859 // When we process #2, Old contains only the FunctionDecl for #1.  By
860 // comparing the parameter types, we see that #1 and #2 are overloaded
861 // (since they have different signatures), so this routine returns
862 // false; MatchedDecl is unchanged.
863 //
864 // When we process #3, Old is an overload set containing #1 and #2. We
865 // compare the signatures of #3 to #1 (they're overloaded, so we do
866 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
867 // identical (return types of functions are not part of the
868 // signature), IsOverload returns false and MatchedDecl will be set to
869 // point to the FunctionDecl for #2.
870 //
871 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
872 // into a class by a using declaration.  The rules for whether to hide
873 // shadow declarations ignore some properties which otherwise figure
874 // into a function template's signature.
875 Sema::OverloadKind
876 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
877                     NamedDecl *&Match, bool NewIsUsingDecl) {
878   for (LookupResult::iterator I = Old.begin(), E = Old.end();
879          I != E; ++I) {
880     NamedDecl *OldD = *I;
881 
882     bool OldIsUsingDecl = false;
883     if (isa<UsingShadowDecl>(OldD)) {
884       OldIsUsingDecl = true;
885 
886       // We can always introduce two using declarations into the same
887       // context, even if they have identical signatures.
888       if (NewIsUsingDecl) continue;
889 
890       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
891     }
892 
893     // If either declaration was introduced by a using declaration,
894     // we'll need to use slightly different rules for matching.
895     // Essentially, these rules are the normal rules, except that
896     // function templates hide function templates with different
897     // return types or template parameter lists.
898     bool UseMemberUsingDeclRules =
899       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
900       !New->getFriendObjectKind();
901 
902     if (FunctionDecl *OldF = OldD->getAsFunction()) {
903       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
904         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
905           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
906           continue;
907         }
908 
909         if (!isa<FunctionTemplateDecl>(OldD) &&
910             !shouldLinkPossiblyHiddenDecl(*I, New))
911           continue;
912 
913         Match = *I;
914         return Ovl_Match;
915       }
916     } else if (isa<UsingDecl>(OldD)) {
917       // We can overload with these, which can show up when doing
918       // redeclaration checks for UsingDecls.
919       assert(Old.getLookupKind() == LookupUsingDeclName);
920     } else if (isa<TagDecl>(OldD)) {
921       // We can always overload with tags by hiding them.
922     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
923       // Optimistically assume that an unresolved using decl will
924       // overload; if it doesn't, we'll have to diagnose during
925       // template instantiation.
926     } else {
927       // (C++ 13p1):
928       //   Only function declarations can be overloaded; object and type
929       //   declarations cannot be overloaded.
930       Match = *I;
931       return Ovl_NonFunction;
932     }
933   }
934 
935   return Ovl_Overload;
936 }
937 
938 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
939                       bool UseUsingDeclRules) {
940   // C++ [basic.start.main]p2: This function shall not be overloaded.
941   if (New->isMain())
942     return false;
943 
944   // MSVCRT user defined entry points cannot be overloaded.
945   if (New->isMSVCRTEntryPoint())
946     return false;
947 
948   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
949   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
950 
951   // C++ [temp.fct]p2:
952   //   A function template can be overloaded with other function templates
953   //   and with normal (non-template) functions.
954   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
955     return true;
956 
957   // Is the function New an overload of the function Old?
958   QualType OldQType = Context.getCanonicalType(Old->getType());
959   QualType NewQType = Context.getCanonicalType(New->getType());
960 
961   // Compare the signatures (C++ 1.3.10) of the two functions to
962   // determine whether they are overloads. If we find any mismatch
963   // in the signature, they are overloads.
964 
965   // If either of these functions is a K&R-style function (no
966   // prototype), then we consider them to have matching signatures.
967   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
968       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
969     return false;
970 
971   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
972   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
973 
974   // The signature of a function includes the types of its
975   // parameters (C++ 1.3.10), which includes the presence or absence
976   // of the ellipsis; see C++ DR 357).
977   if (OldQType != NewQType &&
978       (OldType->getNumParams() != NewType->getNumParams() ||
979        OldType->isVariadic() != NewType->isVariadic() ||
980        !FunctionParamTypesAreEqual(OldType, NewType)))
981     return true;
982 
983   // C++ [temp.over.link]p4:
984   //   The signature of a function template consists of its function
985   //   signature, its return type and its template parameter list. The names
986   //   of the template parameters are significant only for establishing the
987   //   relationship between the template parameters and the rest of the
988   //   signature.
989   //
990   // We check the return type and template parameter lists for function
991   // templates first; the remaining checks follow.
992   //
993   // However, we don't consider either of these when deciding whether
994   // a member introduced by a shadow declaration is hidden.
995   if (!UseUsingDeclRules && NewTemplate &&
996       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
997                                        OldTemplate->getTemplateParameters(),
998                                        false, TPL_TemplateMatch) ||
999        OldType->getReturnType() != NewType->getReturnType()))
1000     return true;
1001 
1002   // If the function is a class member, its signature includes the
1003   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1004   //
1005   // As part of this, also check whether one of the member functions
1006   // is static, in which case they are not overloads (C++
1007   // 13.1p2). While not part of the definition of the signature,
1008   // this check is important to determine whether these functions
1009   // can be overloaded.
1010   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1011   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1012   if (OldMethod && NewMethod &&
1013       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1014     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1015       if (!UseUsingDeclRules &&
1016           (OldMethod->getRefQualifier() == RQ_None ||
1017            NewMethod->getRefQualifier() == RQ_None)) {
1018         // C++0x [over.load]p2:
1019         //   - Member function declarations with the same name and the same
1020         //     parameter-type-list as well as member function template
1021         //     declarations with the same name, the same parameter-type-list, and
1022         //     the same template parameter lists cannot be overloaded if any of
1023         //     them, but not all, have a ref-qualifier (8.3.5).
1024         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1025           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1026         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1027       }
1028       return true;
1029     }
1030 
1031     // We may not have applied the implicit const for a constexpr member
1032     // function yet (because we haven't yet resolved whether this is a static
1033     // or non-static member function). Add it now, on the assumption that this
1034     // is a redeclaration of OldMethod.
1035     unsigned OldQuals = OldMethod->getTypeQualifiers();
1036     unsigned NewQuals = NewMethod->getTypeQualifiers();
1037     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1038         !isa<CXXConstructorDecl>(NewMethod))
1039       NewQuals |= Qualifiers::Const;
1040 
1041     // We do not allow overloading based off of '__restrict'.
1042     OldQuals &= ~Qualifiers::Restrict;
1043     NewQuals &= ~Qualifiers::Restrict;
1044     if (OldQuals != NewQuals)
1045       return true;
1046   }
1047 
1048   // enable_if attributes are an order-sensitive part of the signature.
1049   for (specific_attr_iterator<EnableIfAttr>
1050          NewI = New->specific_attr_begin<EnableIfAttr>(),
1051          NewE = New->specific_attr_end<EnableIfAttr>(),
1052          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1053          OldE = Old->specific_attr_end<EnableIfAttr>();
1054        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1055     if (NewI == NewE || OldI == OldE)
1056       return true;
1057     llvm::FoldingSetNodeID NewID, OldID;
1058     NewI->getCond()->Profile(NewID, Context, true);
1059     OldI->getCond()->Profile(OldID, Context, true);
1060     if (NewID != OldID)
1061       return true;
1062   }
1063 
1064   // The signatures match; this is not an overload.
1065   return false;
1066 }
1067 
1068 /// \brief Checks availability of the function depending on the current
1069 /// function context. Inside an unavailable function, unavailability is ignored.
1070 ///
1071 /// \returns true if \arg FD is unavailable and current context is inside
1072 /// an available function, false otherwise.
1073 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1074   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1075 }
1076 
1077 /// \brief Tries a user-defined conversion from From to ToType.
1078 ///
1079 /// Produces an implicit conversion sequence for when a standard conversion
1080 /// is not an option. See TryImplicitConversion for more information.
1081 static ImplicitConversionSequence
1082 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1083                          bool SuppressUserConversions,
1084                          bool AllowExplicit,
1085                          bool InOverloadResolution,
1086                          bool CStyle,
1087                          bool AllowObjCWritebackConversion,
1088                          bool AllowObjCConversionOnExplicit) {
1089   ImplicitConversionSequence ICS;
1090 
1091   if (SuppressUserConversions) {
1092     // We're not in the case above, so there is no conversion that
1093     // we can perform.
1094     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1095     return ICS;
1096   }
1097 
1098   // Attempt user-defined conversion.
1099   OverloadCandidateSet Conversions(From->getExprLoc(),
1100                                    OverloadCandidateSet::CSK_Normal);
1101   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1102                                   Conversions, AllowExplicit,
1103                                   AllowObjCConversionOnExplicit)) {
1104   case OR_Success:
1105   case OR_Deleted:
1106     ICS.setUserDefined();
1107     ICS.UserDefined.Before.setAsIdentityConversion();
1108     // C++ [over.ics.user]p4:
1109     //   A conversion of an expression of class type to the same class
1110     //   type is given Exact Match rank, and a conversion of an
1111     //   expression of class type to a base class of that type is
1112     //   given Conversion rank, in spite of the fact that a copy
1113     //   constructor (i.e., a user-defined conversion function) is
1114     //   called for those cases.
1115     if (CXXConstructorDecl *Constructor
1116           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1117       QualType FromCanon
1118         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1119       QualType ToCanon
1120         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1121       if (Constructor->isCopyConstructor() &&
1122           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1123         // Turn this into a "standard" conversion sequence, so that it
1124         // gets ranked with standard conversion sequences.
1125         ICS.setStandard();
1126         ICS.Standard.setAsIdentityConversion();
1127         ICS.Standard.setFromType(From->getType());
1128         ICS.Standard.setAllToTypes(ToType);
1129         ICS.Standard.CopyConstructor = Constructor;
1130         if (ToCanon != FromCanon)
1131           ICS.Standard.Second = ICK_Derived_To_Base;
1132       }
1133     }
1134     break;
1135 
1136   case OR_Ambiguous:
1137     ICS.setAmbiguous();
1138     ICS.Ambiguous.setFromType(From->getType());
1139     ICS.Ambiguous.setToType(ToType);
1140     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1141          Cand != Conversions.end(); ++Cand)
1142       if (Cand->Viable)
1143         ICS.Ambiguous.addConversion(Cand->Function);
1144     break;
1145 
1146     // Fall through.
1147   case OR_No_Viable_Function:
1148     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1149     break;
1150   }
1151 
1152   return ICS;
1153 }
1154 
1155 /// TryImplicitConversion - Attempt to perform an implicit conversion
1156 /// from the given expression (Expr) to the given type (ToType). This
1157 /// function returns an implicit conversion sequence that can be used
1158 /// to perform the initialization. Given
1159 ///
1160 ///   void f(float f);
1161 ///   void g(int i) { f(i); }
1162 ///
1163 /// this routine would produce an implicit conversion sequence to
1164 /// describe the initialization of f from i, which will be a standard
1165 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1166 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1167 //
1168 /// Note that this routine only determines how the conversion can be
1169 /// performed; it does not actually perform the conversion. As such,
1170 /// it will not produce any diagnostics if no conversion is available,
1171 /// but will instead return an implicit conversion sequence of kind
1172 /// "BadConversion".
1173 ///
1174 /// If @p SuppressUserConversions, then user-defined conversions are
1175 /// not permitted.
1176 /// If @p AllowExplicit, then explicit user-defined conversions are
1177 /// permitted.
1178 ///
1179 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1180 /// writeback conversion, which allows __autoreleasing id* parameters to
1181 /// be initialized with __strong id* or __weak id* arguments.
1182 static ImplicitConversionSequence
1183 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1184                       bool SuppressUserConversions,
1185                       bool AllowExplicit,
1186                       bool InOverloadResolution,
1187                       bool CStyle,
1188                       bool AllowObjCWritebackConversion,
1189                       bool AllowObjCConversionOnExplicit) {
1190   ImplicitConversionSequence ICS;
1191   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1192                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1193     ICS.setStandard();
1194     return ICS;
1195   }
1196 
1197   if (!S.getLangOpts().CPlusPlus) {
1198     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1199     return ICS;
1200   }
1201 
1202   // C++ [over.ics.user]p4:
1203   //   A conversion of an expression of class type to the same class
1204   //   type is given Exact Match rank, and a conversion of an
1205   //   expression of class type to a base class of that type is
1206   //   given Conversion rank, in spite of the fact that a copy/move
1207   //   constructor (i.e., a user-defined conversion function) is
1208   //   called for those cases.
1209   QualType FromType = From->getType();
1210   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1211       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1212        S.IsDerivedFrom(FromType, ToType))) {
1213     ICS.setStandard();
1214     ICS.Standard.setAsIdentityConversion();
1215     ICS.Standard.setFromType(FromType);
1216     ICS.Standard.setAllToTypes(ToType);
1217 
1218     // We don't actually check at this point whether there is a valid
1219     // copy/move constructor, since overloading just assumes that it
1220     // exists. When we actually perform initialization, we'll find the
1221     // appropriate constructor to copy the returned object, if needed.
1222     ICS.Standard.CopyConstructor = nullptr;
1223 
1224     // Determine whether this is considered a derived-to-base conversion.
1225     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1226       ICS.Standard.Second = ICK_Derived_To_Base;
1227 
1228     return ICS;
1229   }
1230 
1231   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1232                                   AllowExplicit, InOverloadResolution, CStyle,
1233                                   AllowObjCWritebackConversion,
1234                                   AllowObjCConversionOnExplicit);
1235 }
1236 
1237 ImplicitConversionSequence
1238 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1239                             bool SuppressUserConversions,
1240                             bool AllowExplicit,
1241                             bool InOverloadResolution,
1242                             bool CStyle,
1243                             bool AllowObjCWritebackConversion) {
1244   return ::TryImplicitConversion(*this, From, ToType,
1245                                  SuppressUserConversions, AllowExplicit,
1246                                  InOverloadResolution, CStyle,
1247                                  AllowObjCWritebackConversion,
1248                                  /*AllowObjCConversionOnExplicit=*/false);
1249 }
1250 
1251 /// PerformImplicitConversion - Perform an implicit conversion of the
1252 /// expression From to the type ToType. Returns the
1253 /// converted expression. Flavor is the kind of conversion we're
1254 /// performing, used in the error message. If @p AllowExplicit,
1255 /// explicit user-defined conversions are permitted.
1256 ExprResult
1257 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1258                                 AssignmentAction Action, bool AllowExplicit) {
1259   ImplicitConversionSequence ICS;
1260   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1261 }
1262 
1263 ExprResult
1264 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1265                                 AssignmentAction Action, bool AllowExplicit,
1266                                 ImplicitConversionSequence& ICS) {
1267   if (checkPlaceholderForOverload(*this, From))
1268     return ExprError();
1269 
1270   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1271   bool AllowObjCWritebackConversion
1272     = getLangOpts().ObjCAutoRefCount &&
1273       (Action == AA_Passing || Action == AA_Sending);
1274   if (getLangOpts().ObjC1)
1275     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1276                                       ToType, From->getType(), From);
1277   ICS = ::TryImplicitConversion(*this, From, ToType,
1278                                 /*SuppressUserConversions=*/false,
1279                                 AllowExplicit,
1280                                 /*InOverloadResolution=*/false,
1281                                 /*CStyle=*/false,
1282                                 AllowObjCWritebackConversion,
1283                                 /*AllowObjCConversionOnExplicit=*/false);
1284   return PerformImplicitConversion(From, ToType, ICS, Action);
1285 }
1286 
1287 /// \brief Determine whether the conversion from FromType to ToType is a valid
1288 /// conversion that strips "noreturn" off the nested function type.
1289 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1290                                 QualType &ResultTy) {
1291   if (Context.hasSameUnqualifiedType(FromType, ToType))
1292     return false;
1293 
1294   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1295   // where F adds one of the following at most once:
1296   //   - a pointer
1297   //   - a member pointer
1298   //   - a block pointer
1299   CanQualType CanTo = Context.getCanonicalType(ToType);
1300   CanQualType CanFrom = Context.getCanonicalType(FromType);
1301   Type::TypeClass TyClass = CanTo->getTypeClass();
1302   if (TyClass != CanFrom->getTypeClass()) return false;
1303   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1304     if (TyClass == Type::Pointer) {
1305       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1306       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1307     } else if (TyClass == Type::BlockPointer) {
1308       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1309       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1310     } else if (TyClass == Type::MemberPointer) {
1311       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1312       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1313     } else {
1314       return false;
1315     }
1316 
1317     TyClass = CanTo->getTypeClass();
1318     if (TyClass != CanFrom->getTypeClass()) return false;
1319     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1320       return false;
1321   }
1322 
1323   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1324   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1325   if (!EInfo.getNoReturn()) return false;
1326 
1327   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1328   assert(QualType(FromFn, 0).isCanonical());
1329   if (QualType(FromFn, 0) != CanTo) return false;
1330 
1331   ResultTy = ToType;
1332   return true;
1333 }
1334 
1335 /// \brief Determine whether the conversion from FromType to ToType is a valid
1336 /// vector conversion.
1337 ///
1338 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1339 /// conversion.
1340 static bool IsVectorConversion(Sema &S, QualType FromType,
1341                                QualType ToType, ImplicitConversionKind &ICK) {
1342   // We need at least one of these types to be a vector type to have a vector
1343   // conversion.
1344   if (!ToType->isVectorType() && !FromType->isVectorType())
1345     return false;
1346 
1347   // Identical types require no conversions.
1348   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1349     return false;
1350 
1351   // There are no conversions between extended vector types, only identity.
1352   if (ToType->isExtVectorType()) {
1353     // There are no conversions between extended vector types other than the
1354     // identity conversion.
1355     if (FromType->isExtVectorType())
1356       return false;
1357 
1358     // Vector splat from any arithmetic type to a vector.
1359     if (FromType->isArithmeticType()) {
1360       ICK = ICK_Vector_Splat;
1361       return true;
1362     }
1363   }
1364 
1365   // We can perform the conversion between vector types in the following cases:
1366   // 1)vector types are equivalent AltiVec and GCC vector types
1367   // 2)lax vector conversions are permitted and the vector types are of the
1368   //   same size
1369   if (ToType->isVectorType() && FromType->isVectorType()) {
1370     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1371         S.isLaxVectorConversion(FromType, ToType)) {
1372       ICK = ICK_Vector_Conversion;
1373       return true;
1374     }
1375   }
1376 
1377   return false;
1378 }
1379 
1380 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1381                                 bool InOverloadResolution,
1382                                 StandardConversionSequence &SCS,
1383                                 bool CStyle);
1384 
1385 /// IsStandardConversion - Determines whether there is a standard
1386 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1387 /// expression From to the type ToType. Standard conversion sequences
1388 /// only consider non-class types; for conversions that involve class
1389 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1390 /// contain the standard conversion sequence required to perform this
1391 /// conversion and this routine will return true. Otherwise, this
1392 /// routine will return false and the value of SCS is unspecified.
1393 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1394                                  bool InOverloadResolution,
1395                                  StandardConversionSequence &SCS,
1396                                  bool CStyle,
1397                                  bool AllowObjCWritebackConversion) {
1398   QualType FromType = From->getType();
1399 
1400   // Standard conversions (C++ [conv])
1401   SCS.setAsIdentityConversion();
1402   SCS.IncompatibleObjC = false;
1403   SCS.setFromType(FromType);
1404   SCS.CopyConstructor = nullptr;
1405 
1406   // There are no standard conversions for class types in C++, so
1407   // abort early. When overloading in C, however, we do permit
1408   if (FromType->isRecordType() || ToType->isRecordType()) {
1409     if (S.getLangOpts().CPlusPlus)
1410       return false;
1411 
1412     // When we're overloading in C, we allow, as standard conversions,
1413   }
1414 
1415   // The first conversion can be an lvalue-to-rvalue conversion,
1416   // array-to-pointer conversion, or function-to-pointer conversion
1417   // (C++ 4p1).
1418 
1419   if (FromType == S.Context.OverloadTy) {
1420     DeclAccessPair AccessPair;
1421     if (FunctionDecl *Fn
1422           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1423                                                  AccessPair)) {
1424       // We were able to resolve the address of the overloaded function,
1425       // so we can convert to the type of that function.
1426       FromType = Fn->getType();
1427       SCS.setFromType(FromType);
1428 
1429       // we can sometimes resolve &foo<int> regardless of ToType, so check
1430       // if the type matches (identity) or we are converting to bool
1431       if (!S.Context.hasSameUnqualifiedType(
1432                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1433         QualType resultTy;
1434         // if the function type matches except for [[noreturn]], it's ok
1435         if (!S.IsNoReturnConversion(FromType,
1436               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1437           // otherwise, only a boolean conversion is standard
1438           if (!ToType->isBooleanType())
1439             return false;
1440       }
1441 
1442       // Check if the "from" expression is taking the address of an overloaded
1443       // function and recompute the FromType accordingly. Take advantage of the
1444       // fact that non-static member functions *must* have such an address-of
1445       // expression.
1446       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1447       if (Method && !Method->isStatic()) {
1448         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1449                "Non-unary operator on non-static member address");
1450         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1451                == UO_AddrOf &&
1452                "Non-address-of operator on non-static member address");
1453         const Type *ClassType
1454           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1455         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1456       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1457         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1458                UO_AddrOf &&
1459                "Non-address-of operator for overloaded function expression");
1460         FromType = S.Context.getPointerType(FromType);
1461       }
1462 
1463       // Check that we've computed the proper type after overload resolution.
1464       assert(S.Context.hasSameType(
1465         FromType,
1466         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1467     } else {
1468       return false;
1469     }
1470   }
1471   // Lvalue-to-rvalue conversion (C++11 4.1):
1472   //   A glvalue (3.10) of a non-function, non-array type T can
1473   //   be converted to a prvalue.
1474   bool argIsLValue = From->isGLValue();
1475   if (argIsLValue &&
1476       !FromType->isFunctionType() && !FromType->isArrayType() &&
1477       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1478     SCS.First = ICK_Lvalue_To_Rvalue;
1479 
1480     // C11 6.3.2.1p2:
1481     //   ... if the lvalue has atomic type, the value has the non-atomic version
1482     //   of the type of the lvalue ...
1483     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1484       FromType = Atomic->getValueType();
1485 
1486     // If T is a non-class type, the type of the rvalue is the
1487     // cv-unqualified version of T. Otherwise, the type of the rvalue
1488     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1489     // just strip the qualifiers because they don't matter.
1490     FromType = FromType.getUnqualifiedType();
1491   } else if (FromType->isArrayType()) {
1492     // Array-to-pointer conversion (C++ 4.2)
1493     SCS.First = ICK_Array_To_Pointer;
1494 
1495     // An lvalue or rvalue of type "array of N T" or "array of unknown
1496     // bound of T" can be converted to an rvalue of type "pointer to
1497     // T" (C++ 4.2p1).
1498     FromType = S.Context.getArrayDecayedType(FromType);
1499 
1500     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1501       // This conversion is deprecated in C++03 (D.4)
1502       SCS.DeprecatedStringLiteralToCharPtr = true;
1503 
1504       // For the purpose of ranking in overload resolution
1505       // (13.3.3.1.1), this conversion is considered an
1506       // array-to-pointer conversion followed by a qualification
1507       // conversion (4.4). (C++ 4.2p2)
1508       SCS.Second = ICK_Identity;
1509       SCS.Third = ICK_Qualification;
1510       SCS.QualificationIncludesObjCLifetime = false;
1511       SCS.setAllToTypes(FromType);
1512       return true;
1513     }
1514   } else if (FromType->isFunctionType() && argIsLValue) {
1515     // Function-to-pointer conversion (C++ 4.3).
1516     SCS.First = ICK_Function_To_Pointer;
1517 
1518     // An lvalue of function type T can be converted to an rvalue of
1519     // type "pointer to T." The result is a pointer to the
1520     // function. (C++ 4.3p1).
1521     FromType = S.Context.getPointerType(FromType);
1522   } else {
1523     // We don't require any conversions for the first step.
1524     SCS.First = ICK_Identity;
1525   }
1526   SCS.setToType(0, FromType);
1527 
1528   // The second conversion can be an integral promotion, floating
1529   // point promotion, integral conversion, floating point conversion,
1530   // floating-integral conversion, pointer conversion,
1531   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1532   // For overloading in C, this can also be a "compatible-type"
1533   // conversion.
1534   bool IncompatibleObjC = false;
1535   ImplicitConversionKind SecondICK = ICK_Identity;
1536   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1537     // The unqualified versions of the types are the same: there's no
1538     // conversion to do.
1539     SCS.Second = ICK_Identity;
1540   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1541     // Integral promotion (C++ 4.5).
1542     SCS.Second = ICK_Integral_Promotion;
1543     FromType = ToType.getUnqualifiedType();
1544   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1545     // Floating point promotion (C++ 4.6).
1546     SCS.Second = ICK_Floating_Promotion;
1547     FromType = ToType.getUnqualifiedType();
1548   } else if (S.IsComplexPromotion(FromType, ToType)) {
1549     // Complex promotion (Clang extension)
1550     SCS.Second = ICK_Complex_Promotion;
1551     FromType = ToType.getUnqualifiedType();
1552   } else if (ToType->isBooleanType() &&
1553              (FromType->isArithmeticType() ||
1554               FromType->isAnyPointerType() ||
1555               FromType->isBlockPointerType() ||
1556               FromType->isMemberPointerType() ||
1557               FromType->isNullPtrType())) {
1558     // Boolean conversions (C++ 4.12).
1559     SCS.Second = ICK_Boolean_Conversion;
1560     FromType = S.Context.BoolTy;
1561   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1562              ToType->isIntegralType(S.Context)) {
1563     // Integral conversions (C++ 4.7).
1564     SCS.Second = ICK_Integral_Conversion;
1565     FromType = ToType.getUnqualifiedType();
1566   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1567     // Complex conversions (C99 6.3.1.6)
1568     SCS.Second = ICK_Complex_Conversion;
1569     FromType = ToType.getUnqualifiedType();
1570   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1571              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1572     // Complex-real conversions (C99 6.3.1.7)
1573     SCS.Second = ICK_Complex_Real;
1574     FromType = ToType.getUnqualifiedType();
1575   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1576     // Floating point conversions (C++ 4.8).
1577     SCS.Second = ICK_Floating_Conversion;
1578     FromType = ToType.getUnqualifiedType();
1579   } else if ((FromType->isRealFloatingType() &&
1580               ToType->isIntegralType(S.Context)) ||
1581              (FromType->isIntegralOrUnscopedEnumerationType() &&
1582               ToType->isRealFloatingType())) {
1583     // Floating-integral conversions (C++ 4.9).
1584     SCS.Second = ICK_Floating_Integral;
1585     FromType = ToType.getUnqualifiedType();
1586   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1587     SCS.Second = ICK_Block_Pointer_Conversion;
1588   } else if (AllowObjCWritebackConversion &&
1589              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1590     SCS.Second = ICK_Writeback_Conversion;
1591   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1592                                    FromType, IncompatibleObjC)) {
1593     // Pointer conversions (C++ 4.10).
1594     SCS.Second = ICK_Pointer_Conversion;
1595     SCS.IncompatibleObjC = IncompatibleObjC;
1596     FromType = FromType.getUnqualifiedType();
1597   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1598                                          InOverloadResolution, FromType)) {
1599     // Pointer to member conversions (4.11).
1600     SCS.Second = ICK_Pointer_Member;
1601   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1602     SCS.Second = SecondICK;
1603     FromType = ToType.getUnqualifiedType();
1604   } else if (!S.getLangOpts().CPlusPlus &&
1605              S.Context.typesAreCompatible(ToType, FromType)) {
1606     // Compatible conversions (Clang extension for C function overloading)
1607     SCS.Second = ICK_Compatible_Conversion;
1608     FromType = ToType.getUnqualifiedType();
1609   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1610     // Treat a conversion that strips "noreturn" as an identity conversion.
1611     SCS.Second = ICK_NoReturn_Adjustment;
1612   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1613                                              InOverloadResolution,
1614                                              SCS, CStyle)) {
1615     SCS.Second = ICK_TransparentUnionConversion;
1616     FromType = ToType;
1617   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1618                                  CStyle)) {
1619     // tryAtomicConversion has updated the standard conversion sequence
1620     // appropriately.
1621     return true;
1622   } else if (ToType->isEventT() &&
1623              From->isIntegerConstantExpr(S.getASTContext()) &&
1624              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1625     SCS.Second = ICK_Zero_Event_Conversion;
1626     FromType = ToType;
1627   } else {
1628     // No second conversion required.
1629     SCS.Second = ICK_Identity;
1630   }
1631   SCS.setToType(1, FromType);
1632 
1633   QualType CanonFrom;
1634   QualType CanonTo;
1635   // The third conversion can be a qualification conversion (C++ 4p1).
1636   bool ObjCLifetimeConversion;
1637   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1638                                   ObjCLifetimeConversion)) {
1639     SCS.Third = ICK_Qualification;
1640     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1641     FromType = ToType;
1642     CanonFrom = S.Context.getCanonicalType(FromType);
1643     CanonTo = S.Context.getCanonicalType(ToType);
1644   } else {
1645     // No conversion required
1646     SCS.Third = ICK_Identity;
1647 
1648     // C++ [over.best.ics]p6:
1649     //   [...] Any difference in top-level cv-qualification is
1650     //   subsumed by the initialization itself and does not constitute
1651     //   a conversion. [...]
1652     CanonFrom = S.Context.getCanonicalType(FromType);
1653     CanonTo = S.Context.getCanonicalType(ToType);
1654     if (CanonFrom.getLocalUnqualifiedType()
1655                                        == CanonTo.getLocalUnqualifiedType() &&
1656         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1657       FromType = ToType;
1658       CanonFrom = CanonTo;
1659     }
1660   }
1661   SCS.setToType(2, FromType);
1662 
1663   // If we have not converted the argument type to the parameter type,
1664   // this is a bad conversion sequence.
1665   if (CanonFrom != CanonTo)
1666     return false;
1667 
1668   return true;
1669 }
1670 
1671 static bool
1672 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1673                                      QualType &ToType,
1674                                      bool InOverloadResolution,
1675                                      StandardConversionSequence &SCS,
1676                                      bool CStyle) {
1677 
1678   const RecordType *UT = ToType->getAsUnionType();
1679   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1680     return false;
1681   // The field to initialize within the transparent union.
1682   RecordDecl *UD = UT->getDecl();
1683   // It's compatible if the expression matches any of the fields.
1684   for (const auto *it : UD->fields()) {
1685     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1686                              CStyle, /*ObjCWritebackConversion=*/false)) {
1687       ToType = it->getType();
1688       return true;
1689     }
1690   }
1691   return false;
1692 }
1693 
1694 /// IsIntegralPromotion - Determines whether the conversion from the
1695 /// expression From (whose potentially-adjusted type is FromType) to
1696 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1697 /// sets PromotedType to the promoted type.
1698 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1699   const BuiltinType *To = ToType->getAs<BuiltinType>();
1700   // All integers are built-in.
1701   if (!To) {
1702     return false;
1703   }
1704 
1705   // An rvalue of type char, signed char, unsigned char, short int, or
1706   // unsigned short int can be converted to an rvalue of type int if
1707   // int can represent all the values of the source type; otherwise,
1708   // the source rvalue can be converted to an rvalue of type unsigned
1709   // int (C++ 4.5p1).
1710   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1711       !FromType->isEnumeralType()) {
1712     if (// We can promote any signed, promotable integer type to an int
1713         (FromType->isSignedIntegerType() ||
1714          // We can promote any unsigned integer type whose size is
1715          // less than int to an int.
1716          (!FromType->isSignedIntegerType() &&
1717           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1718       return To->getKind() == BuiltinType::Int;
1719     }
1720 
1721     return To->getKind() == BuiltinType::UInt;
1722   }
1723 
1724   // C++11 [conv.prom]p3:
1725   //   A prvalue of an unscoped enumeration type whose underlying type is not
1726   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1727   //   following types that can represent all the values of the enumeration
1728   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1729   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1730   //   long long int. If none of the types in that list can represent all the
1731   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1732   //   type can be converted to an rvalue a prvalue of the extended integer type
1733   //   with lowest integer conversion rank (4.13) greater than the rank of long
1734   //   long in which all the values of the enumeration can be represented. If
1735   //   there are two such extended types, the signed one is chosen.
1736   // C++11 [conv.prom]p4:
1737   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1738   //   can be converted to a prvalue of its underlying type. Moreover, if
1739   //   integral promotion can be applied to its underlying type, a prvalue of an
1740   //   unscoped enumeration type whose underlying type is fixed can also be
1741   //   converted to a prvalue of the promoted underlying type.
1742   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1743     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1744     // provided for a scoped enumeration.
1745     if (FromEnumType->getDecl()->isScoped())
1746       return false;
1747 
1748     // We can perform an integral promotion to the underlying type of the enum,
1749     // even if that's not the promoted type.
1750     if (FromEnumType->getDecl()->isFixed()) {
1751       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1752       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1753              IsIntegralPromotion(From, Underlying, ToType);
1754     }
1755 
1756     // We have already pre-calculated the promotion type, so this is trivial.
1757     if (ToType->isIntegerType() &&
1758         !RequireCompleteType(From->getLocStart(), FromType, 0))
1759       return Context.hasSameUnqualifiedType(ToType,
1760                                 FromEnumType->getDecl()->getPromotionType());
1761   }
1762 
1763   // C++0x [conv.prom]p2:
1764   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1765   //   to an rvalue a prvalue of the first of the following types that can
1766   //   represent all the values of its underlying type: int, unsigned int,
1767   //   long int, unsigned long int, long long int, or unsigned long long int.
1768   //   If none of the types in that list can represent all the values of its
1769   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1770   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1771   //   type.
1772   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1773       ToType->isIntegerType()) {
1774     // Determine whether the type we're converting from is signed or
1775     // unsigned.
1776     bool FromIsSigned = FromType->isSignedIntegerType();
1777     uint64_t FromSize = Context.getTypeSize(FromType);
1778 
1779     // The types we'll try to promote to, in the appropriate
1780     // order. Try each of these types.
1781     QualType PromoteTypes[6] = {
1782       Context.IntTy, Context.UnsignedIntTy,
1783       Context.LongTy, Context.UnsignedLongTy ,
1784       Context.LongLongTy, Context.UnsignedLongLongTy
1785     };
1786     for (int Idx = 0; Idx < 6; ++Idx) {
1787       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1788       if (FromSize < ToSize ||
1789           (FromSize == ToSize &&
1790            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1791         // We found the type that we can promote to. If this is the
1792         // type we wanted, we have a promotion. Otherwise, no
1793         // promotion.
1794         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1795       }
1796     }
1797   }
1798 
1799   // An rvalue for an integral bit-field (9.6) can be converted to an
1800   // rvalue of type int if int can represent all the values of the
1801   // bit-field; otherwise, it can be converted to unsigned int if
1802   // unsigned int can represent all the values of the bit-field. If
1803   // the bit-field is larger yet, no integral promotion applies to
1804   // it. If the bit-field has an enumerated type, it is treated as any
1805   // other value of that type for promotion purposes (C++ 4.5p3).
1806   // FIXME: We should delay checking of bit-fields until we actually perform the
1807   // conversion.
1808   using llvm::APSInt;
1809   if (From)
1810     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1811       APSInt BitWidth;
1812       if (FromType->isIntegralType(Context) &&
1813           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1814         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1815         ToSize = Context.getTypeSize(ToType);
1816 
1817         // Are we promoting to an int from a bitfield that fits in an int?
1818         if (BitWidth < ToSize ||
1819             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1820           return To->getKind() == BuiltinType::Int;
1821         }
1822 
1823         // Are we promoting to an unsigned int from an unsigned bitfield
1824         // that fits into an unsigned int?
1825         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1826           return To->getKind() == BuiltinType::UInt;
1827         }
1828 
1829         return false;
1830       }
1831     }
1832 
1833   // An rvalue of type bool can be converted to an rvalue of type int,
1834   // with false becoming zero and true becoming one (C++ 4.5p4).
1835   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1836     return true;
1837   }
1838 
1839   return false;
1840 }
1841 
1842 /// IsFloatingPointPromotion - Determines whether the conversion from
1843 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1844 /// returns true and sets PromotedType to the promoted type.
1845 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1846   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1847     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1848       /// An rvalue of type float can be converted to an rvalue of type
1849       /// double. (C++ 4.6p1).
1850       if (FromBuiltin->getKind() == BuiltinType::Float &&
1851           ToBuiltin->getKind() == BuiltinType::Double)
1852         return true;
1853 
1854       // C99 6.3.1.5p1:
1855       //   When a float is promoted to double or long double, or a
1856       //   double is promoted to long double [...].
1857       if (!getLangOpts().CPlusPlus &&
1858           (FromBuiltin->getKind() == BuiltinType::Float ||
1859            FromBuiltin->getKind() == BuiltinType::Double) &&
1860           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1861         return true;
1862 
1863       // Half can be promoted to float.
1864       if (!getLangOpts().NativeHalfType &&
1865            FromBuiltin->getKind() == BuiltinType::Half &&
1866           ToBuiltin->getKind() == BuiltinType::Float)
1867         return true;
1868     }
1869 
1870   return false;
1871 }
1872 
1873 /// \brief Determine if a conversion is a complex promotion.
1874 ///
1875 /// A complex promotion is defined as a complex -> complex conversion
1876 /// where the conversion between the underlying real types is a
1877 /// floating-point or integral promotion.
1878 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1879   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1880   if (!FromComplex)
1881     return false;
1882 
1883   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1884   if (!ToComplex)
1885     return false;
1886 
1887   return IsFloatingPointPromotion(FromComplex->getElementType(),
1888                                   ToComplex->getElementType()) ||
1889     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1890                         ToComplex->getElementType());
1891 }
1892 
1893 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1894 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1895 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1896 /// if non-empty, will be a pointer to ToType that may or may not have
1897 /// the right set of qualifiers on its pointee.
1898 ///
1899 static QualType
1900 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1901                                    QualType ToPointee, QualType ToType,
1902                                    ASTContext &Context,
1903                                    bool StripObjCLifetime = false) {
1904   assert((FromPtr->getTypeClass() == Type::Pointer ||
1905           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1906          "Invalid similarly-qualified pointer type");
1907 
1908   /// Conversions to 'id' subsume cv-qualifier conversions.
1909   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1910     return ToType.getUnqualifiedType();
1911 
1912   QualType CanonFromPointee
1913     = Context.getCanonicalType(FromPtr->getPointeeType());
1914   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1915   Qualifiers Quals = CanonFromPointee.getQualifiers();
1916 
1917   if (StripObjCLifetime)
1918     Quals.removeObjCLifetime();
1919 
1920   // Exact qualifier match -> return the pointer type we're converting to.
1921   if (CanonToPointee.getLocalQualifiers() == Quals) {
1922     // ToType is exactly what we need. Return it.
1923     if (!ToType.isNull())
1924       return ToType.getUnqualifiedType();
1925 
1926     // Build a pointer to ToPointee. It has the right qualifiers
1927     // already.
1928     if (isa<ObjCObjectPointerType>(ToType))
1929       return Context.getObjCObjectPointerType(ToPointee);
1930     return Context.getPointerType(ToPointee);
1931   }
1932 
1933   // Just build a canonical type that has the right qualifiers.
1934   QualType QualifiedCanonToPointee
1935     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1936 
1937   if (isa<ObjCObjectPointerType>(ToType))
1938     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1939   return Context.getPointerType(QualifiedCanonToPointee);
1940 }
1941 
1942 static bool isNullPointerConstantForConversion(Expr *Expr,
1943                                                bool InOverloadResolution,
1944                                                ASTContext &Context) {
1945   // Handle value-dependent integral null pointer constants correctly.
1946   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1947   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1948       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1949     return !InOverloadResolution;
1950 
1951   return Expr->isNullPointerConstant(Context,
1952                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1953                                         : Expr::NPC_ValueDependentIsNull);
1954 }
1955 
1956 /// IsPointerConversion - Determines whether the conversion of the
1957 /// expression From, which has the (possibly adjusted) type FromType,
1958 /// can be converted to the type ToType via a pointer conversion (C++
1959 /// 4.10). If so, returns true and places the converted type (that
1960 /// might differ from ToType in its cv-qualifiers at some level) into
1961 /// ConvertedType.
1962 ///
1963 /// This routine also supports conversions to and from block pointers
1964 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1965 /// pointers to interfaces. FIXME: Once we've determined the
1966 /// appropriate overloading rules for Objective-C, we may want to
1967 /// split the Objective-C checks into a different routine; however,
1968 /// GCC seems to consider all of these conversions to be pointer
1969 /// conversions, so for now they live here. IncompatibleObjC will be
1970 /// set if the conversion is an allowed Objective-C conversion that
1971 /// should result in a warning.
1972 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1973                                bool InOverloadResolution,
1974                                QualType& ConvertedType,
1975                                bool &IncompatibleObjC) {
1976   IncompatibleObjC = false;
1977   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1978                               IncompatibleObjC))
1979     return true;
1980 
1981   // Conversion from a null pointer constant to any Objective-C pointer type.
1982   if (ToType->isObjCObjectPointerType() &&
1983       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1984     ConvertedType = ToType;
1985     return true;
1986   }
1987 
1988   // Blocks: Block pointers can be converted to void*.
1989   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1990       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1991     ConvertedType = ToType;
1992     return true;
1993   }
1994   // Blocks: A null pointer constant can be converted to a block
1995   // pointer type.
1996   if (ToType->isBlockPointerType() &&
1997       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1998     ConvertedType = ToType;
1999     return true;
2000   }
2001 
2002   // If the left-hand-side is nullptr_t, the right side can be a null
2003   // pointer constant.
2004   if (ToType->isNullPtrType() &&
2005       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2006     ConvertedType = ToType;
2007     return true;
2008   }
2009 
2010   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2011   if (!ToTypePtr)
2012     return false;
2013 
2014   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2015   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2016     ConvertedType = ToType;
2017     return true;
2018   }
2019 
2020   // Beyond this point, both types need to be pointers
2021   // , including objective-c pointers.
2022   QualType ToPointeeType = ToTypePtr->getPointeeType();
2023   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2024       !getLangOpts().ObjCAutoRefCount) {
2025     ConvertedType = BuildSimilarlyQualifiedPointerType(
2026                                       FromType->getAs<ObjCObjectPointerType>(),
2027                                                        ToPointeeType,
2028                                                        ToType, Context);
2029     return true;
2030   }
2031   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2032   if (!FromTypePtr)
2033     return false;
2034 
2035   QualType FromPointeeType = FromTypePtr->getPointeeType();
2036 
2037   // If the unqualified pointee types are the same, this can't be a
2038   // pointer conversion, so don't do all of the work below.
2039   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2040     return false;
2041 
2042   // An rvalue of type "pointer to cv T," where T is an object type,
2043   // can be converted to an rvalue of type "pointer to cv void" (C++
2044   // 4.10p2).
2045   if (FromPointeeType->isIncompleteOrObjectType() &&
2046       ToPointeeType->isVoidType()) {
2047     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2048                                                        ToPointeeType,
2049                                                        ToType, Context,
2050                                                    /*StripObjCLifetime=*/true);
2051     return true;
2052   }
2053 
2054   // MSVC allows implicit function to void* type conversion.
2055   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2056       ToPointeeType->isVoidType()) {
2057     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2058                                                        ToPointeeType,
2059                                                        ToType, Context);
2060     return true;
2061   }
2062 
2063   // When we're overloading in C, we allow a special kind of pointer
2064   // conversion for compatible-but-not-identical pointee types.
2065   if (!getLangOpts().CPlusPlus &&
2066       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2067     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2068                                                        ToPointeeType,
2069                                                        ToType, Context);
2070     return true;
2071   }
2072 
2073   // C++ [conv.ptr]p3:
2074   //
2075   //   An rvalue of type "pointer to cv D," where D is a class type,
2076   //   can be converted to an rvalue of type "pointer to cv B," where
2077   //   B is a base class (clause 10) of D. If B is an inaccessible
2078   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2079   //   necessitates this conversion is ill-formed. The result of the
2080   //   conversion is a pointer to the base class sub-object of the
2081   //   derived class object. The null pointer value is converted to
2082   //   the null pointer value of the destination type.
2083   //
2084   // Note that we do not check for ambiguity or inaccessibility
2085   // here. That is handled by CheckPointerConversion.
2086   if (getLangOpts().CPlusPlus &&
2087       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2088       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2089       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2090       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2091     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2092                                                        ToPointeeType,
2093                                                        ToType, Context);
2094     return true;
2095   }
2096 
2097   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2098       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2099     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2100                                                        ToPointeeType,
2101                                                        ToType, Context);
2102     return true;
2103   }
2104 
2105   return false;
2106 }
2107 
2108 /// \brief Adopt the given qualifiers for the given type.
2109 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2110   Qualifiers TQs = T.getQualifiers();
2111 
2112   // Check whether qualifiers already match.
2113   if (TQs == Qs)
2114     return T;
2115 
2116   if (Qs.compatiblyIncludes(TQs))
2117     return Context.getQualifiedType(T, Qs);
2118 
2119   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2120 }
2121 
2122 /// isObjCPointerConversion - Determines whether this is an
2123 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2124 /// with the same arguments and return values.
2125 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2126                                    QualType& ConvertedType,
2127                                    bool &IncompatibleObjC) {
2128   if (!getLangOpts().ObjC1)
2129     return false;
2130 
2131   // The set of qualifiers on the type we're converting from.
2132   Qualifiers FromQualifiers = FromType.getQualifiers();
2133 
2134   // First, we handle all conversions on ObjC object pointer types.
2135   const ObjCObjectPointerType* ToObjCPtr =
2136     ToType->getAs<ObjCObjectPointerType>();
2137   const ObjCObjectPointerType *FromObjCPtr =
2138     FromType->getAs<ObjCObjectPointerType>();
2139 
2140   if (ToObjCPtr && FromObjCPtr) {
2141     // If the pointee types are the same (ignoring qualifications),
2142     // then this is not a pointer conversion.
2143     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2144                                        FromObjCPtr->getPointeeType()))
2145       return false;
2146 
2147     // Check for compatible
2148     // Objective C++: We're able to convert between "id" or "Class" and a
2149     // pointer to any interface (in both directions).
2150     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2151       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2152       return true;
2153     }
2154     // Conversions with Objective-C's id<...>.
2155     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2156          ToObjCPtr->isObjCQualifiedIdType()) &&
2157         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2158                                                   /*compare=*/false)) {
2159       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2160       return true;
2161     }
2162     // Objective C++: We're able to convert from a pointer to an
2163     // interface to a pointer to a different interface.
2164     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2165       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2166       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2167       if (getLangOpts().CPlusPlus && LHS && RHS &&
2168           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2169                                                 FromObjCPtr->getPointeeType()))
2170         return false;
2171       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2172                                                    ToObjCPtr->getPointeeType(),
2173                                                          ToType, Context);
2174       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2175       return true;
2176     }
2177 
2178     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2179       // Okay: this is some kind of implicit downcast of Objective-C
2180       // interfaces, which is permitted. However, we're going to
2181       // complain about it.
2182       IncompatibleObjC = true;
2183       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2184                                                    ToObjCPtr->getPointeeType(),
2185                                                          ToType, Context);
2186       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2187       return true;
2188     }
2189   }
2190   // Beyond this point, both types need to be C pointers or block pointers.
2191   QualType ToPointeeType;
2192   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2193     ToPointeeType = ToCPtr->getPointeeType();
2194   else if (const BlockPointerType *ToBlockPtr =
2195             ToType->getAs<BlockPointerType>()) {
2196     // Objective C++: We're able to convert from a pointer to any object
2197     // to a block pointer type.
2198     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2199       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2200       return true;
2201     }
2202     ToPointeeType = ToBlockPtr->getPointeeType();
2203   }
2204   else if (FromType->getAs<BlockPointerType>() &&
2205            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2206     // Objective C++: We're able to convert from a block pointer type to a
2207     // pointer to any object.
2208     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2209     return true;
2210   }
2211   else
2212     return false;
2213 
2214   QualType FromPointeeType;
2215   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2216     FromPointeeType = FromCPtr->getPointeeType();
2217   else if (const BlockPointerType *FromBlockPtr =
2218            FromType->getAs<BlockPointerType>())
2219     FromPointeeType = FromBlockPtr->getPointeeType();
2220   else
2221     return false;
2222 
2223   // If we have pointers to pointers, recursively check whether this
2224   // is an Objective-C conversion.
2225   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2226       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2227                               IncompatibleObjC)) {
2228     // We always complain about this conversion.
2229     IncompatibleObjC = true;
2230     ConvertedType = Context.getPointerType(ConvertedType);
2231     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2232     return true;
2233   }
2234   // Allow conversion of pointee being objective-c pointer to another one;
2235   // as in I* to id.
2236   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2237       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2238       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2239                               IncompatibleObjC)) {
2240 
2241     ConvertedType = Context.getPointerType(ConvertedType);
2242     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2243     return true;
2244   }
2245 
2246   // If we have pointers to functions or blocks, check whether the only
2247   // differences in the argument and result types are in Objective-C
2248   // pointer conversions. If so, we permit the conversion (but
2249   // complain about it).
2250   const FunctionProtoType *FromFunctionType
2251     = FromPointeeType->getAs<FunctionProtoType>();
2252   const FunctionProtoType *ToFunctionType
2253     = ToPointeeType->getAs<FunctionProtoType>();
2254   if (FromFunctionType && ToFunctionType) {
2255     // If the function types are exactly the same, this isn't an
2256     // Objective-C pointer conversion.
2257     if (Context.getCanonicalType(FromPointeeType)
2258           == Context.getCanonicalType(ToPointeeType))
2259       return false;
2260 
2261     // Perform the quick checks that will tell us whether these
2262     // function types are obviously different.
2263     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2264         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2265         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2266       return false;
2267 
2268     bool HasObjCConversion = false;
2269     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2270         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2271       // Okay, the types match exactly. Nothing to do.
2272     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2273                                        ToFunctionType->getReturnType(),
2274                                        ConvertedType, IncompatibleObjC)) {
2275       // Okay, we have an Objective-C pointer conversion.
2276       HasObjCConversion = true;
2277     } else {
2278       // Function types are too different. Abort.
2279       return false;
2280     }
2281 
2282     // Check argument types.
2283     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2284          ArgIdx != NumArgs; ++ArgIdx) {
2285       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2286       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2287       if (Context.getCanonicalType(FromArgType)
2288             == Context.getCanonicalType(ToArgType)) {
2289         // Okay, the types match exactly. Nothing to do.
2290       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2291                                          ConvertedType, IncompatibleObjC)) {
2292         // Okay, we have an Objective-C pointer conversion.
2293         HasObjCConversion = true;
2294       } else {
2295         // Argument types are too different. Abort.
2296         return false;
2297       }
2298     }
2299 
2300     if (HasObjCConversion) {
2301       // We had an Objective-C conversion. Allow this pointer
2302       // conversion, but complain about it.
2303       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2304       IncompatibleObjC = true;
2305       return true;
2306     }
2307   }
2308 
2309   return false;
2310 }
2311 
2312 /// \brief Determine whether this is an Objective-C writeback conversion,
2313 /// used for parameter passing when performing automatic reference counting.
2314 ///
2315 /// \param FromType The type we're converting form.
2316 ///
2317 /// \param ToType The type we're converting to.
2318 ///
2319 /// \param ConvertedType The type that will be produced after applying
2320 /// this conversion.
2321 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2322                                      QualType &ConvertedType) {
2323   if (!getLangOpts().ObjCAutoRefCount ||
2324       Context.hasSameUnqualifiedType(FromType, ToType))
2325     return false;
2326 
2327   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2328   QualType ToPointee;
2329   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2330     ToPointee = ToPointer->getPointeeType();
2331   else
2332     return false;
2333 
2334   Qualifiers ToQuals = ToPointee.getQualifiers();
2335   if (!ToPointee->isObjCLifetimeType() ||
2336       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2337       !ToQuals.withoutObjCLifetime().empty())
2338     return false;
2339 
2340   // Argument must be a pointer to __strong to __weak.
2341   QualType FromPointee;
2342   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2343     FromPointee = FromPointer->getPointeeType();
2344   else
2345     return false;
2346 
2347   Qualifiers FromQuals = FromPointee.getQualifiers();
2348   if (!FromPointee->isObjCLifetimeType() ||
2349       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2350        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2351     return false;
2352 
2353   // Make sure that we have compatible qualifiers.
2354   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2355   if (!ToQuals.compatiblyIncludes(FromQuals))
2356     return false;
2357 
2358   // Remove qualifiers from the pointee type we're converting from; they
2359   // aren't used in the compatibility check belong, and we'll be adding back
2360   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2361   FromPointee = FromPointee.getUnqualifiedType();
2362 
2363   // The unqualified form of the pointee types must be compatible.
2364   ToPointee = ToPointee.getUnqualifiedType();
2365   bool IncompatibleObjC;
2366   if (Context.typesAreCompatible(FromPointee, ToPointee))
2367     FromPointee = ToPointee;
2368   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2369                                     IncompatibleObjC))
2370     return false;
2371 
2372   /// \brief Construct the type we're converting to, which is a pointer to
2373   /// __autoreleasing pointee.
2374   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2375   ConvertedType = Context.getPointerType(FromPointee);
2376   return true;
2377 }
2378 
2379 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2380                                     QualType& ConvertedType) {
2381   QualType ToPointeeType;
2382   if (const BlockPointerType *ToBlockPtr =
2383         ToType->getAs<BlockPointerType>())
2384     ToPointeeType = ToBlockPtr->getPointeeType();
2385   else
2386     return false;
2387 
2388   QualType FromPointeeType;
2389   if (const BlockPointerType *FromBlockPtr =
2390       FromType->getAs<BlockPointerType>())
2391     FromPointeeType = FromBlockPtr->getPointeeType();
2392   else
2393     return false;
2394   // We have pointer to blocks, check whether the only
2395   // differences in the argument and result types are in Objective-C
2396   // pointer conversions. If so, we permit the conversion.
2397 
2398   const FunctionProtoType *FromFunctionType
2399     = FromPointeeType->getAs<FunctionProtoType>();
2400   const FunctionProtoType *ToFunctionType
2401     = ToPointeeType->getAs<FunctionProtoType>();
2402 
2403   if (!FromFunctionType || !ToFunctionType)
2404     return false;
2405 
2406   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2407     return true;
2408 
2409   // Perform the quick checks that will tell us whether these
2410   // function types are obviously different.
2411   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2412       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2413     return false;
2414 
2415   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2416   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2417   if (FromEInfo != ToEInfo)
2418     return false;
2419 
2420   bool IncompatibleObjC = false;
2421   if (Context.hasSameType(FromFunctionType->getReturnType(),
2422                           ToFunctionType->getReturnType())) {
2423     // Okay, the types match exactly. Nothing to do.
2424   } else {
2425     QualType RHS = FromFunctionType->getReturnType();
2426     QualType LHS = ToFunctionType->getReturnType();
2427     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2428         !RHS.hasQualifiers() && LHS.hasQualifiers())
2429        LHS = LHS.getUnqualifiedType();
2430 
2431      if (Context.hasSameType(RHS,LHS)) {
2432        // OK exact match.
2433      } else if (isObjCPointerConversion(RHS, LHS,
2434                                         ConvertedType, IncompatibleObjC)) {
2435      if (IncompatibleObjC)
2436        return false;
2437      // Okay, we have an Objective-C pointer conversion.
2438      }
2439      else
2440        return false;
2441    }
2442 
2443    // Check argument types.
2444    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2445         ArgIdx != NumArgs; ++ArgIdx) {
2446      IncompatibleObjC = false;
2447      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2448      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2449      if (Context.hasSameType(FromArgType, ToArgType)) {
2450        // Okay, the types match exactly. Nothing to do.
2451      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2452                                         ConvertedType, IncompatibleObjC)) {
2453        if (IncompatibleObjC)
2454          return false;
2455        // Okay, we have an Objective-C pointer conversion.
2456      } else
2457        // Argument types are too different. Abort.
2458        return false;
2459    }
2460    if (LangOpts.ObjCAutoRefCount &&
2461        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2462                                                     ToFunctionType))
2463      return false;
2464 
2465    ConvertedType = ToType;
2466    return true;
2467 }
2468 
2469 enum {
2470   ft_default,
2471   ft_different_class,
2472   ft_parameter_arity,
2473   ft_parameter_mismatch,
2474   ft_return_type,
2475   ft_qualifer_mismatch
2476 };
2477 
2478 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2479 /// function types.  Catches different number of parameter, mismatch in
2480 /// parameter types, and different return types.
2481 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2482                                       QualType FromType, QualType ToType) {
2483   // If either type is not valid, include no extra info.
2484   if (FromType.isNull() || ToType.isNull()) {
2485     PDiag << ft_default;
2486     return;
2487   }
2488 
2489   // Get the function type from the pointers.
2490   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2491     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2492                             *ToMember = ToType->getAs<MemberPointerType>();
2493     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2494       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2495             << QualType(FromMember->getClass(), 0);
2496       return;
2497     }
2498     FromType = FromMember->getPointeeType();
2499     ToType = ToMember->getPointeeType();
2500   }
2501 
2502   if (FromType->isPointerType())
2503     FromType = FromType->getPointeeType();
2504   if (ToType->isPointerType())
2505     ToType = ToType->getPointeeType();
2506 
2507   // Remove references.
2508   FromType = FromType.getNonReferenceType();
2509   ToType = ToType.getNonReferenceType();
2510 
2511   // Don't print extra info for non-specialized template functions.
2512   if (FromType->isInstantiationDependentType() &&
2513       !FromType->getAs<TemplateSpecializationType>()) {
2514     PDiag << ft_default;
2515     return;
2516   }
2517 
2518   // No extra info for same types.
2519   if (Context.hasSameType(FromType, ToType)) {
2520     PDiag << ft_default;
2521     return;
2522   }
2523 
2524   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2525                           *ToFunction = ToType->getAs<FunctionProtoType>();
2526 
2527   // Both types need to be function types.
2528   if (!FromFunction || !ToFunction) {
2529     PDiag << ft_default;
2530     return;
2531   }
2532 
2533   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2534     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2535           << FromFunction->getNumParams();
2536     return;
2537   }
2538 
2539   // Handle different parameter types.
2540   unsigned ArgPos;
2541   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2542     PDiag << ft_parameter_mismatch << ArgPos + 1
2543           << ToFunction->getParamType(ArgPos)
2544           << FromFunction->getParamType(ArgPos);
2545     return;
2546   }
2547 
2548   // Handle different return type.
2549   if (!Context.hasSameType(FromFunction->getReturnType(),
2550                            ToFunction->getReturnType())) {
2551     PDiag << ft_return_type << ToFunction->getReturnType()
2552           << FromFunction->getReturnType();
2553     return;
2554   }
2555 
2556   unsigned FromQuals = FromFunction->getTypeQuals(),
2557            ToQuals = ToFunction->getTypeQuals();
2558   if (FromQuals != ToQuals) {
2559     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2560     return;
2561   }
2562 
2563   // Unable to find a difference, so add no extra info.
2564   PDiag << ft_default;
2565 }
2566 
2567 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2568 /// for equality of their argument types. Caller has already checked that
2569 /// they have same number of arguments.  If the parameters are different,
2570 /// ArgPos will have the parameter index of the first different parameter.
2571 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2572                                       const FunctionProtoType *NewType,
2573                                       unsigned *ArgPos) {
2574   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2575                                               N = NewType->param_type_begin(),
2576                                               E = OldType->param_type_end();
2577        O && (O != E); ++O, ++N) {
2578     if (!Context.hasSameType(O->getUnqualifiedType(),
2579                              N->getUnqualifiedType())) {
2580       if (ArgPos)
2581         *ArgPos = O - OldType->param_type_begin();
2582       return false;
2583     }
2584   }
2585   return true;
2586 }
2587 
2588 /// CheckPointerConversion - Check the pointer conversion from the
2589 /// expression From to the type ToType. This routine checks for
2590 /// ambiguous or inaccessible derived-to-base pointer
2591 /// conversions for which IsPointerConversion has already returned
2592 /// true. It returns true and produces a diagnostic if there was an
2593 /// error, or returns false otherwise.
2594 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2595                                   CastKind &Kind,
2596                                   CXXCastPath& BasePath,
2597                                   bool IgnoreBaseAccess) {
2598   QualType FromType = From->getType();
2599   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2600 
2601   Kind = CK_BitCast;
2602 
2603   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2604       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2605       Expr::NPCK_ZeroExpression) {
2606     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2607       DiagRuntimeBehavior(From->getExprLoc(), From,
2608                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2609                             << ToType << From->getSourceRange());
2610     else if (!isUnevaluatedContext())
2611       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2612         << ToType << From->getSourceRange();
2613   }
2614   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2615     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2616       QualType FromPointeeType = FromPtrType->getPointeeType(),
2617                ToPointeeType   = ToPtrType->getPointeeType();
2618 
2619       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2620           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2621         // We must have a derived-to-base conversion. Check an
2622         // ambiguous or inaccessible conversion.
2623         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2624                                          From->getExprLoc(),
2625                                          From->getSourceRange(), &BasePath,
2626                                          IgnoreBaseAccess))
2627           return true;
2628 
2629         // The conversion was successful.
2630         Kind = CK_DerivedToBase;
2631       }
2632     }
2633   } else if (const ObjCObjectPointerType *ToPtrType =
2634                ToType->getAs<ObjCObjectPointerType>()) {
2635     if (const ObjCObjectPointerType *FromPtrType =
2636           FromType->getAs<ObjCObjectPointerType>()) {
2637       // Objective-C++ conversions are always okay.
2638       // FIXME: We should have a different class of conversions for the
2639       // Objective-C++ implicit conversions.
2640       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2641         return false;
2642     } else if (FromType->isBlockPointerType()) {
2643       Kind = CK_BlockPointerToObjCPointerCast;
2644     } else {
2645       Kind = CK_CPointerToObjCPointerCast;
2646     }
2647   } else if (ToType->isBlockPointerType()) {
2648     if (!FromType->isBlockPointerType())
2649       Kind = CK_AnyPointerToBlockPointerCast;
2650   }
2651 
2652   // We shouldn't fall into this case unless it's valid for other
2653   // reasons.
2654   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2655     Kind = CK_NullToPointer;
2656 
2657   return false;
2658 }
2659 
2660 /// IsMemberPointerConversion - Determines whether the conversion of the
2661 /// expression From, which has the (possibly adjusted) type FromType, can be
2662 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2663 /// If so, returns true and places the converted type (that might differ from
2664 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2665 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2666                                      QualType ToType,
2667                                      bool InOverloadResolution,
2668                                      QualType &ConvertedType) {
2669   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2670   if (!ToTypePtr)
2671     return false;
2672 
2673   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2674   if (From->isNullPointerConstant(Context,
2675                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2676                                         : Expr::NPC_ValueDependentIsNull)) {
2677     ConvertedType = ToType;
2678     return true;
2679   }
2680 
2681   // Otherwise, both types have to be member pointers.
2682   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2683   if (!FromTypePtr)
2684     return false;
2685 
2686   // A pointer to member of B can be converted to a pointer to member of D,
2687   // where D is derived from B (C++ 4.11p2).
2688   QualType FromClass(FromTypePtr->getClass(), 0);
2689   QualType ToClass(ToTypePtr->getClass(), 0);
2690 
2691   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2692       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2693       IsDerivedFrom(ToClass, FromClass)) {
2694     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2695                                                  ToClass.getTypePtr());
2696     return true;
2697   }
2698 
2699   return false;
2700 }
2701 
2702 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2703 /// expression From to the type ToType. This routine checks for ambiguous or
2704 /// virtual or inaccessible base-to-derived member pointer conversions
2705 /// for which IsMemberPointerConversion has already returned true. It returns
2706 /// true and produces a diagnostic if there was an error, or returns false
2707 /// otherwise.
2708 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2709                                         CastKind &Kind,
2710                                         CXXCastPath &BasePath,
2711                                         bool IgnoreBaseAccess) {
2712   QualType FromType = From->getType();
2713   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2714   if (!FromPtrType) {
2715     // This must be a null pointer to member pointer conversion
2716     assert(From->isNullPointerConstant(Context,
2717                                        Expr::NPC_ValueDependentIsNull) &&
2718            "Expr must be null pointer constant!");
2719     Kind = CK_NullToMemberPointer;
2720     return false;
2721   }
2722 
2723   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2724   assert(ToPtrType && "No member pointer cast has a target type "
2725                       "that is not a member pointer.");
2726 
2727   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2728   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2729 
2730   // FIXME: What about dependent types?
2731   assert(FromClass->isRecordType() && "Pointer into non-class.");
2732   assert(ToClass->isRecordType() && "Pointer into non-class.");
2733 
2734   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2735                      /*DetectVirtual=*/true);
2736   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2737   assert(DerivationOkay &&
2738          "Should not have been called if derivation isn't OK.");
2739   (void)DerivationOkay;
2740 
2741   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2742                                   getUnqualifiedType())) {
2743     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2744     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2745       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2746     return true;
2747   }
2748 
2749   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2750     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2751       << FromClass << ToClass << QualType(VBase, 0)
2752       << From->getSourceRange();
2753     return true;
2754   }
2755 
2756   if (!IgnoreBaseAccess)
2757     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2758                          Paths.front(),
2759                          diag::err_downcast_from_inaccessible_base);
2760 
2761   // Must be a base to derived member conversion.
2762   BuildBasePathArray(Paths, BasePath);
2763   Kind = CK_BaseToDerivedMemberPointer;
2764   return false;
2765 }
2766 
2767 /// Determine whether the lifetime conversion between the two given
2768 /// qualifiers sets is nontrivial.
2769 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2770                                                Qualifiers ToQuals) {
2771   // Converting anything to const __unsafe_unretained is trivial.
2772   if (ToQuals.hasConst() &&
2773       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2774     return false;
2775 
2776   return true;
2777 }
2778 
2779 /// IsQualificationConversion - Determines whether the conversion from
2780 /// an rvalue of type FromType to ToType is a qualification conversion
2781 /// (C++ 4.4).
2782 ///
2783 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2784 /// when the qualification conversion involves a change in the Objective-C
2785 /// object lifetime.
2786 bool
2787 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2788                                 bool CStyle, bool &ObjCLifetimeConversion) {
2789   FromType = Context.getCanonicalType(FromType);
2790   ToType = Context.getCanonicalType(ToType);
2791   ObjCLifetimeConversion = false;
2792 
2793   // If FromType and ToType are the same type, this is not a
2794   // qualification conversion.
2795   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2796     return false;
2797 
2798   // (C++ 4.4p4):
2799   //   A conversion can add cv-qualifiers at levels other than the first
2800   //   in multi-level pointers, subject to the following rules: [...]
2801   bool PreviousToQualsIncludeConst = true;
2802   bool UnwrappedAnyPointer = false;
2803   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2804     // Within each iteration of the loop, we check the qualifiers to
2805     // determine if this still looks like a qualification
2806     // conversion. Then, if all is well, we unwrap one more level of
2807     // pointers or pointers-to-members and do it all again
2808     // until there are no more pointers or pointers-to-members left to
2809     // unwrap.
2810     UnwrappedAnyPointer = true;
2811 
2812     Qualifiers FromQuals = FromType.getQualifiers();
2813     Qualifiers ToQuals = ToType.getQualifiers();
2814 
2815     // Objective-C ARC:
2816     //   Check Objective-C lifetime conversions.
2817     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2818         UnwrappedAnyPointer) {
2819       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2820         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2821           ObjCLifetimeConversion = true;
2822         FromQuals.removeObjCLifetime();
2823         ToQuals.removeObjCLifetime();
2824       } else {
2825         // Qualification conversions cannot cast between different
2826         // Objective-C lifetime qualifiers.
2827         return false;
2828       }
2829     }
2830 
2831     // Allow addition/removal of GC attributes but not changing GC attributes.
2832     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2833         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2834       FromQuals.removeObjCGCAttr();
2835       ToQuals.removeObjCGCAttr();
2836     }
2837 
2838     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2839     //      2,j, and similarly for volatile.
2840     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2841       return false;
2842 
2843     //   -- if the cv 1,j and cv 2,j are different, then const is in
2844     //      every cv for 0 < k < j.
2845     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2846         && !PreviousToQualsIncludeConst)
2847       return false;
2848 
2849     // Keep track of whether all prior cv-qualifiers in the "to" type
2850     // include const.
2851     PreviousToQualsIncludeConst
2852       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2853   }
2854 
2855   // We are left with FromType and ToType being the pointee types
2856   // after unwrapping the original FromType and ToType the same number
2857   // of types. If we unwrapped any pointers, and if FromType and
2858   // ToType have the same unqualified type (since we checked
2859   // qualifiers above), then this is a qualification conversion.
2860   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2861 }
2862 
2863 /// \brief - Determine whether this is a conversion from a scalar type to an
2864 /// atomic type.
2865 ///
2866 /// If successful, updates \c SCS's second and third steps in the conversion
2867 /// sequence to finish the conversion.
2868 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2869                                 bool InOverloadResolution,
2870                                 StandardConversionSequence &SCS,
2871                                 bool CStyle) {
2872   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2873   if (!ToAtomic)
2874     return false;
2875 
2876   StandardConversionSequence InnerSCS;
2877   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2878                             InOverloadResolution, InnerSCS,
2879                             CStyle, /*AllowObjCWritebackConversion=*/false))
2880     return false;
2881 
2882   SCS.Second = InnerSCS.Second;
2883   SCS.setToType(1, InnerSCS.getToType(1));
2884   SCS.Third = InnerSCS.Third;
2885   SCS.QualificationIncludesObjCLifetime
2886     = InnerSCS.QualificationIncludesObjCLifetime;
2887   SCS.setToType(2, InnerSCS.getToType(2));
2888   return true;
2889 }
2890 
2891 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2892                                               CXXConstructorDecl *Constructor,
2893                                               QualType Type) {
2894   const FunctionProtoType *CtorType =
2895       Constructor->getType()->getAs<FunctionProtoType>();
2896   if (CtorType->getNumParams() > 0) {
2897     QualType FirstArg = CtorType->getParamType(0);
2898     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2899       return true;
2900   }
2901   return false;
2902 }
2903 
2904 static OverloadingResult
2905 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2906                                        CXXRecordDecl *To,
2907                                        UserDefinedConversionSequence &User,
2908                                        OverloadCandidateSet &CandidateSet,
2909                                        bool AllowExplicit) {
2910   DeclContext::lookup_result R = S.LookupConstructors(To);
2911   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2912        Con != ConEnd; ++Con) {
2913     NamedDecl *D = *Con;
2914     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2915 
2916     // Find the constructor (which may be a template).
2917     CXXConstructorDecl *Constructor = nullptr;
2918     FunctionTemplateDecl *ConstructorTmpl
2919       = dyn_cast<FunctionTemplateDecl>(D);
2920     if (ConstructorTmpl)
2921       Constructor
2922         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2923     else
2924       Constructor = cast<CXXConstructorDecl>(D);
2925 
2926     bool Usable = !Constructor->isInvalidDecl() &&
2927                   S.isInitListConstructor(Constructor) &&
2928                   (AllowExplicit || !Constructor->isExplicit());
2929     if (Usable) {
2930       // If the first argument is (a reference to) the target type,
2931       // suppress conversions.
2932       bool SuppressUserConversions =
2933           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2934       if (ConstructorTmpl)
2935         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2936                                        /*ExplicitArgs*/ nullptr,
2937                                        From, CandidateSet,
2938                                        SuppressUserConversions);
2939       else
2940         S.AddOverloadCandidate(Constructor, FoundDecl,
2941                                From, CandidateSet,
2942                                SuppressUserConversions);
2943     }
2944   }
2945 
2946   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2947 
2948   OverloadCandidateSet::iterator Best;
2949   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2950   case OR_Success: {
2951     // Record the standard conversion we used and the conversion function.
2952     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2953     QualType ThisType = Constructor->getThisType(S.Context);
2954     // Initializer lists don't have conversions as such.
2955     User.Before.setAsIdentityConversion();
2956     User.HadMultipleCandidates = HadMultipleCandidates;
2957     User.ConversionFunction = Constructor;
2958     User.FoundConversionFunction = Best->FoundDecl;
2959     User.After.setAsIdentityConversion();
2960     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2961     User.After.setAllToTypes(ToType);
2962     return OR_Success;
2963   }
2964 
2965   case OR_No_Viable_Function:
2966     return OR_No_Viable_Function;
2967   case OR_Deleted:
2968     return OR_Deleted;
2969   case OR_Ambiguous:
2970     return OR_Ambiguous;
2971   }
2972 
2973   llvm_unreachable("Invalid OverloadResult!");
2974 }
2975 
2976 /// Determines whether there is a user-defined conversion sequence
2977 /// (C++ [over.ics.user]) that converts expression From to the type
2978 /// ToType. If such a conversion exists, User will contain the
2979 /// user-defined conversion sequence that performs such a conversion
2980 /// and this routine will return true. Otherwise, this routine returns
2981 /// false and User is unspecified.
2982 ///
2983 /// \param AllowExplicit  true if the conversion should consider C++0x
2984 /// "explicit" conversion functions as well as non-explicit conversion
2985 /// functions (C++0x [class.conv.fct]p2).
2986 ///
2987 /// \param AllowObjCConversionOnExplicit true if the conversion should
2988 /// allow an extra Objective-C pointer conversion on uses of explicit
2989 /// constructors. Requires \c AllowExplicit to also be set.
2990 static OverloadingResult
2991 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2992                         UserDefinedConversionSequence &User,
2993                         OverloadCandidateSet &CandidateSet,
2994                         bool AllowExplicit,
2995                         bool AllowObjCConversionOnExplicit) {
2996   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
2997 
2998   // Whether we will only visit constructors.
2999   bool ConstructorsOnly = false;
3000 
3001   // If the type we are conversion to is a class type, enumerate its
3002   // constructors.
3003   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3004     // C++ [over.match.ctor]p1:
3005     //   When objects of class type are direct-initialized (8.5), or
3006     //   copy-initialized from an expression of the same or a
3007     //   derived class type (8.5), overload resolution selects the
3008     //   constructor. [...] For copy-initialization, the candidate
3009     //   functions are all the converting constructors (12.3.1) of
3010     //   that class. The argument list is the expression-list within
3011     //   the parentheses of the initializer.
3012     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3013         (From->getType()->getAs<RecordType>() &&
3014          S.IsDerivedFrom(From->getType(), ToType)))
3015       ConstructorsOnly = true;
3016 
3017     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3018     // RequireCompleteType may have returned true due to some invalid decl
3019     // during template instantiation, but ToType may be complete enough now
3020     // to try to recover.
3021     if (ToType->isIncompleteType()) {
3022       // We're not going to find any constructors.
3023     } else if (CXXRecordDecl *ToRecordDecl
3024                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3025 
3026       Expr **Args = &From;
3027       unsigned NumArgs = 1;
3028       bool ListInitializing = false;
3029       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3030         // But first, see if there is an init-list-constructor that will work.
3031         OverloadingResult Result = IsInitializerListConstructorConversion(
3032             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3033         if (Result != OR_No_Viable_Function)
3034           return Result;
3035         // Never mind.
3036         CandidateSet.clear();
3037 
3038         // If we're list-initializing, we pass the individual elements as
3039         // arguments, not the entire list.
3040         Args = InitList->getInits();
3041         NumArgs = InitList->getNumInits();
3042         ListInitializing = true;
3043       }
3044 
3045       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3046       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3047            Con != ConEnd; ++Con) {
3048         NamedDecl *D = *Con;
3049         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3050 
3051         // Find the constructor (which may be a template).
3052         CXXConstructorDecl *Constructor = nullptr;
3053         FunctionTemplateDecl *ConstructorTmpl
3054           = dyn_cast<FunctionTemplateDecl>(D);
3055         if (ConstructorTmpl)
3056           Constructor
3057             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3058         else
3059           Constructor = cast<CXXConstructorDecl>(D);
3060 
3061         bool Usable = !Constructor->isInvalidDecl();
3062         if (ListInitializing)
3063           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3064         else
3065           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3066         if (Usable) {
3067           bool SuppressUserConversions = !ConstructorsOnly;
3068           if (SuppressUserConversions && ListInitializing) {
3069             SuppressUserConversions = false;
3070             if (NumArgs == 1) {
3071               // If the first argument is (a reference to) the target type,
3072               // suppress conversions.
3073               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3074                                                 S.Context, Constructor, ToType);
3075             }
3076           }
3077           if (ConstructorTmpl)
3078             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3079                                            /*ExplicitArgs*/ nullptr,
3080                                            llvm::makeArrayRef(Args, NumArgs),
3081                                            CandidateSet, SuppressUserConversions);
3082           else
3083             // Allow one user-defined conversion when user specifies a
3084             // From->ToType conversion via an static cast (c-style, etc).
3085             S.AddOverloadCandidate(Constructor, FoundDecl,
3086                                    llvm::makeArrayRef(Args, NumArgs),
3087                                    CandidateSet, SuppressUserConversions);
3088         }
3089       }
3090     }
3091   }
3092 
3093   // Enumerate conversion functions, if we're allowed to.
3094   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3095   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3096     // No conversion functions from incomplete types.
3097   } else if (const RecordType *FromRecordType
3098                                    = From->getType()->getAs<RecordType>()) {
3099     if (CXXRecordDecl *FromRecordDecl
3100          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3101       // Add all of the conversion functions as candidates.
3102       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3103       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3104         DeclAccessPair FoundDecl = I.getPair();
3105         NamedDecl *D = FoundDecl.getDecl();
3106         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3107         if (isa<UsingShadowDecl>(D))
3108           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3109 
3110         CXXConversionDecl *Conv;
3111         FunctionTemplateDecl *ConvTemplate;
3112         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3113           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3114         else
3115           Conv = cast<CXXConversionDecl>(D);
3116 
3117         if (AllowExplicit || !Conv->isExplicit()) {
3118           if (ConvTemplate)
3119             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3120                                              ActingContext, From, ToType,
3121                                              CandidateSet,
3122                                              AllowObjCConversionOnExplicit);
3123           else
3124             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3125                                      From, ToType, CandidateSet,
3126                                      AllowObjCConversionOnExplicit);
3127         }
3128       }
3129     }
3130   }
3131 
3132   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3133 
3134   OverloadCandidateSet::iterator Best;
3135   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3136                                                         Best, true)) {
3137   case OR_Success:
3138   case OR_Deleted:
3139     // Record the standard conversion we used and the conversion function.
3140     if (CXXConstructorDecl *Constructor
3141           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3142       // C++ [over.ics.user]p1:
3143       //   If the user-defined conversion is specified by a
3144       //   constructor (12.3.1), the initial standard conversion
3145       //   sequence converts the source type to the type required by
3146       //   the argument of the constructor.
3147       //
3148       QualType ThisType = Constructor->getThisType(S.Context);
3149       if (isa<InitListExpr>(From)) {
3150         // Initializer lists don't have conversions as such.
3151         User.Before.setAsIdentityConversion();
3152       } else {
3153         if (Best->Conversions[0].isEllipsis())
3154           User.EllipsisConversion = true;
3155         else {
3156           User.Before = Best->Conversions[0].Standard;
3157           User.EllipsisConversion = false;
3158         }
3159       }
3160       User.HadMultipleCandidates = HadMultipleCandidates;
3161       User.ConversionFunction = Constructor;
3162       User.FoundConversionFunction = Best->FoundDecl;
3163       User.After.setAsIdentityConversion();
3164       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3165       User.After.setAllToTypes(ToType);
3166       return Result;
3167     }
3168     if (CXXConversionDecl *Conversion
3169                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3170       // C++ [over.ics.user]p1:
3171       //
3172       //   [...] If the user-defined conversion is specified by a
3173       //   conversion function (12.3.2), the initial standard
3174       //   conversion sequence converts the source type to the
3175       //   implicit object parameter of the conversion function.
3176       User.Before = Best->Conversions[0].Standard;
3177       User.HadMultipleCandidates = HadMultipleCandidates;
3178       User.ConversionFunction = Conversion;
3179       User.FoundConversionFunction = Best->FoundDecl;
3180       User.EllipsisConversion = false;
3181 
3182       // C++ [over.ics.user]p2:
3183       //   The second standard conversion sequence converts the
3184       //   result of the user-defined conversion to the target type
3185       //   for the sequence. Since an implicit conversion sequence
3186       //   is an initialization, the special rules for
3187       //   initialization by user-defined conversion apply when
3188       //   selecting the best user-defined conversion for a
3189       //   user-defined conversion sequence (see 13.3.3 and
3190       //   13.3.3.1).
3191       User.After = Best->FinalConversion;
3192       return Result;
3193     }
3194     llvm_unreachable("Not a constructor or conversion function?");
3195 
3196   case OR_No_Viable_Function:
3197     return OR_No_Viable_Function;
3198 
3199   case OR_Ambiguous:
3200     return OR_Ambiguous;
3201   }
3202 
3203   llvm_unreachable("Invalid OverloadResult!");
3204 }
3205 
3206 bool
3207 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3208   ImplicitConversionSequence ICS;
3209   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3210                                     OverloadCandidateSet::CSK_Normal);
3211   OverloadingResult OvResult =
3212     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3213                             CandidateSet, false, false);
3214   if (OvResult == OR_Ambiguous)
3215     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3216         << From->getType() << ToType << From->getSourceRange();
3217   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3218     if (!RequireCompleteType(From->getLocStart(), ToType,
3219                              diag::err_typecheck_nonviable_condition_incomplete,
3220                              From->getType(), From->getSourceRange()))
3221       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3222           << From->getType() << From->getSourceRange() << ToType;
3223   } else
3224     return false;
3225   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3226   return true;
3227 }
3228 
3229 /// \brief Compare the user-defined conversion functions or constructors
3230 /// of two user-defined conversion sequences to determine whether any ordering
3231 /// is possible.
3232 static ImplicitConversionSequence::CompareKind
3233 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3234                            FunctionDecl *Function2) {
3235   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3236     return ImplicitConversionSequence::Indistinguishable;
3237 
3238   // Objective-C++:
3239   //   If both conversion functions are implicitly-declared conversions from
3240   //   a lambda closure type to a function pointer and a block pointer,
3241   //   respectively, always prefer the conversion to a function pointer,
3242   //   because the function pointer is more lightweight and is more likely
3243   //   to keep code working.
3244   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3245   if (!Conv1)
3246     return ImplicitConversionSequence::Indistinguishable;
3247 
3248   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3249   if (!Conv2)
3250     return ImplicitConversionSequence::Indistinguishable;
3251 
3252   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3253     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3254     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3255     if (Block1 != Block2)
3256       return Block1 ? ImplicitConversionSequence::Worse
3257                     : ImplicitConversionSequence::Better;
3258   }
3259 
3260   return ImplicitConversionSequence::Indistinguishable;
3261 }
3262 
3263 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3264     const ImplicitConversionSequence &ICS) {
3265   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3266          (ICS.isUserDefined() &&
3267           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3268 }
3269 
3270 /// CompareImplicitConversionSequences - Compare two implicit
3271 /// conversion sequences to determine whether one is better than the
3272 /// other or if they are indistinguishable (C++ 13.3.3.2).
3273 static ImplicitConversionSequence::CompareKind
3274 CompareImplicitConversionSequences(Sema &S,
3275                                    const ImplicitConversionSequence& ICS1,
3276                                    const ImplicitConversionSequence& ICS2)
3277 {
3278   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3279   // conversion sequences (as defined in 13.3.3.1)
3280   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3281   //      conversion sequence than a user-defined conversion sequence or
3282   //      an ellipsis conversion sequence, and
3283   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3284   //      conversion sequence than an ellipsis conversion sequence
3285   //      (13.3.3.1.3).
3286   //
3287   // C++0x [over.best.ics]p10:
3288   //   For the purpose of ranking implicit conversion sequences as
3289   //   described in 13.3.3.2, the ambiguous conversion sequence is
3290   //   treated as a user-defined sequence that is indistinguishable
3291   //   from any other user-defined conversion sequence.
3292 
3293   // String literal to 'char *' conversion has been deprecated in C++03. It has
3294   // been removed from C++11. We still accept this conversion, if it happens at
3295   // the best viable function. Otherwise, this conversion is considered worse
3296   // than ellipsis conversion. Consider this as an extension; this is not in the
3297   // standard. For example:
3298   //
3299   // int &f(...);    // #1
3300   // void f(char*);  // #2
3301   // void g() { int &r = f("foo"); }
3302   //
3303   // In C++03, we pick #2 as the best viable function.
3304   // In C++11, we pick #1 as the best viable function, because ellipsis
3305   // conversion is better than string-literal to char* conversion (since there
3306   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3307   // convert arguments, #2 would be the best viable function in C++11.
3308   // If the best viable function has this conversion, a warning will be issued
3309   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3310 
3311   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3312       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3313       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3314     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3315                ? ImplicitConversionSequence::Worse
3316                : ImplicitConversionSequence::Better;
3317 
3318   if (ICS1.getKindRank() < ICS2.getKindRank())
3319     return ImplicitConversionSequence::Better;
3320   if (ICS2.getKindRank() < ICS1.getKindRank())
3321     return ImplicitConversionSequence::Worse;
3322 
3323   // The following checks require both conversion sequences to be of
3324   // the same kind.
3325   if (ICS1.getKind() != ICS2.getKind())
3326     return ImplicitConversionSequence::Indistinguishable;
3327 
3328   ImplicitConversionSequence::CompareKind Result =
3329       ImplicitConversionSequence::Indistinguishable;
3330 
3331   // Two implicit conversion sequences of the same form are
3332   // indistinguishable conversion sequences unless one of the
3333   // following rules apply: (C++ 13.3.3.2p3):
3334 
3335   // List-initialization sequence L1 is a better conversion sequence than
3336   // list-initialization sequence L2 if:
3337   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3338   //   if not that,
3339   // - L1 converts to type “array of N1 T”, L2 converts to type “array of N2 T”,
3340   //   and N1 is smaller than N2.,
3341   // even if one of the other rules in this paragraph would otherwise apply.
3342   if (!ICS1.isBad()) {
3343     if (ICS1.isStdInitializerListElement() &&
3344         !ICS2.isStdInitializerListElement())
3345       return ImplicitConversionSequence::Better;
3346     if (!ICS1.isStdInitializerListElement() &&
3347         ICS2.isStdInitializerListElement())
3348       return ImplicitConversionSequence::Worse;
3349   }
3350 
3351   if (ICS1.isStandard())
3352     // Standard conversion sequence S1 is a better conversion sequence than
3353     // standard conversion sequence S2 if [...]
3354     Result = CompareStandardConversionSequences(S,
3355                                                 ICS1.Standard, ICS2.Standard);
3356   else if (ICS1.isUserDefined()) {
3357     // User-defined conversion sequence U1 is a better conversion
3358     // sequence than another user-defined conversion sequence U2 if
3359     // they contain the same user-defined conversion function or
3360     // constructor and if the second standard conversion sequence of
3361     // U1 is better than the second standard conversion sequence of
3362     // U2 (C++ 13.3.3.2p3).
3363     if (ICS1.UserDefined.ConversionFunction ==
3364           ICS2.UserDefined.ConversionFunction)
3365       Result = CompareStandardConversionSequences(S,
3366                                                   ICS1.UserDefined.After,
3367                                                   ICS2.UserDefined.After);
3368     else
3369       Result = compareConversionFunctions(S,
3370                                           ICS1.UserDefined.ConversionFunction,
3371                                           ICS2.UserDefined.ConversionFunction);
3372   }
3373 
3374   return Result;
3375 }
3376 
3377 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3378   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3379     Qualifiers Quals;
3380     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3381     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3382   }
3383 
3384   return Context.hasSameUnqualifiedType(T1, T2);
3385 }
3386 
3387 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3388 // determine if one is a proper subset of the other.
3389 static ImplicitConversionSequence::CompareKind
3390 compareStandardConversionSubsets(ASTContext &Context,
3391                                  const StandardConversionSequence& SCS1,
3392                                  const StandardConversionSequence& SCS2) {
3393   ImplicitConversionSequence::CompareKind Result
3394     = ImplicitConversionSequence::Indistinguishable;
3395 
3396   // the identity conversion sequence is considered to be a subsequence of
3397   // any non-identity conversion sequence
3398   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3399     return ImplicitConversionSequence::Better;
3400   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3401     return ImplicitConversionSequence::Worse;
3402 
3403   if (SCS1.Second != SCS2.Second) {
3404     if (SCS1.Second == ICK_Identity)
3405       Result = ImplicitConversionSequence::Better;
3406     else if (SCS2.Second == ICK_Identity)
3407       Result = ImplicitConversionSequence::Worse;
3408     else
3409       return ImplicitConversionSequence::Indistinguishable;
3410   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3411     return ImplicitConversionSequence::Indistinguishable;
3412 
3413   if (SCS1.Third == SCS2.Third) {
3414     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3415                              : ImplicitConversionSequence::Indistinguishable;
3416   }
3417 
3418   if (SCS1.Third == ICK_Identity)
3419     return Result == ImplicitConversionSequence::Worse
3420              ? ImplicitConversionSequence::Indistinguishable
3421              : ImplicitConversionSequence::Better;
3422 
3423   if (SCS2.Third == ICK_Identity)
3424     return Result == ImplicitConversionSequence::Better
3425              ? ImplicitConversionSequence::Indistinguishable
3426              : ImplicitConversionSequence::Worse;
3427 
3428   return ImplicitConversionSequence::Indistinguishable;
3429 }
3430 
3431 /// \brief Determine whether one of the given reference bindings is better
3432 /// than the other based on what kind of bindings they are.
3433 static bool
3434 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3435                              const StandardConversionSequence &SCS2) {
3436   // C++0x [over.ics.rank]p3b4:
3437   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3438   //      implicit object parameter of a non-static member function declared
3439   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3440   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3441   //      lvalue reference to a function lvalue and S2 binds an rvalue
3442   //      reference*.
3443   //
3444   // FIXME: Rvalue references. We're going rogue with the above edits,
3445   // because the semantics in the current C++0x working paper (N3225 at the
3446   // time of this writing) break the standard definition of std::forward
3447   // and std::reference_wrapper when dealing with references to functions.
3448   // Proposed wording changes submitted to CWG for consideration.
3449   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3450       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3451     return false;
3452 
3453   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3454           SCS2.IsLvalueReference) ||
3455          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3456           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3457 }
3458 
3459 /// CompareStandardConversionSequences - Compare two standard
3460 /// conversion sequences to determine whether one is better than the
3461 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3462 static ImplicitConversionSequence::CompareKind
3463 CompareStandardConversionSequences(Sema &S,
3464                                    const StandardConversionSequence& SCS1,
3465                                    const StandardConversionSequence& SCS2)
3466 {
3467   // Standard conversion sequence S1 is a better conversion sequence
3468   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3469 
3470   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3471   //     sequences in the canonical form defined by 13.3.3.1.1,
3472   //     excluding any Lvalue Transformation; the identity conversion
3473   //     sequence is considered to be a subsequence of any
3474   //     non-identity conversion sequence) or, if not that,
3475   if (ImplicitConversionSequence::CompareKind CK
3476         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3477     return CK;
3478 
3479   //  -- the rank of S1 is better than the rank of S2 (by the rules
3480   //     defined below), or, if not that,
3481   ImplicitConversionRank Rank1 = SCS1.getRank();
3482   ImplicitConversionRank Rank2 = SCS2.getRank();
3483   if (Rank1 < Rank2)
3484     return ImplicitConversionSequence::Better;
3485   else if (Rank2 < Rank1)
3486     return ImplicitConversionSequence::Worse;
3487 
3488   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3489   // are indistinguishable unless one of the following rules
3490   // applies:
3491 
3492   //   A conversion that is not a conversion of a pointer, or
3493   //   pointer to member, to bool is better than another conversion
3494   //   that is such a conversion.
3495   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3496     return SCS2.isPointerConversionToBool()
3497              ? ImplicitConversionSequence::Better
3498              : ImplicitConversionSequence::Worse;
3499 
3500   // C++ [over.ics.rank]p4b2:
3501   //
3502   //   If class B is derived directly or indirectly from class A,
3503   //   conversion of B* to A* is better than conversion of B* to
3504   //   void*, and conversion of A* to void* is better than conversion
3505   //   of B* to void*.
3506   bool SCS1ConvertsToVoid
3507     = SCS1.isPointerConversionToVoidPointer(S.Context);
3508   bool SCS2ConvertsToVoid
3509     = SCS2.isPointerConversionToVoidPointer(S.Context);
3510   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3511     // Exactly one of the conversion sequences is a conversion to
3512     // a void pointer; it's the worse conversion.
3513     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3514                               : ImplicitConversionSequence::Worse;
3515   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3516     // Neither conversion sequence converts to a void pointer; compare
3517     // their derived-to-base conversions.
3518     if (ImplicitConversionSequence::CompareKind DerivedCK
3519           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3520       return DerivedCK;
3521   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3522              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3523     // Both conversion sequences are conversions to void
3524     // pointers. Compare the source types to determine if there's an
3525     // inheritance relationship in their sources.
3526     QualType FromType1 = SCS1.getFromType();
3527     QualType FromType2 = SCS2.getFromType();
3528 
3529     // Adjust the types we're converting from via the array-to-pointer
3530     // conversion, if we need to.
3531     if (SCS1.First == ICK_Array_To_Pointer)
3532       FromType1 = S.Context.getArrayDecayedType(FromType1);
3533     if (SCS2.First == ICK_Array_To_Pointer)
3534       FromType2 = S.Context.getArrayDecayedType(FromType2);
3535 
3536     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3537     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3538 
3539     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3540       return ImplicitConversionSequence::Better;
3541     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3542       return ImplicitConversionSequence::Worse;
3543 
3544     // Objective-C++: If one interface is more specific than the
3545     // other, it is the better one.
3546     const ObjCObjectPointerType* FromObjCPtr1
3547       = FromType1->getAs<ObjCObjectPointerType>();
3548     const ObjCObjectPointerType* FromObjCPtr2
3549       = FromType2->getAs<ObjCObjectPointerType>();
3550     if (FromObjCPtr1 && FromObjCPtr2) {
3551       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3552                                                           FromObjCPtr2);
3553       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3554                                                            FromObjCPtr1);
3555       if (AssignLeft != AssignRight) {
3556         return AssignLeft? ImplicitConversionSequence::Better
3557                          : ImplicitConversionSequence::Worse;
3558       }
3559     }
3560   }
3561 
3562   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3563   // bullet 3).
3564   if (ImplicitConversionSequence::CompareKind QualCK
3565         = CompareQualificationConversions(S, SCS1, SCS2))
3566     return QualCK;
3567 
3568   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3569     // Check for a better reference binding based on the kind of bindings.
3570     if (isBetterReferenceBindingKind(SCS1, SCS2))
3571       return ImplicitConversionSequence::Better;
3572     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3573       return ImplicitConversionSequence::Worse;
3574 
3575     // C++ [over.ics.rank]p3b4:
3576     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3577     //      which the references refer are the same type except for
3578     //      top-level cv-qualifiers, and the type to which the reference
3579     //      initialized by S2 refers is more cv-qualified than the type
3580     //      to which the reference initialized by S1 refers.
3581     QualType T1 = SCS1.getToType(2);
3582     QualType T2 = SCS2.getToType(2);
3583     T1 = S.Context.getCanonicalType(T1);
3584     T2 = S.Context.getCanonicalType(T2);
3585     Qualifiers T1Quals, T2Quals;
3586     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3587     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3588     if (UnqualT1 == UnqualT2) {
3589       // Objective-C++ ARC: If the references refer to objects with different
3590       // lifetimes, prefer bindings that don't change lifetime.
3591       if (SCS1.ObjCLifetimeConversionBinding !=
3592                                           SCS2.ObjCLifetimeConversionBinding) {
3593         return SCS1.ObjCLifetimeConversionBinding
3594                                            ? ImplicitConversionSequence::Worse
3595                                            : ImplicitConversionSequence::Better;
3596       }
3597 
3598       // If the type is an array type, promote the element qualifiers to the
3599       // type for comparison.
3600       if (isa<ArrayType>(T1) && T1Quals)
3601         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3602       if (isa<ArrayType>(T2) && T2Quals)
3603         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3604       if (T2.isMoreQualifiedThan(T1))
3605         return ImplicitConversionSequence::Better;
3606       else if (T1.isMoreQualifiedThan(T2))
3607         return ImplicitConversionSequence::Worse;
3608     }
3609   }
3610 
3611   // In Microsoft mode, prefer an integral conversion to a
3612   // floating-to-integral conversion if the integral conversion
3613   // is between types of the same size.
3614   // For example:
3615   // void f(float);
3616   // void f(int);
3617   // int main {
3618   //    long a;
3619   //    f(a);
3620   // }
3621   // Here, MSVC will call f(int) instead of generating a compile error
3622   // as clang will do in standard mode.
3623   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3624       SCS2.Second == ICK_Floating_Integral &&
3625       S.Context.getTypeSize(SCS1.getFromType()) ==
3626           S.Context.getTypeSize(SCS1.getToType(2)))
3627     return ImplicitConversionSequence::Better;
3628 
3629   return ImplicitConversionSequence::Indistinguishable;
3630 }
3631 
3632 /// CompareQualificationConversions - Compares two standard conversion
3633 /// sequences to determine whether they can be ranked based on their
3634 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3635 static ImplicitConversionSequence::CompareKind
3636 CompareQualificationConversions(Sema &S,
3637                                 const StandardConversionSequence& SCS1,
3638                                 const StandardConversionSequence& SCS2) {
3639   // C++ 13.3.3.2p3:
3640   //  -- S1 and S2 differ only in their qualification conversion and
3641   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3642   //     cv-qualification signature of type T1 is a proper subset of
3643   //     the cv-qualification signature of type T2, and S1 is not the
3644   //     deprecated string literal array-to-pointer conversion (4.2).
3645   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3646       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3647     return ImplicitConversionSequence::Indistinguishable;
3648 
3649   // FIXME: the example in the standard doesn't use a qualification
3650   // conversion (!)
3651   QualType T1 = SCS1.getToType(2);
3652   QualType T2 = SCS2.getToType(2);
3653   T1 = S.Context.getCanonicalType(T1);
3654   T2 = S.Context.getCanonicalType(T2);
3655   Qualifiers T1Quals, T2Quals;
3656   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3657   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3658 
3659   // If the types are the same, we won't learn anything by unwrapped
3660   // them.
3661   if (UnqualT1 == UnqualT2)
3662     return ImplicitConversionSequence::Indistinguishable;
3663 
3664   // If the type is an array type, promote the element qualifiers to the type
3665   // for comparison.
3666   if (isa<ArrayType>(T1) && T1Quals)
3667     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3668   if (isa<ArrayType>(T2) && T2Quals)
3669     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3670 
3671   ImplicitConversionSequence::CompareKind Result
3672     = ImplicitConversionSequence::Indistinguishable;
3673 
3674   // Objective-C++ ARC:
3675   //   Prefer qualification conversions not involving a change in lifetime
3676   //   to qualification conversions that do not change lifetime.
3677   if (SCS1.QualificationIncludesObjCLifetime !=
3678                                       SCS2.QualificationIncludesObjCLifetime) {
3679     Result = SCS1.QualificationIncludesObjCLifetime
3680                ? ImplicitConversionSequence::Worse
3681                : ImplicitConversionSequence::Better;
3682   }
3683 
3684   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3685     // Within each iteration of the loop, we check the qualifiers to
3686     // determine if this still looks like a qualification
3687     // conversion. Then, if all is well, we unwrap one more level of
3688     // pointers or pointers-to-members and do it all again
3689     // until there are no more pointers or pointers-to-members left
3690     // to unwrap. This essentially mimics what
3691     // IsQualificationConversion does, but here we're checking for a
3692     // strict subset of qualifiers.
3693     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3694       // The qualifiers are the same, so this doesn't tell us anything
3695       // about how the sequences rank.
3696       ;
3697     else if (T2.isMoreQualifiedThan(T1)) {
3698       // T1 has fewer qualifiers, so it could be the better sequence.
3699       if (Result == ImplicitConversionSequence::Worse)
3700         // Neither has qualifiers that are a subset of the other's
3701         // qualifiers.
3702         return ImplicitConversionSequence::Indistinguishable;
3703 
3704       Result = ImplicitConversionSequence::Better;
3705     } else if (T1.isMoreQualifiedThan(T2)) {
3706       // T2 has fewer qualifiers, so it could be the better sequence.
3707       if (Result == ImplicitConversionSequence::Better)
3708         // Neither has qualifiers that are a subset of the other's
3709         // qualifiers.
3710         return ImplicitConversionSequence::Indistinguishable;
3711 
3712       Result = ImplicitConversionSequence::Worse;
3713     } else {
3714       // Qualifiers are disjoint.
3715       return ImplicitConversionSequence::Indistinguishable;
3716     }
3717 
3718     // If the types after this point are equivalent, we're done.
3719     if (S.Context.hasSameUnqualifiedType(T1, T2))
3720       break;
3721   }
3722 
3723   // Check that the winning standard conversion sequence isn't using
3724   // the deprecated string literal array to pointer conversion.
3725   switch (Result) {
3726   case ImplicitConversionSequence::Better:
3727     if (SCS1.DeprecatedStringLiteralToCharPtr)
3728       Result = ImplicitConversionSequence::Indistinguishable;
3729     break;
3730 
3731   case ImplicitConversionSequence::Indistinguishable:
3732     break;
3733 
3734   case ImplicitConversionSequence::Worse:
3735     if (SCS2.DeprecatedStringLiteralToCharPtr)
3736       Result = ImplicitConversionSequence::Indistinguishable;
3737     break;
3738   }
3739 
3740   return Result;
3741 }
3742 
3743 /// CompareDerivedToBaseConversions - Compares two standard conversion
3744 /// sequences to determine whether they can be ranked based on their
3745 /// various kinds of derived-to-base conversions (C++
3746 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3747 /// conversions between Objective-C interface types.
3748 static ImplicitConversionSequence::CompareKind
3749 CompareDerivedToBaseConversions(Sema &S,
3750                                 const StandardConversionSequence& SCS1,
3751                                 const StandardConversionSequence& SCS2) {
3752   QualType FromType1 = SCS1.getFromType();
3753   QualType ToType1 = SCS1.getToType(1);
3754   QualType FromType2 = SCS2.getFromType();
3755   QualType ToType2 = SCS2.getToType(1);
3756 
3757   // Adjust the types we're converting from via the array-to-pointer
3758   // conversion, if we need to.
3759   if (SCS1.First == ICK_Array_To_Pointer)
3760     FromType1 = S.Context.getArrayDecayedType(FromType1);
3761   if (SCS2.First == ICK_Array_To_Pointer)
3762     FromType2 = S.Context.getArrayDecayedType(FromType2);
3763 
3764   // Canonicalize all of the types.
3765   FromType1 = S.Context.getCanonicalType(FromType1);
3766   ToType1 = S.Context.getCanonicalType(ToType1);
3767   FromType2 = S.Context.getCanonicalType(FromType2);
3768   ToType2 = S.Context.getCanonicalType(ToType2);
3769 
3770   // C++ [over.ics.rank]p4b3:
3771   //
3772   //   If class B is derived directly or indirectly from class A and
3773   //   class C is derived directly or indirectly from B,
3774   //
3775   // Compare based on pointer conversions.
3776   if (SCS1.Second == ICK_Pointer_Conversion &&
3777       SCS2.Second == ICK_Pointer_Conversion &&
3778       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3779       FromType1->isPointerType() && FromType2->isPointerType() &&
3780       ToType1->isPointerType() && ToType2->isPointerType()) {
3781     QualType FromPointee1
3782       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3783     QualType ToPointee1
3784       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3785     QualType FromPointee2
3786       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3787     QualType ToPointee2
3788       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3789 
3790     //   -- conversion of C* to B* is better than conversion of C* to A*,
3791     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3792       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3793         return ImplicitConversionSequence::Better;
3794       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3795         return ImplicitConversionSequence::Worse;
3796     }
3797 
3798     //   -- conversion of B* to A* is better than conversion of C* to A*,
3799     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3800       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3801         return ImplicitConversionSequence::Better;
3802       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3803         return ImplicitConversionSequence::Worse;
3804     }
3805   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3806              SCS2.Second == ICK_Pointer_Conversion) {
3807     const ObjCObjectPointerType *FromPtr1
3808       = FromType1->getAs<ObjCObjectPointerType>();
3809     const ObjCObjectPointerType *FromPtr2
3810       = FromType2->getAs<ObjCObjectPointerType>();
3811     const ObjCObjectPointerType *ToPtr1
3812       = ToType1->getAs<ObjCObjectPointerType>();
3813     const ObjCObjectPointerType *ToPtr2
3814       = ToType2->getAs<ObjCObjectPointerType>();
3815 
3816     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3817       // Apply the same conversion ranking rules for Objective-C pointer types
3818       // that we do for C++ pointers to class types. However, we employ the
3819       // Objective-C pseudo-subtyping relationship used for assignment of
3820       // Objective-C pointer types.
3821       bool FromAssignLeft
3822         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3823       bool FromAssignRight
3824         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3825       bool ToAssignLeft
3826         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3827       bool ToAssignRight
3828         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3829 
3830       // A conversion to an a non-id object pointer type or qualified 'id'
3831       // type is better than a conversion to 'id'.
3832       if (ToPtr1->isObjCIdType() &&
3833           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3834         return ImplicitConversionSequence::Worse;
3835       if (ToPtr2->isObjCIdType() &&
3836           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3837         return ImplicitConversionSequence::Better;
3838 
3839       // A conversion to a non-id object pointer type is better than a
3840       // conversion to a qualified 'id' type
3841       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3842         return ImplicitConversionSequence::Worse;
3843       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3844         return ImplicitConversionSequence::Better;
3845 
3846       // A conversion to an a non-Class object pointer type or qualified 'Class'
3847       // type is better than a conversion to 'Class'.
3848       if (ToPtr1->isObjCClassType() &&
3849           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3850         return ImplicitConversionSequence::Worse;
3851       if (ToPtr2->isObjCClassType() &&
3852           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3853         return ImplicitConversionSequence::Better;
3854 
3855       // A conversion to a non-Class object pointer type is better than a
3856       // conversion to a qualified 'Class' type.
3857       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3858         return ImplicitConversionSequence::Worse;
3859       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3860         return ImplicitConversionSequence::Better;
3861 
3862       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3863       if (S.Context.hasSameType(FromType1, FromType2) &&
3864           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3865           (ToAssignLeft != ToAssignRight))
3866         return ToAssignLeft? ImplicitConversionSequence::Worse
3867                            : ImplicitConversionSequence::Better;
3868 
3869       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3870       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3871           (FromAssignLeft != FromAssignRight))
3872         return FromAssignLeft? ImplicitConversionSequence::Better
3873         : ImplicitConversionSequence::Worse;
3874     }
3875   }
3876 
3877   // Ranking of member-pointer types.
3878   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3879       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3880       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3881     const MemberPointerType * FromMemPointer1 =
3882                                         FromType1->getAs<MemberPointerType>();
3883     const MemberPointerType * ToMemPointer1 =
3884                                           ToType1->getAs<MemberPointerType>();
3885     const MemberPointerType * FromMemPointer2 =
3886                                           FromType2->getAs<MemberPointerType>();
3887     const MemberPointerType * ToMemPointer2 =
3888                                           ToType2->getAs<MemberPointerType>();
3889     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3890     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3891     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3892     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3893     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3894     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3895     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3896     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3897     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3898     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3899       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3900         return ImplicitConversionSequence::Worse;
3901       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3902         return ImplicitConversionSequence::Better;
3903     }
3904     // conversion of B::* to C::* is better than conversion of A::* to C::*
3905     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3906       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3907         return ImplicitConversionSequence::Better;
3908       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3909         return ImplicitConversionSequence::Worse;
3910     }
3911   }
3912 
3913   if (SCS1.Second == ICK_Derived_To_Base) {
3914     //   -- conversion of C to B is better than conversion of C to A,
3915     //   -- binding of an expression of type C to a reference of type
3916     //      B& is better than binding an expression of type C to a
3917     //      reference of type A&,
3918     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3919         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3920       if (S.IsDerivedFrom(ToType1, ToType2))
3921         return ImplicitConversionSequence::Better;
3922       else if (S.IsDerivedFrom(ToType2, ToType1))
3923         return ImplicitConversionSequence::Worse;
3924     }
3925 
3926     //   -- conversion of B to A is better than conversion of C to A.
3927     //   -- binding of an expression of type B to a reference of type
3928     //      A& is better than binding an expression of type C to a
3929     //      reference of type A&,
3930     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3931         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3932       if (S.IsDerivedFrom(FromType2, FromType1))
3933         return ImplicitConversionSequence::Better;
3934       else if (S.IsDerivedFrom(FromType1, FromType2))
3935         return ImplicitConversionSequence::Worse;
3936     }
3937   }
3938 
3939   return ImplicitConversionSequence::Indistinguishable;
3940 }
3941 
3942 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3943 /// C++ class.
3944 static bool isTypeValid(QualType T) {
3945   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3946     return !Record->isInvalidDecl();
3947 
3948   return true;
3949 }
3950 
3951 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3952 /// determine whether they are reference-related,
3953 /// reference-compatible, reference-compatible with added
3954 /// qualification, or incompatible, for use in C++ initialization by
3955 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3956 /// type, and the first type (T1) is the pointee type of the reference
3957 /// type being initialized.
3958 Sema::ReferenceCompareResult
3959 Sema::CompareReferenceRelationship(SourceLocation Loc,
3960                                    QualType OrigT1, QualType OrigT2,
3961                                    bool &DerivedToBase,
3962                                    bool &ObjCConversion,
3963                                    bool &ObjCLifetimeConversion) {
3964   assert(!OrigT1->isReferenceType() &&
3965     "T1 must be the pointee type of the reference type");
3966   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3967 
3968   QualType T1 = Context.getCanonicalType(OrigT1);
3969   QualType T2 = Context.getCanonicalType(OrigT2);
3970   Qualifiers T1Quals, T2Quals;
3971   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3972   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3973 
3974   // C++ [dcl.init.ref]p4:
3975   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3976   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3977   //   T1 is a base class of T2.
3978   DerivedToBase = false;
3979   ObjCConversion = false;
3980   ObjCLifetimeConversion = false;
3981   if (UnqualT1 == UnqualT2) {
3982     // Nothing to do.
3983   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3984              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3985              IsDerivedFrom(UnqualT2, UnqualT1))
3986     DerivedToBase = true;
3987   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3988            UnqualT2->isObjCObjectOrInterfaceType() &&
3989            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3990     ObjCConversion = true;
3991   else
3992     return Ref_Incompatible;
3993 
3994   // At this point, we know that T1 and T2 are reference-related (at
3995   // least).
3996 
3997   // If the type is an array type, promote the element qualifiers to the type
3998   // for comparison.
3999   if (isa<ArrayType>(T1) && T1Quals)
4000     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4001   if (isa<ArrayType>(T2) && T2Quals)
4002     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4003 
4004   // C++ [dcl.init.ref]p4:
4005   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4006   //   reference-related to T2 and cv1 is the same cv-qualification
4007   //   as, or greater cv-qualification than, cv2. For purposes of
4008   //   overload resolution, cases for which cv1 is greater
4009   //   cv-qualification than cv2 are identified as
4010   //   reference-compatible with added qualification (see 13.3.3.2).
4011   //
4012   // Note that we also require equivalence of Objective-C GC and address-space
4013   // qualifiers when performing these computations, so that e.g., an int in
4014   // address space 1 is not reference-compatible with an int in address
4015   // space 2.
4016   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4017       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4018     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4019       ObjCLifetimeConversion = true;
4020 
4021     T1Quals.removeObjCLifetime();
4022     T2Quals.removeObjCLifetime();
4023   }
4024 
4025   if (T1Quals == T2Quals)
4026     return Ref_Compatible;
4027   else if (T1Quals.compatiblyIncludes(T2Quals))
4028     return Ref_Compatible_With_Added_Qualification;
4029   else
4030     return Ref_Related;
4031 }
4032 
4033 /// \brief Look for a user-defined conversion to an value reference-compatible
4034 ///        with DeclType. Return true if something definite is found.
4035 static bool
4036 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4037                          QualType DeclType, SourceLocation DeclLoc,
4038                          Expr *Init, QualType T2, bool AllowRvalues,
4039                          bool AllowExplicit) {
4040   assert(T2->isRecordType() && "Can only find conversions of record types.");
4041   CXXRecordDecl *T2RecordDecl
4042     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4043 
4044   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4045   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4046   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4047     NamedDecl *D = *I;
4048     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4049     if (isa<UsingShadowDecl>(D))
4050       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4051 
4052     FunctionTemplateDecl *ConvTemplate
4053       = dyn_cast<FunctionTemplateDecl>(D);
4054     CXXConversionDecl *Conv;
4055     if (ConvTemplate)
4056       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4057     else
4058       Conv = cast<CXXConversionDecl>(D);
4059 
4060     // If this is an explicit conversion, and we're not allowed to consider
4061     // explicit conversions, skip it.
4062     if (!AllowExplicit && Conv->isExplicit())
4063       continue;
4064 
4065     if (AllowRvalues) {
4066       bool DerivedToBase = false;
4067       bool ObjCConversion = false;
4068       bool ObjCLifetimeConversion = false;
4069 
4070       // If we are initializing an rvalue reference, don't permit conversion
4071       // functions that return lvalues.
4072       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4073         const ReferenceType *RefType
4074           = Conv->getConversionType()->getAs<LValueReferenceType>();
4075         if (RefType && !RefType->getPointeeType()->isFunctionType())
4076           continue;
4077       }
4078 
4079       if (!ConvTemplate &&
4080           S.CompareReferenceRelationship(
4081             DeclLoc,
4082             Conv->getConversionType().getNonReferenceType()
4083               .getUnqualifiedType(),
4084             DeclType.getNonReferenceType().getUnqualifiedType(),
4085             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4086           Sema::Ref_Incompatible)
4087         continue;
4088     } else {
4089       // If the conversion function doesn't return a reference type,
4090       // it can't be considered for this conversion. An rvalue reference
4091       // is only acceptable if its referencee is a function type.
4092 
4093       const ReferenceType *RefType =
4094         Conv->getConversionType()->getAs<ReferenceType>();
4095       if (!RefType ||
4096           (!RefType->isLValueReferenceType() &&
4097            !RefType->getPointeeType()->isFunctionType()))
4098         continue;
4099     }
4100 
4101     if (ConvTemplate)
4102       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4103                                        Init, DeclType, CandidateSet,
4104                                        /*AllowObjCConversionOnExplicit=*/false);
4105     else
4106       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4107                                DeclType, CandidateSet,
4108                                /*AllowObjCConversionOnExplicit=*/false);
4109   }
4110 
4111   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4112 
4113   OverloadCandidateSet::iterator Best;
4114   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4115   case OR_Success:
4116     // C++ [over.ics.ref]p1:
4117     //
4118     //   [...] If the parameter binds directly to the result of
4119     //   applying a conversion function to the argument
4120     //   expression, the implicit conversion sequence is a
4121     //   user-defined conversion sequence (13.3.3.1.2), with the
4122     //   second standard conversion sequence either an identity
4123     //   conversion or, if the conversion function returns an
4124     //   entity of a type that is a derived class of the parameter
4125     //   type, a derived-to-base Conversion.
4126     if (!Best->FinalConversion.DirectBinding)
4127       return false;
4128 
4129     ICS.setUserDefined();
4130     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4131     ICS.UserDefined.After = Best->FinalConversion;
4132     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4133     ICS.UserDefined.ConversionFunction = Best->Function;
4134     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4135     ICS.UserDefined.EllipsisConversion = false;
4136     assert(ICS.UserDefined.After.ReferenceBinding &&
4137            ICS.UserDefined.After.DirectBinding &&
4138            "Expected a direct reference binding!");
4139     return true;
4140 
4141   case OR_Ambiguous:
4142     ICS.setAmbiguous();
4143     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4144          Cand != CandidateSet.end(); ++Cand)
4145       if (Cand->Viable)
4146         ICS.Ambiguous.addConversion(Cand->Function);
4147     return true;
4148 
4149   case OR_No_Viable_Function:
4150   case OR_Deleted:
4151     // There was no suitable conversion, or we found a deleted
4152     // conversion; continue with other checks.
4153     return false;
4154   }
4155 
4156   llvm_unreachable("Invalid OverloadResult!");
4157 }
4158 
4159 /// \brief Compute an implicit conversion sequence for reference
4160 /// initialization.
4161 static ImplicitConversionSequence
4162 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4163                  SourceLocation DeclLoc,
4164                  bool SuppressUserConversions,
4165                  bool AllowExplicit) {
4166   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4167 
4168   // Most paths end in a failed conversion.
4169   ImplicitConversionSequence ICS;
4170   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4171 
4172   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4173   QualType T2 = Init->getType();
4174 
4175   // If the initializer is the address of an overloaded function, try
4176   // to resolve the overloaded function. If all goes well, T2 is the
4177   // type of the resulting function.
4178   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4179     DeclAccessPair Found;
4180     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4181                                                                 false, Found))
4182       T2 = Fn->getType();
4183   }
4184 
4185   // Compute some basic properties of the types and the initializer.
4186   bool isRValRef = DeclType->isRValueReferenceType();
4187   bool DerivedToBase = false;
4188   bool ObjCConversion = false;
4189   bool ObjCLifetimeConversion = false;
4190   Expr::Classification InitCategory = Init->Classify(S.Context);
4191   Sema::ReferenceCompareResult RefRelationship
4192     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4193                                      ObjCConversion, ObjCLifetimeConversion);
4194 
4195 
4196   // C++0x [dcl.init.ref]p5:
4197   //   A reference to type "cv1 T1" is initialized by an expression
4198   //   of type "cv2 T2" as follows:
4199 
4200   //     -- If reference is an lvalue reference and the initializer expression
4201   if (!isRValRef) {
4202     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4203     //        reference-compatible with "cv2 T2," or
4204     //
4205     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4206     if (InitCategory.isLValue() &&
4207         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4208       // C++ [over.ics.ref]p1:
4209       //   When a parameter of reference type binds directly (8.5.3)
4210       //   to an argument expression, the implicit conversion sequence
4211       //   is the identity conversion, unless the argument expression
4212       //   has a type that is a derived class of the parameter type,
4213       //   in which case the implicit conversion sequence is a
4214       //   derived-to-base Conversion (13.3.3.1).
4215       ICS.setStandard();
4216       ICS.Standard.First = ICK_Identity;
4217       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4218                          : ObjCConversion? ICK_Compatible_Conversion
4219                          : ICK_Identity;
4220       ICS.Standard.Third = ICK_Identity;
4221       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4222       ICS.Standard.setToType(0, T2);
4223       ICS.Standard.setToType(1, T1);
4224       ICS.Standard.setToType(2, T1);
4225       ICS.Standard.ReferenceBinding = true;
4226       ICS.Standard.DirectBinding = true;
4227       ICS.Standard.IsLvalueReference = !isRValRef;
4228       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4229       ICS.Standard.BindsToRvalue = false;
4230       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4231       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4232       ICS.Standard.CopyConstructor = nullptr;
4233       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4234 
4235       // Nothing more to do: the inaccessibility/ambiguity check for
4236       // derived-to-base conversions is suppressed when we're
4237       // computing the implicit conversion sequence (C++
4238       // [over.best.ics]p2).
4239       return ICS;
4240     }
4241 
4242     //       -- has a class type (i.e., T2 is a class type), where T1 is
4243     //          not reference-related to T2, and can be implicitly
4244     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4245     //          is reference-compatible with "cv3 T3" 92) (this
4246     //          conversion is selected by enumerating the applicable
4247     //          conversion functions (13.3.1.6) and choosing the best
4248     //          one through overload resolution (13.3)),
4249     if (!SuppressUserConversions && T2->isRecordType() &&
4250         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4251         RefRelationship == Sema::Ref_Incompatible) {
4252       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4253                                    Init, T2, /*AllowRvalues=*/false,
4254                                    AllowExplicit))
4255         return ICS;
4256     }
4257   }
4258 
4259   //     -- Otherwise, the reference shall be an lvalue reference to a
4260   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4261   //        shall be an rvalue reference.
4262   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4263     return ICS;
4264 
4265   //       -- If the initializer expression
4266   //
4267   //            -- is an xvalue, class prvalue, array prvalue or function
4268   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4269   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4270       (InitCategory.isXValue() ||
4271       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4272       (InitCategory.isLValue() && T2->isFunctionType()))) {
4273     ICS.setStandard();
4274     ICS.Standard.First = ICK_Identity;
4275     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4276                       : ObjCConversion? ICK_Compatible_Conversion
4277                       : ICK_Identity;
4278     ICS.Standard.Third = ICK_Identity;
4279     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4280     ICS.Standard.setToType(0, T2);
4281     ICS.Standard.setToType(1, T1);
4282     ICS.Standard.setToType(2, T1);
4283     ICS.Standard.ReferenceBinding = true;
4284     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4285     // binding unless we're binding to a class prvalue.
4286     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4287     // allow the use of rvalue references in C++98/03 for the benefit of
4288     // standard library implementors; therefore, we need the xvalue check here.
4289     ICS.Standard.DirectBinding =
4290       S.getLangOpts().CPlusPlus11 ||
4291       !(InitCategory.isPRValue() || T2->isRecordType());
4292     ICS.Standard.IsLvalueReference = !isRValRef;
4293     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4294     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4295     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4296     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4297     ICS.Standard.CopyConstructor = nullptr;
4298     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4299     return ICS;
4300   }
4301 
4302   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4303   //               reference-related to T2, and can be implicitly converted to
4304   //               an xvalue, class prvalue, or function lvalue of type
4305   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4306   //               "cv3 T3",
4307   //
4308   //          then the reference is bound to the value of the initializer
4309   //          expression in the first case and to the result of the conversion
4310   //          in the second case (or, in either case, to an appropriate base
4311   //          class subobject).
4312   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4313       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4314       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4315                                Init, T2, /*AllowRvalues=*/true,
4316                                AllowExplicit)) {
4317     // In the second case, if the reference is an rvalue reference
4318     // and the second standard conversion sequence of the
4319     // user-defined conversion sequence includes an lvalue-to-rvalue
4320     // conversion, the program is ill-formed.
4321     if (ICS.isUserDefined() && isRValRef &&
4322         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4323       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4324 
4325     return ICS;
4326   }
4327 
4328   // A temporary of function type cannot be created; don't even try.
4329   if (T1->isFunctionType())
4330     return ICS;
4331 
4332   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4333   //          initialized from the initializer expression using the
4334   //          rules for a non-reference copy initialization (8.5). The
4335   //          reference is then bound to the temporary. If T1 is
4336   //          reference-related to T2, cv1 must be the same
4337   //          cv-qualification as, or greater cv-qualification than,
4338   //          cv2; otherwise, the program is ill-formed.
4339   if (RefRelationship == Sema::Ref_Related) {
4340     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4341     // we would be reference-compatible or reference-compatible with
4342     // added qualification. But that wasn't the case, so the reference
4343     // initialization fails.
4344     //
4345     // Note that we only want to check address spaces and cvr-qualifiers here.
4346     // ObjC GC and lifetime qualifiers aren't important.
4347     Qualifiers T1Quals = T1.getQualifiers();
4348     Qualifiers T2Quals = T2.getQualifiers();
4349     T1Quals.removeObjCGCAttr();
4350     T1Quals.removeObjCLifetime();
4351     T2Quals.removeObjCGCAttr();
4352     T2Quals.removeObjCLifetime();
4353     if (!T1Quals.compatiblyIncludes(T2Quals))
4354       return ICS;
4355   }
4356 
4357   // If at least one of the types is a class type, the types are not
4358   // related, and we aren't allowed any user conversions, the
4359   // reference binding fails. This case is important for breaking
4360   // recursion, since TryImplicitConversion below will attempt to
4361   // create a temporary through the use of a copy constructor.
4362   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4363       (T1->isRecordType() || T2->isRecordType()))
4364     return ICS;
4365 
4366   // If T1 is reference-related to T2 and the reference is an rvalue
4367   // reference, the initializer expression shall not be an lvalue.
4368   if (RefRelationship >= Sema::Ref_Related &&
4369       isRValRef && Init->Classify(S.Context).isLValue())
4370     return ICS;
4371 
4372   // C++ [over.ics.ref]p2:
4373   //   When a parameter of reference type is not bound directly to
4374   //   an argument expression, the conversion sequence is the one
4375   //   required to convert the argument expression to the
4376   //   underlying type of the reference according to
4377   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4378   //   to copy-initializing a temporary of the underlying type with
4379   //   the argument expression. Any difference in top-level
4380   //   cv-qualification is subsumed by the initialization itself
4381   //   and does not constitute a conversion.
4382   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4383                               /*AllowExplicit=*/false,
4384                               /*InOverloadResolution=*/false,
4385                               /*CStyle=*/false,
4386                               /*AllowObjCWritebackConversion=*/false,
4387                               /*AllowObjCConversionOnExplicit=*/false);
4388 
4389   // Of course, that's still a reference binding.
4390   if (ICS.isStandard()) {
4391     ICS.Standard.ReferenceBinding = true;
4392     ICS.Standard.IsLvalueReference = !isRValRef;
4393     ICS.Standard.BindsToFunctionLvalue = false;
4394     ICS.Standard.BindsToRvalue = true;
4395     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4396     ICS.Standard.ObjCLifetimeConversionBinding = false;
4397   } else if (ICS.isUserDefined()) {
4398     const ReferenceType *LValRefType =
4399         ICS.UserDefined.ConversionFunction->getReturnType()
4400             ->getAs<LValueReferenceType>();
4401 
4402     // C++ [over.ics.ref]p3:
4403     //   Except for an implicit object parameter, for which see 13.3.1, a
4404     //   standard conversion sequence cannot be formed if it requires [...]
4405     //   binding an rvalue reference to an lvalue other than a function
4406     //   lvalue.
4407     // Note that the function case is not possible here.
4408     if (DeclType->isRValueReferenceType() && LValRefType) {
4409       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4410       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4411       // reference to an rvalue!
4412       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4413       return ICS;
4414     }
4415 
4416     ICS.UserDefined.Before.setAsIdentityConversion();
4417     ICS.UserDefined.After.ReferenceBinding = true;
4418     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4419     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4420     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4421     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4422     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4423   }
4424 
4425   return ICS;
4426 }
4427 
4428 static ImplicitConversionSequence
4429 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4430                       bool SuppressUserConversions,
4431                       bool InOverloadResolution,
4432                       bool AllowObjCWritebackConversion,
4433                       bool AllowExplicit = false);
4434 
4435 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4436 /// initializer list From.
4437 static ImplicitConversionSequence
4438 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4439                   bool SuppressUserConversions,
4440                   bool InOverloadResolution,
4441                   bool AllowObjCWritebackConversion) {
4442   // C++11 [over.ics.list]p1:
4443   //   When an argument is an initializer list, it is not an expression and
4444   //   special rules apply for converting it to a parameter type.
4445 
4446   ImplicitConversionSequence Result;
4447   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4448 
4449   // We need a complete type for what follows. Incomplete types can never be
4450   // initialized from init lists.
4451   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4452     return Result;
4453 
4454   // Per DR1467:
4455   //   If the parameter type is a class X and the initializer list has a single
4456   //   element of type cv U, where U is X or a class derived from X, the
4457   //   implicit conversion sequence is the one required to convert the element
4458   //   to the parameter type.
4459   //
4460   //   Otherwise, if the parameter type is a character array [... ]
4461   //   and the initializer list has a single element that is an
4462   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4463   //   implicit conversion sequence is the identity conversion.
4464   if (From->getNumInits() == 1) {
4465     if (ToType->isRecordType()) {
4466       QualType InitType = From->getInit(0)->getType();
4467       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4468           S.IsDerivedFrom(InitType, ToType))
4469         return TryCopyInitialization(S, From->getInit(0), ToType,
4470                                      SuppressUserConversions,
4471                                      InOverloadResolution,
4472                                      AllowObjCWritebackConversion);
4473     }
4474     // FIXME: Check the other conditions here: array of character type,
4475     // initializer is a string literal.
4476     if (ToType->isArrayType()) {
4477       InitializedEntity Entity =
4478         InitializedEntity::InitializeParameter(S.Context, ToType,
4479                                                /*Consumed=*/false);
4480       if (S.CanPerformCopyInitialization(Entity, From)) {
4481         Result.setStandard();
4482         Result.Standard.setAsIdentityConversion();
4483         Result.Standard.setFromType(ToType);
4484         Result.Standard.setAllToTypes(ToType);
4485         return Result;
4486       }
4487     }
4488   }
4489 
4490   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4491   // C++11 [over.ics.list]p2:
4492   //   If the parameter type is std::initializer_list<X> or "array of X" and
4493   //   all the elements can be implicitly converted to X, the implicit
4494   //   conversion sequence is the worst conversion necessary to convert an
4495   //   element of the list to X.
4496   //
4497   // C++14 [over.ics.list]p3:
4498   //   Otherwise, if the parameter type is “array of N X”, if the initializer
4499   //   list has exactly N elements or if it has fewer than N elements and X is
4500   //   default-constructible, and if all the elements of the initializer list
4501   //   can be implicitly converted to X, the implicit conversion sequence is
4502   //   the worst conversion necessary to convert an element of the list to X.
4503   //
4504   // FIXME: We're missing a lot of these checks.
4505   bool toStdInitializerList = false;
4506   QualType X;
4507   if (ToType->isArrayType())
4508     X = S.Context.getAsArrayType(ToType)->getElementType();
4509   else
4510     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4511   if (!X.isNull()) {
4512     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4513       Expr *Init = From->getInit(i);
4514       ImplicitConversionSequence ICS =
4515           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4516                                 InOverloadResolution,
4517                                 AllowObjCWritebackConversion);
4518       // If a single element isn't convertible, fail.
4519       if (ICS.isBad()) {
4520         Result = ICS;
4521         break;
4522       }
4523       // Otherwise, look for the worst conversion.
4524       if (Result.isBad() ||
4525           CompareImplicitConversionSequences(S, ICS, Result) ==
4526               ImplicitConversionSequence::Worse)
4527         Result = ICS;
4528     }
4529 
4530     // For an empty list, we won't have computed any conversion sequence.
4531     // Introduce the identity conversion sequence.
4532     if (From->getNumInits() == 0) {
4533       Result.setStandard();
4534       Result.Standard.setAsIdentityConversion();
4535       Result.Standard.setFromType(ToType);
4536       Result.Standard.setAllToTypes(ToType);
4537     }
4538 
4539     Result.setStdInitializerListElement(toStdInitializerList);
4540     return Result;
4541   }
4542 
4543   // C++14 [over.ics.list]p4:
4544   // C++11 [over.ics.list]p3:
4545   //   Otherwise, if the parameter is a non-aggregate class X and overload
4546   //   resolution chooses a single best constructor [...] the implicit
4547   //   conversion sequence is a user-defined conversion sequence. If multiple
4548   //   constructors are viable but none is better than the others, the
4549   //   implicit conversion sequence is a user-defined conversion sequence.
4550   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4551     // This function can deal with initializer lists.
4552     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4553                                     /*AllowExplicit=*/false,
4554                                     InOverloadResolution, /*CStyle=*/false,
4555                                     AllowObjCWritebackConversion,
4556                                     /*AllowObjCConversionOnExplicit=*/false);
4557   }
4558 
4559   // C++14 [over.ics.list]p5:
4560   // C++11 [over.ics.list]p4:
4561   //   Otherwise, if the parameter has an aggregate type which can be
4562   //   initialized from the initializer list [...] the implicit conversion
4563   //   sequence is a user-defined conversion sequence.
4564   if (ToType->isAggregateType()) {
4565     // Type is an aggregate, argument is an init list. At this point it comes
4566     // down to checking whether the initialization works.
4567     // FIXME: Find out whether this parameter is consumed or not.
4568     InitializedEntity Entity =
4569         InitializedEntity::InitializeParameter(S.Context, ToType,
4570                                                /*Consumed=*/false);
4571     if (S.CanPerformCopyInitialization(Entity, From)) {
4572       Result.setUserDefined();
4573       Result.UserDefined.Before.setAsIdentityConversion();
4574       // Initializer lists don't have a type.
4575       Result.UserDefined.Before.setFromType(QualType());
4576       Result.UserDefined.Before.setAllToTypes(QualType());
4577 
4578       Result.UserDefined.After.setAsIdentityConversion();
4579       Result.UserDefined.After.setFromType(ToType);
4580       Result.UserDefined.After.setAllToTypes(ToType);
4581       Result.UserDefined.ConversionFunction = nullptr;
4582     }
4583     return Result;
4584   }
4585 
4586   // C++14 [over.ics.list]p6:
4587   // C++11 [over.ics.list]p5:
4588   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4589   if (ToType->isReferenceType()) {
4590     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4591     // mention initializer lists in any way. So we go by what list-
4592     // initialization would do and try to extrapolate from that.
4593 
4594     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4595 
4596     // If the initializer list has a single element that is reference-related
4597     // to the parameter type, we initialize the reference from that.
4598     if (From->getNumInits() == 1) {
4599       Expr *Init = From->getInit(0);
4600 
4601       QualType T2 = Init->getType();
4602 
4603       // If the initializer is the address of an overloaded function, try
4604       // to resolve the overloaded function. If all goes well, T2 is the
4605       // type of the resulting function.
4606       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4607         DeclAccessPair Found;
4608         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4609                                    Init, ToType, false, Found))
4610           T2 = Fn->getType();
4611       }
4612 
4613       // Compute some basic properties of the types and the initializer.
4614       bool dummy1 = false;
4615       bool dummy2 = false;
4616       bool dummy3 = false;
4617       Sema::ReferenceCompareResult RefRelationship
4618         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4619                                          dummy2, dummy3);
4620 
4621       if (RefRelationship >= Sema::Ref_Related) {
4622         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4623                                 SuppressUserConversions,
4624                                 /*AllowExplicit=*/false);
4625       }
4626     }
4627 
4628     // Otherwise, we bind the reference to a temporary created from the
4629     // initializer list.
4630     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4631                                InOverloadResolution,
4632                                AllowObjCWritebackConversion);
4633     if (Result.isFailure())
4634       return Result;
4635     assert(!Result.isEllipsis() &&
4636            "Sub-initialization cannot result in ellipsis conversion.");
4637 
4638     // Can we even bind to a temporary?
4639     if (ToType->isRValueReferenceType() ||
4640         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4641       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4642                                             Result.UserDefined.After;
4643       SCS.ReferenceBinding = true;
4644       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4645       SCS.BindsToRvalue = true;
4646       SCS.BindsToFunctionLvalue = false;
4647       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4648       SCS.ObjCLifetimeConversionBinding = false;
4649     } else
4650       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4651                     From, ToType);
4652     return Result;
4653   }
4654 
4655   // C++14 [over.ics.list]p7:
4656   // C++11 [over.ics.list]p6:
4657   //   Otherwise, if the parameter type is not a class:
4658   if (!ToType->isRecordType()) {
4659     //    - if the initializer list has one element that is not itself an
4660     //      initializer list, the implicit conversion sequence is the one
4661     //      required to convert the element to the parameter type.
4662     unsigned NumInits = From->getNumInits();
4663     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4664       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4665                                      SuppressUserConversions,
4666                                      InOverloadResolution,
4667                                      AllowObjCWritebackConversion);
4668     //    - if the initializer list has no elements, the implicit conversion
4669     //      sequence is the identity conversion.
4670     else if (NumInits == 0) {
4671       Result.setStandard();
4672       Result.Standard.setAsIdentityConversion();
4673       Result.Standard.setFromType(ToType);
4674       Result.Standard.setAllToTypes(ToType);
4675     }
4676     return Result;
4677   }
4678 
4679   // C++14 [over.ics.list]p8:
4680   // C++11 [over.ics.list]p7:
4681   //   In all cases other than those enumerated above, no conversion is possible
4682   return Result;
4683 }
4684 
4685 /// TryCopyInitialization - Try to copy-initialize a value of type
4686 /// ToType from the expression From. Return the implicit conversion
4687 /// sequence required to pass this argument, which may be a bad
4688 /// conversion sequence (meaning that the argument cannot be passed to
4689 /// a parameter of this type). If @p SuppressUserConversions, then we
4690 /// do not permit any user-defined conversion sequences.
4691 static ImplicitConversionSequence
4692 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4693                       bool SuppressUserConversions,
4694                       bool InOverloadResolution,
4695                       bool AllowObjCWritebackConversion,
4696                       bool AllowExplicit) {
4697   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4698     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4699                              InOverloadResolution,AllowObjCWritebackConversion);
4700 
4701   if (ToType->isReferenceType())
4702     return TryReferenceInit(S, From, ToType,
4703                             /*FIXME:*/From->getLocStart(),
4704                             SuppressUserConversions,
4705                             AllowExplicit);
4706 
4707   return TryImplicitConversion(S, From, ToType,
4708                                SuppressUserConversions,
4709                                /*AllowExplicit=*/false,
4710                                InOverloadResolution,
4711                                /*CStyle=*/false,
4712                                AllowObjCWritebackConversion,
4713                                /*AllowObjCConversionOnExplicit=*/false);
4714 }
4715 
4716 static bool TryCopyInitialization(const CanQualType FromQTy,
4717                                   const CanQualType ToQTy,
4718                                   Sema &S,
4719                                   SourceLocation Loc,
4720                                   ExprValueKind FromVK) {
4721   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4722   ImplicitConversionSequence ICS =
4723     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4724 
4725   return !ICS.isBad();
4726 }
4727 
4728 /// TryObjectArgumentInitialization - Try to initialize the object
4729 /// parameter of the given member function (@c Method) from the
4730 /// expression @p From.
4731 static ImplicitConversionSequence
4732 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4733                                 Expr::Classification FromClassification,
4734                                 CXXMethodDecl *Method,
4735                                 CXXRecordDecl *ActingContext) {
4736   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4737   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4738   //                 const volatile object.
4739   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4740     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4741   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4742 
4743   // Set up the conversion sequence as a "bad" conversion, to allow us
4744   // to exit early.
4745   ImplicitConversionSequence ICS;
4746 
4747   // We need to have an object of class type.
4748   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4749     FromType = PT->getPointeeType();
4750 
4751     // When we had a pointer, it's implicitly dereferenced, so we
4752     // better have an lvalue.
4753     assert(FromClassification.isLValue());
4754   }
4755 
4756   assert(FromType->isRecordType());
4757 
4758   // C++0x [over.match.funcs]p4:
4759   //   For non-static member functions, the type of the implicit object
4760   //   parameter is
4761   //
4762   //     - "lvalue reference to cv X" for functions declared without a
4763   //        ref-qualifier or with the & ref-qualifier
4764   //     - "rvalue reference to cv X" for functions declared with the &&
4765   //        ref-qualifier
4766   //
4767   // where X is the class of which the function is a member and cv is the
4768   // cv-qualification on the member function declaration.
4769   //
4770   // However, when finding an implicit conversion sequence for the argument, we
4771   // are not allowed to create temporaries or perform user-defined conversions
4772   // (C++ [over.match.funcs]p5). We perform a simplified version of
4773   // reference binding here, that allows class rvalues to bind to
4774   // non-constant references.
4775 
4776   // First check the qualifiers.
4777   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4778   if (ImplicitParamType.getCVRQualifiers()
4779                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4780       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4781     ICS.setBad(BadConversionSequence::bad_qualifiers,
4782                FromType, ImplicitParamType);
4783     return ICS;
4784   }
4785 
4786   // Check that we have either the same type or a derived type. It
4787   // affects the conversion rank.
4788   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4789   ImplicitConversionKind SecondKind;
4790   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4791     SecondKind = ICK_Identity;
4792   } else if (S.IsDerivedFrom(FromType, ClassType))
4793     SecondKind = ICK_Derived_To_Base;
4794   else {
4795     ICS.setBad(BadConversionSequence::unrelated_class,
4796                FromType, ImplicitParamType);
4797     return ICS;
4798   }
4799 
4800   // Check the ref-qualifier.
4801   switch (Method->getRefQualifier()) {
4802   case RQ_None:
4803     // Do nothing; we don't care about lvalueness or rvalueness.
4804     break;
4805 
4806   case RQ_LValue:
4807     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4808       // non-const lvalue reference cannot bind to an rvalue
4809       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4810                  ImplicitParamType);
4811       return ICS;
4812     }
4813     break;
4814 
4815   case RQ_RValue:
4816     if (!FromClassification.isRValue()) {
4817       // rvalue reference cannot bind to an lvalue
4818       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4819                  ImplicitParamType);
4820       return ICS;
4821     }
4822     break;
4823   }
4824 
4825   // Success. Mark this as a reference binding.
4826   ICS.setStandard();
4827   ICS.Standard.setAsIdentityConversion();
4828   ICS.Standard.Second = SecondKind;
4829   ICS.Standard.setFromType(FromType);
4830   ICS.Standard.setAllToTypes(ImplicitParamType);
4831   ICS.Standard.ReferenceBinding = true;
4832   ICS.Standard.DirectBinding = true;
4833   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4834   ICS.Standard.BindsToFunctionLvalue = false;
4835   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4836   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4837     = (Method->getRefQualifier() == RQ_None);
4838   return ICS;
4839 }
4840 
4841 /// PerformObjectArgumentInitialization - Perform initialization of
4842 /// the implicit object parameter for the given Method with the given
4843 /// expression.
4844 ExprResult
4845 Sema::PerformObjectArgumentInitialization(Expr *From,
4846                                           NestedNameSpecifier *Qualifier,
4847                                           NamedDecl *FoundDecl,
4848                                           CXXMethodDecl *Method) {
4849   QualType FromRecordType, DestType;
4850   QualType ImplicitParamRecordType  =
4851     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4852 
4853   Expr::Classification FromClassification;
4854   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4855     FromRecordType = PT->getPointeeType();
4856     DestType = Method->getThisType(Context);
4857     FromClassification = Expr::Classification::makeSimpleLValue();
4858   } else {
4859     FromRecordType = From->getType();
4860     DestType = ImplicitParamRecordType;
4861     FromClassification = From->Classify(Context);
4862   }
4863 
4864   // Note that we always use the true parent context when performing
4865   // the actual argument initialization.
4866   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4867       *this, From->getType(), FromClassification, Method, Method->getParent());
4868   if (ICS.isBad()) {
4869     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4870       Qualifiers FromQs = FromRecordType.getQualifiers();
4871       Qualifiers ToQs = DestType.getQualifiers();
4872       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4873       if (CVR) {
4874         Diag(From->getLocStart(),
4875              diag::err_member_function_call_bad_cvr)
4876           << Method->getDeclName() << FromRecordType << (CVR - 1)
4877           << From->getSourceRange();
4878         Diag(Method->getLocation(), diag::note_previous_decl)
4879           << Method->getDeclName();
4880         return ExprError();
4881       }
4882     }
4883 
4884     return Diag(From->getLocStart(),
4885                 diag::err_implicit_object_parameter_init)
4886        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4887   }
4888 
4889   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4890     ExprResult FromRes =
4891       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4892     if (FromRes.isInvalid())
4893       return ExprError();
4894     From = FromRes.get();
4895   }
4896 
4897   if (!Context.hasSameType(From->getType(), DestType))
4898     From = ImpCastExprToType(From, DestType, CK_NoOp,
4899                              From->getValueKind()).get();
4900   return From;
4901 }
4902 
4903 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4904 /// expression From to bool (C++0x [conv]p3).
4905 static ImplicitConversionSequence
4906 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4907   return TryImplicitConversion(S, From, S.Context.BoolTy,
4908                                /*SuppressUserConversions=*/false,
4909                                /*AllowExplicit=*/true,
4910                                /*InOverloadResolution=*/false,
4911                                /*CStyle=*/false,
4912                                /*AllowObjCWritebackConversion=*/false,
4913                                /*AllowObjCConversionOnExplicit=*/false);
4914 }
4915 
4916 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4917 /// of the expression From to bool (C++0x [conv]p3).
4918 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4919   if (checkPlaceholderForOverload(*this, From))
4920     return ExprError();
4921 
4922   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4923   if (!ICS.isBad())
4924     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4925 
4926   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4927     return Diag(From->getLocStart(),
4928                 diag::err_typecheck_bool_condition)
4929                   << From->getType() << From->getSourceRange();
4930   return ExprError();
4931 }
4932 
4933 /// Check that the specified conversion is permitted in a converted constant
4934 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4935 /// is acceptable.
4936 static bool CheckConvertedConstantConversions(Sema &S,
4937                                               StandardConversionSequence &SCS) {
4938   // Since we know that the target type is an integral or unscoped enumeration
4939   // type, most conversion kinds are impossible. All possible First and Third
4940   // conversions are fine.
4941   switch (SCS.Second) {
4942   case ICK_Identity:
4943   case ICK_NoReturn_Adjustment:
4944   case ICK_Integral_Promotion:
4945   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
4946     return true;
4947 
4948   case ICK_Boolean_Conversion:
4949     // Conversion from an integral or unscoped enumeration type to bool is
4950     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4951     // conversion, so we allow it in a converted constant expression.
4952     //
4953     // FIXME: Per core issue 1407, we should not allow this, but that breaks
4954     // a lot of popular code. We should at least add a warning for this
4955     // (non-conforming) extension.
4956     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4957            SCS.getToType(2)->isBooleanType();
4958 
4959   case ICK_Pointer_Conversion:
4960   case ICK_Pointer_Member:
4961     // C++1z: null pointer conversions and null member pointer conversions are
4962     // only permitted if the source type is std::nullptr_t.
4963     return SCS.getFromType()->isNullPtrType();
4964 
4965   case ICK_Floating_Promotion:
4966   case ICK_Complex_Promotion:
4967   case ICK_Floating_Conversion:
4968   case ICK_Complex_Conversion:
4969   case ICK_Floating_Integral:
4970   case ICK_Compatible_Conversion:
4971   case ICK_Derived_To_Base:
4972   case ICK_Vector_Conversion:
4973   case ICK_Vector_Splat:
4974   case ICK_Complex_Real:
4975   case ICK_Block_Pointer_Conversion:
4976   case ICK_TransparentUnionConversion:
4977   case ICK_Writeback_Conversion:
4978   case ICK_Zero_Event_Conversion:
4979     return false;
4980 
4981   case ICK_Lvalue_To_Rvalue:
4982   case ICK_Array_To_Pointer:
4983   case ICK_Function_To_Pointer:
4984     llvm_unreachable("found a first conversion kind in Second");
4985 
4986   case ICK_Qualification:
4987     llvm_unreachable("found a third conversion kind in Second");
4988 
4989   case ICK_Num_Conversion_Kinds:
4990     break;
4991   }
4992 
4993   llvm_unreachable("unknown conversion kind");
4994 }
4995 
4996 /// CheckConvertedConstantExpression - Check that the expression From is a
4997 /// converted constant expression of type T, perform the conversion and produce
4998 /// the converted expression, per C++11 [expr.const]p3.
4999 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5000                                                    QualType T, APValue &Value,
5001                                                    Sema::CCEKind CCE,
5002                                                    bool RequireInt) {
5003   assert(S.getLangOpts().CPlusPlus11 &&
5004          "converted constant expression outside C++11");
5005 
5006   if (checkPlaceholderForOverload(S, From))
5007     return ExprError();
5008 
5009   // C++1z [expr.const]p3:
5010   //  A converted constant expression of type T is an expression,
5011   //  implicitly converted to type T, where the converted
5012   //  expression is a constant expression and the implicit conversion
5013   //  sequence contains only [... list of conversions ...].
5014   ImplicitConversionSequence ICS =
5015     TryCopyInitialization(S, From, T,
5016                           /*SuppressUserConversions=*/false,
5017                           /*InOverloadResolution=*/false,
5018                           /*AllowObjcWritebackConversion=*/false,
5019                           /*AllowExplicit=*/false);
5020   StandardConversionSequence *SCS = nullptr;
5021   switch (ICS.getKind()) {
5022   case ImplicitConversionSequence::StandardConversion:
5023     SCS = &ICS.Standard;
5024     break;
5025   case ImplicitConversionSequence::UserDefinedConversion:
5026     // We are converting to a non-class type, so the Before sequence
5027     // must be trivial.
5028     SCS = &ICS.UserDefined.After;
5029     break;
5030   case ImplicitConversionSequence::AmbiguousConversion:
5031   case ImplicitConversionSequence::BadConversion:
5032     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5033       return S.Diag(From->getLocStart(),
5034                     diag::err_typecheck_converted_constant_expression)
5035                 << From->getType() << From->getSourceRange() << T;
5036     return ExprError();
5037 
5038   case ImplicitConversionSequence::EllipsisConversion:
5039     llvm_unreachable("ellipsis conversion in converted constant expression");
5040   }
5041 
5042   // Check that we would only use permitted conversions.
5043   if (!CheckConvertedConstantConversions(S, *SCS)) {
5044     return S.Diag(From->getLocStart(),
5045                   diag::err_typecheck_converted_constant_expression_disallowed)
5046              << From->getType() << From->getSourceRange() << T;
5047   }
5048   // [...] and where the reference binding (if any) binds directly.
5049   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5050     return S.Diag(From->getLocStart(),
5051                   diag::err_typecheck_converted_constant_expression_indirect)
5052              << From->getType() << From->getSourceRange() << T;
5053   }
5054 
5055   ExprResult Result =
5056       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5057   if (Result.isInvalid())
5058     return Result;
5059 
5060   // Check for a narrowing implicit conversion.
5061   APValue PreNarrowingValue;
5062   QualType PreNarrowingType;
5063   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5064                                 PreNarrowingType)) {
5065   case NK_Variable_Narrowing:
5066     // Implicit conversion to a narrower type, and the value is not a constant
5067     // expression. We'll diagnose this in a moment.
5068   case NK_Not_Narrowing:
5069     break;
5070 
5071   case NK_Constant_Narrowing:
5072     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5073       << CCE << /*Constant*/1
5074       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5075     break;
5076 
5077   case NK_Type_Narrowing:
5078     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5079       << CCE << /*Constant*/0 << From->getType() << T;
5080     break;
5081   }
5082 
5083   // Check the expression is a constant expression.
5084   SmallVector<PartialDiagnosticAt, 8> Notes;
5085   Expr::EvalResult Eval;
5086   Eval.Diag = &Notes;
5087 
5088   if ((T->isReferenceType()
5089            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5090            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5091       (RequireInt && !Eval.Val.isInt())) {
5092     // The expression can't be folded, so we can't keep it at this position in
5093     // the AST.
5094     Result = ExprError();
5095   } else {
5096     Value = Eval.Val;
5097 
5098     if (Notes.empty()) {
5099       // It's a constant expression.
5100       return Result;
5101     }
5102   }
5103 
5104   // It's not a constant expression. Produce an appropriate diagnostic.
5105   if (Notes.size() == 1 &&
5106       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5107     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5108   else {
5109     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5110       << CCE << From->getSourceRange();
5111     for (unsigned I = 0; I < Notes.size(); ++I)
5112       S.Diag(Notes[I].first, Notes[I].second);
5113   }
5114   return ExprError();
5115 }
5116 
5117 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5118                                                   APValue &Value, CCEKind CCE) {
5119   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5120 }
5121 
5122 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5123                                                   llvm::APSInt &Value,
5124                                                   CCEKind CCE) {
5125   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5126 
5127   APValue V;
5128   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5129   if (!R.isInvalid())
5130     Value = V.getInt();
5131   return R;
5132 }
5133 
5134 
5135 /// dropPointerConversions - If the given standard conversion sequence
5136 /// involves any pointer conversions, remove them.  This may change
5137 /// the result type of the conversion sequence.
5138 static void dropPointerConversion(StandardConversionSequence &SCS) {
5139   if (SCS.Second == ICK_Pointer_Conversion) {
5140     SCS.Second = ICK_Identity;
5141     SCS.Third = ICK_Identity;
5142     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5143   }
5144 }
5145 
5146 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5147 /// convert the expression From to an Objective-C pointer type.
5148 static ImplicitConversionSequence
5149 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5150   // Do an implicit conversion to 'id'.
5151   QualType Ty = S.Context.getObjCIdType();
5152   ImplicitConversionSequence ICS
5153     = TryImplicitConversion(S, From, Ty,
5154                             // FIXME: Are these flags correct?
5155                             /*SuppressUserConversions=*/false,
5156                             /*AllowExplicit=*/true,
5157                             /*InOverloadResolution=*/false,
5158                             /*CStyle=*/false,
5159                             /*AllowObjCWritebackConversion=*/false,
5160                             /*AllowObjCConversionOnExplicit=*/true);
5161 
5162   // Strip off any final conversions to 'id'.
5163   switch (ICS.getKind()) {
5164   case ImplicitConversionSequence::BadConversion:
5165   case ImplicitConversionSequence::AmbiguousConversion:
5166   case ImplicitConversionSequence::EllipsisConversion:
5167     break;
5168 
5169   case ImplicitConversionSequence::UserDefinedConversion:
5170     dropPointerConversion(ICS.UserDefined.After);
5171     break;
5172 
5173   case ImplicitConversionSequence::StandardConversion:
5174     dropPointerConversion(ICS.Standard);
5175     break;
5176   }
5177 
5178   return ICS;
5179 }
5180 
5181 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5182 /// conversion of the expression From to an Objective-C pointer type.
5183 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5184   if (checkPlaceholderForOverload(*this, From))
5185     return ExprError();
5186 
5187   QualType Ty = Context.getObjCIdType();
5188   ImplicitConversionSequence ICS =
5189     TryContextuallyConvertToObjCPointer(*this, From);
5190   if (!ICS.isBad())
5191     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5192   return ExprError();
5193 }
5194 
5195 /// Determine whether the provided type is an integral type, or an enumeration
5196 /// type of a permitted flavor.
5197 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5198   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5199                                  : T->isIntegralOrUnscopedEnumerationType();
5200 }
5201 
5202 static ExprResult
5203 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5204                             Sema::ContextualImplicitConverter &Converter,
5205                             QualType T, UnresolvedSetImpl &ViableConversions) {
5206 
5207   if (Converter.Suppress)
5208     return ExprError();
5209 
5210   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5211   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5212     CXXConversionDecl *Conv =
5213         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5214     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5215     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5216   }
5217   return From;
5218 }
5219 
5220 static bool
5221 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5222                            Sema::ContextualImplicitConverter &Converter,
5223                            QualType T, bool HadMultipleCandidates,
5224                            UnresolvedSetImpl &ExplicitConversions) {
5225   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5226     DeclAccessPair Found = ExplicitConversions[0];
5227     CXXConversionDecl *Conversion =
5228         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5229 
5230     // The user probably meant to invoke the given explicit
5231     // conversion; use it.
5232     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5233     std::string TypeStr;
5234     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5235 
5236     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5237         << FixItHint::CreateInsertion(From->getLocStart(),
5238                                       "static_cast<" + TypeStr + ">(")
5239         << FixItHint::CreateInsertion(
5240                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5241     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5242 
5243     // If we aren't in a SFINAE context, build a call to the
5244     // explicit conversion function.
5245     if (SemaRef.isSFINAEContext())
5246       return true;
5247 
5248     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5249     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5250                                                        HadMultipleCandidates);
5251     if (Result.isInvalid())
5252       return true;
5253     // Record usage of conversion in an implicit cast.
5254     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5255                                     CK_UserDefinedConversion, Result.get(),
5256                                     nullptr, Result.get()->getValueKind());
5257   }
5258   return false;
5259 }
5260 
5261 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5262                              Sema::ContextualImplicitConverter &Converter,
5263                              QualType T, bool HadMultipleCandidates,
5264                              DeclAccessPair &Found) {
5265   CXXConversionDecl *Conversion =
5266       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5267   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5268 
5269   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5270   if (!Converter.SuppressConversion) {
5271     if (SemaRef.isSFINAEContext())
5272       return true;
5273 
5274     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5275         << From->getSourceRange();
5276   }
5277 
5278   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5279                                                      HadMultipleCandidates);
5280   if (Result.isInvalid())
5281     return true;
5282   // Record usage of conversion in an implicit cast.
5283   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5284                                   CK_UserDefinedConversion, Result.get(),
5285                                   nullptr, Result.get()->getValueKind());
5286   return false;
5287 }
5288 
5289 static ExprResult finishContextualImplicitConversion(
5290     Sema &SemaRef, SourceLocation Loc, Expr *From,
5291     Sema::ContextualImplicitConverter &Converter) {
5292   if (!Converter.match(From->getType()) && !Converter.Suppress)
5293     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5294         << From->getSourceRange();
5295 
5296   return SemaRef.DefaultLvalueConversion(From);
5297 }
5298 
5299 static void
5300 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5301                                   UnresolvedSetImpl &ViableConversions,
5302                                   OverloadCandidateSet &CandidateSet) {
5303   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5304     DeclAccessPair FoundDecl = ViableConversions[I];
5305     NamedDecl *D = FoundDecl.getDecl();
5306     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5307     if (isa<UsingShadowDecl>(D))
5308       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5309 
5310     CXXConversionDecl *Conv;
5311     FunctionTemplateDecl *ConvTemplate;
5312     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5313       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5314     else
5315       Conv = cast<CXXConversionDecl>(D);
5316 
5317     if (ConvTemplate)
5318       SemaRef.AddTemplateConversionCandidate(
5319         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5320         /*AllowObjCConversionOnExplicit=*/false);
5321     else
5322       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5323                                      ToType, CandidateSet,
5324                                      /*AllowObjCConversionOnExplicit=*/false);
5325   }
5326 }
5327 
5328 /// \brief Attempt to convert the given expression to a type which is accepted
5329 /// by the given converter.
5330 ///
5331 /// This routine will attempt to convert an expression of class type to a
5332 /// type accepted by the specified converter. In C++11 and before, the class
5333 /// must have a single non-explicit conversion function converting to a matching
5334 /// type. In C++1y, there can be multiple such conversion functions, but only
5335 /// one target type.
5336 ///
5337 /// \param Loc The source location of the construct that requires the
5338 /// conversion.
5339 ///
5340 /// \param From The expression we're converting from.
5341 ///
5342 /// \param Converter Used to control and diagnose the conversion process.
5343 ///
5344 /// \returns The expression, converted to an integral or enumeration type if
5345 /// successful.
5346 ExprResult Sema::PerformContextualImplicitConversion(
5347     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5348   // We can't perform any more checking for type-dependent expressions.
5349   if (From->isTypeDependent())
5350     return From;
5351 
5352   // Process placeholders immediately.
5353   if (From->hasPlaceholderType()) {
5354     ExprResult result = CheckPlaceholderExpr(From);
5355     if (result.isInvalid())
5356       return result;
5357     From = result.get();
5358   }
5359 
5360   // If the expression already has a matching type, we're golden.
5361   QualType T = From->getType();
5362   if (Converter.match(T))
5363     return DefaultLvalueConversion(From);
5364 
5365   // FIXME: Check for missing '()' if T is a function type?
5366 
5367   // We can only perform contextual implicit conversions on objects of class
5368   // type.
5369   const RecordType *RecordTy = T->getAs<RecordType>();
5370   if (!RecordTy || !getLangOpts().CPlusPlus) {
5371     if (!Converter.Suppress)
5372       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5373     return From;
5374   }
5375 
5376   // We must have a complete class type.
5377   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5378     ContextualImplicitConverter &Converter;
5379     Expr *From;
5380 
5381     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5382         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5383 
5384     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5385       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5386     }
5387   } IncompleteDiagnoser(Converter, From);
5388 
5389   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5390     return From;
5391 
5392   // Look for a conversion to an integral or enumeration type.
5393   UnresolvedSet<4>
5394       ViableConversions; // These are *potentially* viable in C++1y.
5395   UnresolvedSet<4> ExplicitConversions;
5396   const auto &Conversions =
5397       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5398 
5399   bool HadMultipleCandidates =
5400       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5401 
5402   // To check that there is only one target type, in C++1y:
5403   QualType ToType;
5404   bool HasUniqueTargetType = true;
5405 
5406   // Collect explicit or viable (potentially in C++1y) conversions.
5407   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5408     NamedDecl *D = (*I)->getUnderlyingDecl();
5409     CXXConversionDecl *Conversion;
5410     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5411     if (ConvTemplate) {
5412       if (getLangOpts().CPlusPlus14)
5413         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5414       else
5415         continue; // C++11 does not consider conversion operator templates(?).
5416     } else
5417       Conversion = cast<CXXConversionDecl>(D);
5418 
5419     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5420            "Conversion operator templates are considered potentially "
5421            "viable in C++1y");
5422 
5423     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5424     if (Converter.match(CurToType) || ConvTemplate) {
5425 
5426       if (Conversion->isExplicit()) {
5427         // FIXME: For C++1y, do we need this restriction?
5428         // cf. diagnoseNoViableConversion()
5429         if (!ConvTemplate)
5430           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5431       } else {
5432         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5433           if (ToType.isNull())
5434             ToType = CurToType.getUnqualifiedType();
5435           else if (HasUniqueTargetType &&
5436                    (CurToType.getUnqualifiedType() != ToType))
5437             HasUniqueTargetType = false;
5438         }
5439         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5440       }
5441     }
5442   }
5443 
5444   if (getLangOpts().CPlusPlus14) {
5445     // C++1y [conv]p6:
5446     // ... An expression e of class type E appearing in such a context
5447     // is said to be contextually implicitly converted to a specified
5448     // type T and is well-formed if and only if e can be implicitly
5449     // converted to a type T that is determined as follows: E is searched
5450     // for conversion functions whose return type is cv T or reference to
5451     // cv T such that T is allowed by the context. There shall be
5452     // exactly one such T.
5453 
5454     // If no unique T is found:
5455     if (ToType.isNull()) {
5456       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5457                                      HadMultipleCandidates,
5458                                      ExplicitConversions))
5459         return ExprError();
5460       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5461     }
5462 
5463     // If more than one unique Ts are found:
5464     if (!HasUniqueTargetType)
5465       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5466                                          ViableConversions);
5467 
5468     // If one unique T is found:
5469     // First, build a candidate set from the previously recorded
5470     // potentially viable conversions.
5471     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5472     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5473                                       CandidateSet);
5474 
5475     // Then, perform overload resolution over the candidate set.
5476     OverloadCandidateSet::iterator Best;
5477     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5478     case OR_Success: {
5479       // Apply this conversion.
5480       DeclAccessPair Found =
5481           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5482       if (recordConversion(*this, Loc, From, Converter, T,
5483                            HadMultipleCandidates, Found))
5484         return ExprError();
5485       break;
5486     }
5487     case OR_Ambiguous:
5488       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5489                                          ViableConversions);
5490     case OR_No_Viable_Function:
5491       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5492                                      HadMultipleCandidates,
5493                                      ExplicitConversions))
5494         return ExprError();
5495     // fall through 'OR_Deleted' case.
5496     case OR_Deleted:
5497       // We'll complain below about a non-integral condition type.
5498       break;
5499     }
5500   } else {
5501     switch (ViableConversions.size()) {
5502     case 0: {
5503       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5504                                      HadMultipleCandidates,
5505                                      ExplicitConversions))
5506         return ExprError();
5507 
5508       // We'll complain below about a non-integral condition type.
5509       break;
5510     }
5511     case 1: {
5512       // Apply this conversion.
5513       DeclAccessPair Found = ViableConversions[0];
5514       if (recordConversion(*this, Loc, From, Converter, T,
5515                            HadMultipleCandidates, Found))
5516         return ExprError();
5517       break;
5518     }
5519     default:
5520       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5521                                          ViableConversions);
5522     }
5523   }
5524 
5525   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5526 }
5527 
5528 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5529 /// an acceptable non-member overloaded operator for a call whose
5530 /// arguments have types T1 (and, if non-empty, T2). This routine
5531 /// implements the check in C++ [over.match.oper]p3b2 concerning
5532 /// enumeration types.
5533 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5534                                                    FunctionDecl *Fn,
5535                                                    ArrayRef<Expr *> Args) {
5536   QualType T1 = Args[0]->getType();
5537   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5538 
5539   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5540     return true;
5541 
5542   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5543     return true;
5544 
5545   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5546   if (Proto->getNumParams() < 1)
5547     return false;
5548 
5549   if (T1->isEnumeralType()) {
5550     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5551     if (Context.hasSameUnqualifiedType(T1, ArgType))
5552       return true;
5553   }
5554 
5555   if (Proto->getNumParams() < 2)
5556     return false;
5557 
5558   if (!T2.isNull() && T2->isEnumeralType()) {
5559     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5560     if (Context.hasSameUnqualifiedType(T2, ArgType))
5561       return true;
5562   }
5563 
5564   return false;
5565 }
5566 
5567 /// AddOverloadCandidate - Adds the given function to the set of
5568 /// candidate functions, using the given function call arguments.  If
5569 /// @p SuppressUserConversions, then don't allow user-defined
5570 /// conversions via constructors or conversion operators.
5571 ///
5572 /// \param PartialOverloading true if we are performing "partial" overloading
5573 /// based on an incomplete set of function arguments. This feature is used by
5574 /// code completion.
5575 void
5576 Sema::AddOverloadCandidate(FunctionDecl *Function,
5577                            DeclAccessPair FoundDecl,
5578                            ArrayRef<Expr *> Args,
5579                            OverloadCandidateSet &CandidateSet,
5580                            bool SuppressUserConversions,
5581                            bool PartialOverloading,
5582                            bool AllowExplicit) {
5583   const FunctionProtoType *Proto
5584     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5585   assert(Proto && "Functions without a prototype cannot be overloaded");
5586   assert(!Function->getDescribedFunctionTemplate() &&
5587          "Use AddTemplateOverloadCandidate for function templates");
5588 
5589   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5590     if (!isa<CXXConstructorDecl>(Method)) {
5591       // If we get here, it's because we're calling a member function
5592       // that is named without a member access expression (e.g.,
5593       // "this->f") that was either written explicitly or created
5594       // implicitly. This can happen with a qualified call to a member
5595       // function, e.g., X::f(). We use an empty type for the implied
5596       // object argument (C++ [over.call.func]p3), and the acting context
5597       // is irrelevant.
5598       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5599                          QualType(), Expr::Classification::makeSimpleLValue(),
5600                          Args, CandidateSet, SuppressUserConversions,
5601                          PartialOverloading);
5602       return;
5603     }
5604     // We treat a constructor like a non-member function, since its object
5605     // argument doesn't participate in overload resolution.
5606   }
5607 
5608   if (!CandidateSet.isNewCandidate(Function))
5609     return;
5610 
5611   // C++ [over.match.oper]p3:
5612   //   if no operand has a class type, only those non-member functions in the
5613   //   lookup set that have a first parameter of type T1 or "reference to
5614   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5615   //   is a right operand) a second parameter of type T2 or "reference to
5616   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5617   //   candidate functions.
5618   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5619       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5620     return;
5621 
5622   // C++11 [class.copy]p11: [DR1402]
5623   //   A defaulted move constructor that is defined as deleted is ignored by
5624   //   overload resolution.
5625   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5626   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5627       Constructor->isMoveConstructor())
5628     return;
5629 
5630   // Overload resolution is always an unevaluated context.
5631   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5632 
5633   // Add this candidate
5634   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5635   Candidate.FoundDecl = FoundDecl;
5636   Candidate.Function = Function;
5637   Candidate.Viable = true;
5638   Candidate.IsSurrogate = false;
5639   Candidate.IgnoreObjectArgument = false;
5640   Candidate.ExplicitCallArguments = Args.size();
5641 
5642   if (Constructor) {
5643     // C++ [class.copy]p3:
5644     //   A member function template is never instantiated to perform the copy
5645     //   of a class object to an object of its class type.
5646     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5647     if (Args.size() == 1 &&
5648         Constructor->isSpecializationCopyingObject() &&
5649         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5650          IsDerivedFrom(Args[0]->getType(), ClassType))) {
5651       Candidate.Viable = false;
5652       Candidate.FailureKind = ovl_fail_illegal_constructor;
5653       return;
5654     }
5655   }
5656 
5657   unsigned NumParams = Proto->getNumParams();
5658 
5659   // (C++ 13.3.2p2): A candidate function having fewer than m
5660   // parameters is viable only if it has an ellipsis in its parameter
5661   // list (8.3.5).
5662   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5663       !Proto->isVariadic()) {
5664     Candidate.Viable = false;
5665     Candidate.FailureKind = ovl_fail_too_many_arguments;
5666     return;
5667   }
5668 
5669   // (C++ 13.3.2p2): A candidate function having more than m parameters
5670   // is viable only if the (m+1)st parameter has a default argument
5671   // (8.3.6). For the purposes of overload resolution, the
5672   // parameter list is truncated on the right, so that there are
5673   // exactly m parameters.
5674   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5675   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5676     // Not enough arguments.
5677     Candidate.Viable = false;
5678     Candidate.FailureKind = ovl_fail_too_few_arguments;
5679     return;
5680   }
5681 
5682   // (CUDA B.1): Check for invalid calls between targets.
5683   if (getLangOpts().CUDA)
5684     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5685       // Skip the check for callers that are implicit members, because in this
5686       // case we may not yet know what the member's target is; the target is
5687       // inferred for the member automatically, based on the bases and fields of
5688       // the class.
5689       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5690         Candidate.Viable = false;
5691         Candidate.FailureKind = ovl_fail_bad_target;
5692         return;
5693       }
5694 
5695   // Determine the implicit conversion sequences for each of the
5696   // arguments.
5697   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5698     if (ArgIdx < NumParams) {
5699       // (C++ 13.3.2p3): for F to be a viable function, there shall
5700       // exist for each argument an implicit conversion sequence
5701       // (13.3.3.1) that converts that argument to the corresponding
5702       // parameter of F.
5703       QualType ParamType = Proto->getParamType(ArgIdx);
5704       Candidate.Conversions[ArgIdx]
5705         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5706                                 SuppressUserConversions,
5707                                 /*InOverloadResolution=*/true,
5708                                 /*AllowObjCWritebackConversion=*/
5709                                   getLangOpts().ObjCAutoRefCount,
5710                                 AllowExplicit);
5711       if (Candidate.Conversions[ArgIdx].isBad()) {
5712         Candidate.Viable = false;
5713         Candidate.FailureKind = ovl_fail_bad_conversion;
5714         return;
5715       }
5716     } else {
5717       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5718       // argument for which there is no corresponding parameter is
5719       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5720       Candidate.Conversions[ArgIdx].setEllipsis();
5721     }
5722   }
5723 
5724   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5725     Candidate.Viable = false;
5726     Candidate.FailureKind = ovl_fail_enable_if;
5727     Candidate.DeductionFailure.Data = FailedAttr;
5728     return;
5729   }
5730 }
5731 
5732 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5733                                        bool IsInstance) {
5734   SmallVector<ObjCMethodDecl*, 4> Methods;
5735   if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5736     return nullptr;
5737 
5738   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5739     bool Match = true;
5740     ObjCMethodDecl *Method = Methods[b];
5741     unsigned NumNamedArgs = Sel.getNumArgs();
5742     // Method might have more arguments than selector indicates. This is due
5743     // to addition of c-style arguments in method.
5744     if (Method->param_size() > NumNamedArgs)
5745       NumNamedArgs = Method->param_size();
5746     if (Args.size() < NumNamedArgs)
5747       continue;
5748 
5749     for (unsigned i = 0; i < NumNamedArgs; i++) {
5750       // We can't do any type-checking on a type-dependent argument.
5751       if (Args[i]->isTypeDependent()) {
5752         Match = false;
5753         break;
5754       }
5755 
5756       ParmVarDecl *param = Method->parameters()[i];
5757       Expr *argExpr = Args[i];
5758       assert(argExpr && "SelectBestMethod(): missing expression");
5759 
5760       // Strip the unbridged-cast placeholder expression off unless it's
5761       // a consumed argument.
5762       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5763           !param->hasAttr<CFConsumedAttr>())
5764         argExpr = stripARCUnbridgedCast(argExpr);
5765 
5766       // If the parameter is __unknown_anytype, move on to the next method.
5767       if (param->getType() == Context.UnknownAnyTy) {
5768         Match = false;
5769         break;
5770       }
5771 
5772       ImplicitConversionSequence ConversionState
5773         = TryCopyInitialization(*this, argExpr, param->getType(),
5774                                 /*SuppressUserConversions*/false,
5775                                 /*InOverloadResolution=*/true,
5776                                 /*AllowObjCWritebackConversion=*/
5777                                 getLangOpts().ObjCAutoRefCount,
5778                                 /*AllowExplicit*/false);
5779         if (ConversionState.isBad()) {
5780           Match = false;
5781           break;
5782         }
5783     }
5784     // Promote additional arguments to variadic methods.
5785     if (Match && Method->isVariadic()) {
5786       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5787         if (Args[i]->isTypeDependent()) {
5788           Match = false;
5789           break;
5790         }
5791         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5792                                                           nullptr);
5793         if (Arg.isInvalid()) {
5794           Match = false;
5795           break;
5796         }
5797       }
5798     } else {
5799       // Check for extra arguments to non-variadic methods.
5800       if (Args.size() != NumNamedArgs)
5801         Match = false;
5802       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5803         // Special case when selectors have no argument. In this case, select
5804         // one with the most general result type of 'id'.
5805         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5806           QualType ReturnT = Methods[b]->getReturnType();
5807           if (ReturnT->isObjCIdType())
5808             return Methods[b];
5809         }
5810       }
5811     }
5812 
5813     if (Match)
5814       return Method;
5815   }
5816   return nullptr;
5817 }
5818 
5819 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5820 
5821 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5822                                   bool MissingImplicitThis) {
5823   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5824   // we need to find the first failing one.
5825   if (!Function->hasAttrs())
5826     return nullptr;
5827   AttrVec Attrs = Function->getAttrs();
5828   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5829                                        IsNotEnableIfAttr);
5830   if (Attrs.begin() == E)
5831     return nullptr;
5832   std::reverse(Attrs.begin(), E);
5833 
5834   SFINAETrap Trap(*this);
5835 
5836   // Convert the arguments.
5837   SmallVector<Expr *, 16> ConvertedArgs;
5838   bool InitializationFailed = false;
5839   bool ContainsValueDependentExpr = false;
5840   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5841     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5842         !cast<CXXMethodDecl>(Function)->isStatic() &&
5843         !isa<CXXConstructorDecl>(Function)) {
5844       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5845       ExprResult R =
5846         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5847                                             Method, Method);
5848       if (R.isInvalid()) {
5849         InitializationFailed = true;
5850         break;
5851       }
5852       ContainsValueDependentExpr |= R.get()->isValueDependent();
5853       ConvertedArgs.push_back(R.get());
5854     } else {
5855       ExprResult R =
5856         PerformCopyInitialization(InitializedEntity::InitializeParameter(
5857                                                 Context,
5858                                                 Function->getParamDecl(i)),
5859                                   SourceLocation(),
5860                                   Args[i]);
5861       if (R.isInvalid()) {
5862         InitializationFailed = true;
5863         break;
5864       }
5865       ContainsValueDependentExpr |= R.get()->isValueDependent();
5866       ConvertedArgs.push_back(R.get());
5867     }
5868   }
5869 
5870   if (InitializationFailed || Trap.hasErrorOccurred())
5871     return cast<EnableIfAttr>(Attrs[0]);
5872 
5873   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5874     APValue Result;
5875     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5876     if (EIA->getCond()->isValueDependent()) {
5877       // Don't even try now, we'll examine it after instantiation.
5878       continue;
5879     }
5880 
5881     if (!EIA->getCond()->EvaluateWithSubstitution(
5882             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5883       if (!ContainsValueDependentExpr)
5884         return EIA;
5885     } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
5886       return EIA;
5887     }
5888   }
5889   return nullptr;
5890 }
5891 
5892 /// \brief Add all of the function declarations in the given function set to
5893 /// the overload candidate set.
5894 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5895                                  ArrayRef<Expr *> Args,
5896                                  OverloadCandidateSet& CandidateSet,
5897                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5898                                  bool SuppressUserConversions,
5899                                  bool PartialOverloading) {
5900   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5901     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5902     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5903       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5904         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5905                            cast<CXXMethodDecl>(FD)->getParent(),
5906                            Args[0]->getType(), Args[0]->Classify(Context),
5907                            Args.slice(1), CandidateSet,
5908                            SuppressUserConversions, PartialOverloading);
5909       else
5910         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5911                              SuppressUserConversions, PartialOverloading);
5912     } else {
5913       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5914       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5915           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5916         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5917                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5918                                    ExplicitTemplateArgs,
5919                                    Args[0]->getType(),
5920                                    Args[0]->Classify(Context), Args.slice(1),
5921                                    CandidateSet, SuppressUserConversions,
5922                                    PartialOverloading);
5923       else
5924         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5925                                      ExplicitTemplateArgs, Args,
5926                                      CandidateSet, SuppressUserConversions,
5927                                      PartialOverloading);
5928     }
5929   }
5930 }
5931 
5932 /// AddMethodCandidate - Adds a named decl (which is some kind of
5933 /// method) as a method candidate to the given overload set.
5934 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5935                               QualType ObjectType,
5936                               Expr::Classification ObjectClassification,
5937                               ArrayRef<Expr *> Args,
5938                               OverloadCandidateSet& CandidateSet,
5939                               bool SuppressUserConversions) {
5940   NamedDecl *Decl = FoundDecl.getDecl();
5941   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5942 
5943   if (isa<UsingShadowDecl>(Decl))
5944     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5945 
5946   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5947     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5948            "Expected a member function template");
5949     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5950                                /*ExplicitArgs*/ nullptr,
5951                                ObjectType, ObjectClassification,
5952                                Args, CandidateSet,
5953                                SuppressUserConversions);
5954   } else {
5955     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5956                        ObjectType, ObjectClassification,
5957                        Args,
5958                        CandidateSet, SuppressUserConversions);
5959   }
5960 }
5961 
5962 /// AddMethodCandidate - Adds the given C++ member function to the set
5963 /// of candidate functions, using the given function call arguments
5964 /// and the object argument (@c Object). For example, in a call
5965 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5966 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5967 /// allow user-defined conversions via constructors or conversion
5968 /// operators.
5969 void
5970 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5971                          CXXRecordDecl *ActingContext, QualType ObjectType,
5972                          Expr::Classification ObjectClassification,
5973                          ArrayRef<Expr *> Args,
5974                          OverloadCandidateSet &CandidateSet,
5975                          bool SuppressUserConversions,
5976                          bool PartialOverloading) {
5977   const FunctionProtoType *Proto
5978     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5979   assert(Proto && "Methods without a prototype cannot be overloaded");
5980   assert(!isa<CXXConstructorDecl>(Method) &&
5981          "Use AddOverloadCandidate for constructors");
5982 
5983   if (!CandidateSet.isNewCandidate(Method))
5984     return;
5985 
5986   // C++11 [class.copy]p23: [DR1402]
5987   //   A defaulted move assignment operator that is defined as deleted is
5988   //   ignored by overload resolution.
5989   if (Method->isDefaulted() && Method->isDeleted() &&
5990       Method->isMoveAssignmentOperator())
5991     return;
5992 
5993   // Overload resolution is always an unevaluated context.
5994   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5995 
5996   // Add this candidate
5997   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5998   Candidate.FoundDecl = FoundDecl;
5999   Candidate.Function = Method;
6000   Candidate.IsSurrogate = false;
6001   Candidate.IgnoreObjectArgument = false;
6002   Candidate.ExplicitCallArguments = Args.size();
6003 
6004   unsigned NumParams = Proto->getNumParams();
6005 
6006   // (C++ 13.3.2p2): A candidate function having fewer than m
6007   // parameters is viable only if it has an ellipsis in its parameter
6008   // list (8.3.5).
6009   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6010       !Proto->isVariadic()) {
6011     Candidate.Viable = false;
6012     Candidate.FailureKind = ovl_fail_too_many_arguments;
6013     return;
6014   }
6015 
6016   // (C++ 13.3.2p2): A candidate function having more than m parameters
6017   // is viable only if the (m+1)st parameter has a default argument
6018   // (8.3.6). For the purposes of overload resolution, the
6019   // parameter list is truncated on the right, so that there are
6020   // exactly m parameters.
6021   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6022   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6023     // Not enough arguments.
6024     Candidate.Viable = false;
6025     Candidate.FailureKind = ovl_fail_too_few_arguments;
6026     return;
6027   }
6028 
6029   Candidate.Viable = true;
6030 
6031   if (Method->isStatic() || ObjectType.isNull())
6032     // The implicit object argument is ignored.
6033     Candidate.IgnoreObjectArgument = true;
6034   else {
6035     // Determine the implicit conversion sequence for the object
6036     // parameter.
6037     Candidate.Conversions[0]
6038       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6039                                         Method, ActingContext);
6040     if (Candidate.Conversions[0].isBad()) {
6041       Candidate.Viable = false;
6042       Candidate.FailureKind = ovl_fail_bad_conversion;
6043       return;
6044     }
6045   }
6046 
6047   // (CUDA B.1): Check for invalid calls between targets.
6048   if (getLangOpts().CUDA)
6049     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6050       if (CheckCUDATarget(Caller, Method)) {
6051         Candidate.Viable = false;
6052         Candidate.FailureKind = ovl_fail_bad_target;
6053         return;
6054       }
6055 
6056   // Determine the implicit conversion sequences for each of the
6057   // arguments.
6058   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6059     if (ArgIdx < NumParams) {
6060       // (C++ 13.3.2p3): for F to be a viable function, there shall
6061       // exist for each argument an implicit conversion sequence
6062       // (13.3.3.1) that converts that argument to the corresponding
6063       // parameter of F.
6064       QualType ParamType = Proto->getParamType(ArgIdx);
6065       Candidate.Conversions[ArgIdx + 1]
6066         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6067                                 SuppressUserConversions,
6068                                 /*InOverloadResolution=*/true,
6069                                 /*AllowObjCWritebackConversion=*/
6070                                   getLangOpts().ObjCAutoRefCount);
6071       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6072         Candidate.Viable = false;
6073         Candidate.FailureKind = ovl_fail_bad_conversion;
6074         return;
6075       }
6076     } else {
6077       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6078       // argument for which there is no corresponding parameter is
6079       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6080       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6081     }
6082   }
6083 
6084   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6085     Candidate.Viable = false;
6086     Candidate.FailureKind = ovl_fail_enable_if;
6087     Candidate.DeductionFailure.Data = FailedAttr;
6088     return;
6089   }
6090 }
6091 
6092 /// \brief Add a C++ member function template as a candidate to the candidate
6093 /// set, using template argument deduction to produce an appropriate member
6094 /// function template specialization.
6095 void
6096 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6097                                  DeclAccessPair FoundDecl,
6098                                  CXXRecordDecl *ActingContext,
6099                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6100                                  QualType ObjectType,
6101                                  Expr::Classification ObjectClassification,
6102                                  ArrayRef<Expr *> Args,
6103                                  OverloadCandidateSet& CandidateSet,
6104                                  bool SuppressUserConversions,
6105                                  bool PartialOverloading) {
6106   if (!CandidateSet.isNewCandidate(MethodTmpl))
6107     return;
6108 
6109   // C++ [over.match.funcs]p7:
6110   //   In each case where a candidate is a function template, candidate
6111   //   function template specializations are generated using template argument
6112   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6113   //   candidate functions in the usual way.113) A given name can refer to one
6114   //   or more function templates and also to a set of overloaded non-template
6115   //   functions. In such a case, the candidate functions generated from each
6116   //   function template are combined with the set of non-template candidate
6117   //   functions.
6118   TemplateDeductionInfo Info(CandidateSet.getLocation());
6119   FunctionDecl *Specialization = nullptr;
6120   if (TemplateDeductionResult Result
6121       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6122                                 Specialization, Info, PartialOverloading)) {
6123     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6124     Candidate.FoundDecl = FoundDecl;
6125     Candidate.Function = MethodTmpl->getTemplatedDecl();
6126     Candidate.Viable = false;
6127     Candidate.FailureKind = ovl_fail_bad_deduction;
6128     Candidate.IsSurrogate = false;
6129     Candidate.IgnoreObjectArgument = false;
6130     Candidate.ExplicitCallArguments = Args.size();
6131     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6132                                                           Info);
6133     return;
6134   }
6135 
6136   // Add the function template specialization produced by template argument
6137   // deduction as a candidate.
6138   assert(Specialization && "Missing member function template specialization?");
6139   assert(isa<CXXMethodDecl>(Specialization) &&
6140          "Specialization is not a member function?");
6141   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6142                      ActingContext, ObjectType, ObjectClassification, Args,
6143                      CandidateSet, SuppressUserConversions, PartialOverloading);
6144 }
6145 
6146 /// \brief Add a C++ function template specialization as a candidate
6147 /// in the candidate set, using template argument deduction to produce
6148 /// an appropriate function template specialization.
6149 void
6150 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6151                                    DeclAccessPair FoundDecl,
6152                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6153                                    ArrayRef<Expr *> Args,
6154                                    OverloadCandidateSet& CandidateSet,
6155                                    bool SuppressUserConversions,
6156                                    bool PartialOverloading) {
6157   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6158     return;
6159 
6160   // C++ [over.match.funcs]p7:
6161   //   In each case where a candidate is a function template, candidate
6162   //   function template specializations are generated using template argument
6163   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6164   //   candidate functions in the usual way.113) A given name can refer to one
6165   //   or more function templates and also to a set of overloaded non-template
6166   //   functions. In such a case, the candidate functions generated from each
6167   //   function template are combined with the set of non-template candidate
6168   //   functions.
6169   TemplateDeductionInfo Info(CandidateSet.getLocation());
6170   FunctionDecl *Specialization = nullptr;
6171   if (TemplateDeductionResult Result
6172         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6173                                   Specialization, Info, PartialOverloading)) {
6174     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6175     Candidate.FoundDecl = FoundDecl;
6176     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6177     Candidate.Viable = false;
6178     Candidate.FailureKind = ovl_fail_bad_deduction;
6179     Candidate.IsSurrogate = false;
6180     Candidate.IgnoreObjectArgument = false;
6181     Candidate.ExplicitCallArguments = Args.size();
6182     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6183                                                           Info);
6184     return;
6185   }
6186 
6187   // Add the function template specialization produced by template argument
6188   // deduction as a candidate.
6189   assert(Specialization && "Missing function template specialization?");
6190   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6191                        SuppressUserConversions, PartialOverloading);
6192 }
6193 
6194 /// Determine whether this is an allowable conversion from the result
6195 /// of an explicit conversion operator to the expected type, per C++
6196 /// [over.match.conv]p1 and [over.match.ref]p1.
6197 ///
6198 /// \param ConvType The return type of the conversion function.
6199 ///
6200 /// \param ToType The type we are converting to.
6201 ///
6202 /// \param AllowObjCPointerConversion Allow a conversion from one
6203 /// Objective-C pointer to another.
6204 ///
6205 /// \returns true if the conversion is allowable, false otherwise.
6206 static bool isAllowableExplicitConversion(Sema &S,
6207                                           QualType ConvType, QualType ToType,
6208                                           bool AllowObjCPointerConversion) {
6209   QualType ToNonRefType = ToType.getNonReferenceType();
6210 
6211   // Easy case: the types are the same.
6212   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6213     return true;
6214 
6215   // Allow qualification conversions.
6216   bool ObjCLifetimeConversion;
6217   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6218                                   ObjCLifetimeConversion))
6219     return true;
6220 
6221   // If we're not allowed to consider Objective-C pointer conversions,
6222   // we're done.
6223   if (!AllowObjCPointerConversion)
6224     return false;
6225 
6226   // Is this an Objective-C pointer conversion?
6227   bool IncompatibleObjC = false;
6228   QualType ConvertedType;
6229   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6230                                    IncompatibleObjC);
6231 }
6232 
6233 /// AddConversionCandidate - Add a C++ conversion function as a
6234 /// candidate in the candidate set (C++ [over.match.conv],
6235 /// C++ [over.match.copy]). From is the expression we're converting from,
6236 /// and ToType is the type that we're eventually trying to convert to
6237 /// (which may or may not be the same type as the type that the
6238 /// conversion function produces).
6239 void
6240 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6241                              DeclAccessPair FoundDecl,
6242                              CXXRecordDecl *ActingContext,
6243                              Expr *From, QualType ToType,
6244                              OverloadCandidateSet& CandidateSet,
6245                              bool AllowObjCConversionOnExplicit) {
6246   assert(!Conversion->getDescribedFunctionTemplate() &&
6247          "Conversion function templates use AddTemplateConversionCandidate");
6248   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6249   if (!CandidateSet.isNewCandidate(Conversion))
6250     return;
6251 
6252   // If the conversion function has an undeduced return type, trigger its
6253   // deduction now.
6254   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6255     if (DeduceReturnType(Conversion, From->getExprLoc()))
6256       return;
6257     ConvType = Conversion->getConversionType().getNonReferenceType();
6258   }
6259 
6260   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6261   // operator is only a candidate if its return type is the target type or
6262   // can be converted to the target type with a qualification conversion.
6263   if (Conversion->isExplicit() &&
6264       !isAllowableExplicitConversion(*this, ConvType, ToType,
6265                                      AllowObjCConversionOnExplicit))
6266     return;
6267 
6268   // Overload resolution is always an unevaluated context.
6269   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6270 
6271   // Add this candidate
6272   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6273   Candidate.FoundDecl = FoundDecl;
6274   Candidate.Function = Conversion;
6275   Candidate.IsSurrogate = false;
6276   Candidate.IgnoreObjectArgument = false;
6277   Candidate.FinalConversion.setAsIdentityConversion();
6278   Candidate.FinalConversion.setFromType(ConvType);
6279   Candidate.FinalConversion.setAllToTypes(ToType);
6280   Candidate.Viable = true;
6281   Candidate.ExplicitCallArguments = 1;
6282 
6283   // C++ [over.match.funcs]p4:
6284   //   For conversion functions, the function is considered to be a member of
6285   //   the class of the implicit implied object argument for the purpose of
6286   //   defining the type of the implicit object parameter.
6287   //
6288   // Determine the implicit conversion sequence for the implicit
6289   // object parameter.
6290   QualType ImplicitParamType = From->getType();
6291   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6292     ImplicitParamType = FromPtrType->getPointeeType();
6293   CXXRecordDecl *ConversionContext
6294     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6295 
6296   Candidate.Conversions[0]
6297     = TryObjectArgumentInitialization(*this, From->getType(),
6298                                       From->Classify(Context),
6299                                       Conversion, ConversionContext);
6300 
6301   if (Candidate.Conversions[0].isBad()) {
6302     Candidate.Viable = false;
6303     Candidate.FailureKind = ovl_fail_bad_conversion;
6304     return;
6305   }
6306 
6307   // We won't go through a user-defined type conversion function to convert a
6308   // derived to base as such conversions are given Conversion Rank. They only
6309   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6310   QualType FromCanon
6311     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6312   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6313   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6314     Candidate.Viable = false;
6315     Candidate.FailureKind = ovl_fail_trivial_conversion;
6316     return;
6317   }
6318 
6319   // To determine what the conversion from the result of calling the
6320   // conversion function to the type we're eventually trying to
6321   // convert to (ToType), we need to synthesize a call to the
6322   // conversion function and attempt copy initialization from it. This
6323   // makes sure that we get the right semantics with respect to
6324   // lvalues/rvalues and the type. Fortunately, we can allocate this
6325   // call on the stack and we don't need its arguments to be
6326   // well-formed.
6327   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6328                             VK_LValue, From->getLocStart());
6329   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6330                                 Context.getPointerType(Conversion->getType()),
6331                                 CK_FunctionToPointerDecay,
6332                                 &ConversionRef, VK_RValue);
6333 
6334   QualType ConversionType = Conversion->getConversionType();
6335   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6336     Candidate.Viable = false;
6337     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6338     return;
6339   }
6340 
6341   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6342 
6343   // Note that it is safe to allocate CallExpr on the stack here because
6344   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6345   // allocator).
6346   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6347   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6348                 From->getLocStart());
6349   ImplicitConversionSequence ICS =
6350     TryCopyInitialization(*this, &Call, ToType,
6351                           /*SuppressUserConversions=*/true,
6352                           /*InOverloadResolution=*/false,
6353                           /*AllowObjCWritebackConversion=*/false);
6354 
6355   switch (ICS.getKind()) {
6356   case ImplicitConversionSequence::StandardConversion:
6357     Candidate.FinalConversion = ICS.Standard;
6358 
6359     // C++ [over.ics.user]p3:
6360     //   If the user-defined conversion is specified by a specialization of a
6361     //   conversion function template, the second standard conversion sequence
6362     //   shall have exact match rank.
6363     if (Conversion->getPrimaryTemplate() &&
6364         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6365       Candidate.Viable = false;
6366       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6367       return;
6368     }
6369 
6370     // C++0x [dcl.init.ref]p5:
6371     //    In the second case, if the reference is an rvalue reference and
6372     //    the second standard conversion sequence of the user-defined
6373     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6374     //    program is ill-formed.
6375     if (ToType->isRValueReferenceType() &&
6376         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6377       Candidate.Viable = false;
6378       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6379       return;
6380     }
6381     break;
6382 
6383   case ImplicitConversionSequence::BadConversion:
6384     Candidate.Viable = false;
6385     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6386     return;
6387 
6388   default:
6389     llvm_unreachable(
6390            "Can only end up with a standard conversion sequence or failure");
6391   }
6392 
6393   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6394     Candidate.Viable = false;
6395     Candidate.FailureKind = ovl_fail_enable_if;
6396     Candidate.DeductionFailure.Data = FailedAttr;
6397     return;
6398   }
6399 }
6400 
6401 /// \brief Adds a conversion function template specialization
6402 /// candidate to the overload set, using template argument deduction
6403 /// to deduce the template arguments of the conversion function
6404 /// template from the type that we are converting to (C++
6405 /// [temp.deduct.conv]).
6406 void
6407 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6408                                      DeclAccessPair FoundDecl,
6409                                      CXXRecordDecl *ActingDC,
6410                                      Expr *From, QualType ToType,
6411                                      OverloadCandidateSet &CandidateSet,
6412                                      bool AllowObjCConversionOnExplicit) {
6413   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6414          "Only conversion function templates permitted here");
6415 
6416   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6417     return;
6418 
6419   TemplateDeductionInfo Info(CandidateSet.getLocation());
6420   CXXConversionDecl *Specialization = nullptr;
6421   if (TemplateDeductionResult Result
6422         = DeduceTemplateArguments(FunctionTemplate, ToType,
6423                                   Specialization, Info)) {
6424     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6425     Candidate.FoundDecl = FoundDecl;
6426     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6427     Candidate.Viable = false;
6428     Candidate.FailureKind = ovl_fail_bad_deduction;
6429     Candidate.IsSurrogate = false;
6430     Candidate.IgnoreObjectArgument = false;
6431     Candidate.ExplicitCallArguments = 1;
6432     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6433                                                           Info);
6434     return;
6435   }
6436 
6437   // Add the conversion function template specialization produced by
6438   // template argument deduction as a candidate.
6439   assert(Specialization && "Missing function template specialization?");
6440   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6441                          CandidateSet, AllowObjCConversionOnExplicit);
6442 }
6443 
6444 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6445 /// converts the given @c Object to a function pointer via the
6446 /// conversion function @c Conversion, and then attempts to call it
6447 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6448 /// the type of function that we'll eventually be calling.
6449 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6450                                  DeclAccessPair FoundDecl,
6451                                  CXXRecordDecl *ActingContext,
6452                                  const FunctionProtoType *Proto,
6453                                  Expr *Object,
6454                                  ArrayRef<Expr *> Args,
6455                                  OverloadCandidateSet& CandidateSet) {
6456   if (!CandidateSet.isNewCandidate(Conversion))
6457     return;
6458 
6459   // Overload resolution is always an unevaluated context.
6460   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6461 
6462   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6463   Candidate.FoundDecl = FoundDecl;
6464   Candidate.Function = nullptr;
6465   Candidate.Surrogate = Conversion;
6466   Candidate.Viable = true;
6467   Candidate.IsSurrogate = true;
6468   Candidate.IgnoreObjectArgument = false;
6469   Candidate.ExplicitCallArguments = Args.size();
6470 
6471   // Determine the implicit conversion sequence for the implicit
6472   // object parameter.
6473   ImplicitConversionSequence ObjectInit
6474     = TryObjectArgumentInitialization(*this, Object->getType(),
6475                                       Object->Classify(Context),
6476                                       Conversion, ActingContext);
6477   if (ObjectInit.isBad()) {
6478     Candidate.Viable = false;
6479     Candidate.FailureKind = ovl_fail_bad_conversion;
6480     Candidate.Conversions[0] = ObjectInit;
6481     return;
6482   }
6483 
6484   // The first conversion is actually a user-defined conversion whose
6485   // first conversion is ObjectInit's standard conversion (which is
6486   // effectively a reference binding). Record it as such.
6487   Candidate.Conversions[0].setUserDefined();
6488   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6489   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6490   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6491   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6492   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6493   Candidate.Conversions[0].UserDefined.After
6494     = Candidate.Conversions[0].UserDefined.Before;
6495   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6496 
6497   // Find the
6498   unsigned NumParams = Proto->getNumParams();
6499 
6500   // (C++ 13.3.2p2): A candidate function having fewer than m
6501   // parameters is viable only if it has an ellipsis in its parameter
6502   // list (8.3.5).
6503   if (Args.size() > NumParams && !Proto->isVariadic()) {
6504     Candidate.Viable = false;
6505     Candidate.FailureKind = ovl_fail_too_many_arguments;
6506     return;
6507   }
6508 
6509   // Function types don't have any default arguments, so just check if
6510   // we have enough arguments.
6511   if (Args.size() < NumParams) {
6512     // Not enough arguments.
6513     Candidate.Viable = false;
6514     Candidate.FailureKind = ovl_fail_too_few_arguments;
6515     return;
6516   }
6517 
6518   // Determine the implicit conversion sequences for each of the
6519   // arguments.
6520   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6521     if (ArgIdx < NumParams) {
6522       // (C++ 13.3.2p3): for F to be a viable function, there shall
6523       // exist for each argument an implicit conversion sequence
6524       // (13.3.3.1) that converts that argument to the corresponding
6525       // parameter of F.
6526       QualType ParamType = Proto->getParamType(ArgIdx);
6527       Candidate.Conversions[ArgIdx + 1]
6528         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6529                                 /*SuppressUserConversions=*/false,
6530                                 /*InOverloadResolution=*/false,
6531                                 /*AllowObjCWritebackConversion=*/
6532                                   getLangOpts().ObjCAutoRefCount);
6533       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6534         Candidate.Viable = false;
6535         Candidate.FailureKind = ovl_fail_bad_conversion;
6536         return;
6537       }
6538     } else {
6539       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6540       // argument for which there is no corresponding parameter is
6541       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6542       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6543     }
6544   }
6545 
6546   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6547     Candidate.Viable = false;
6548     Candidate.FailureKind = ovl_fail_enable_if;
6549     Candidate.DeductionFailure.Data = FailedAttr;
6550     return;
6551   }
6552 }
6553 
6554 /// \brief Add overload candidates for overloaded operators that are
6555 /// member functions.
6556 ///
6557 /// Add the overloaded operator candidates that are member functions
6558 /// for the operator Op that was used in an operator expression such
6559 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6560 /// CandidateSet will store the added overload candidates. (C++
6561 /// [over.match.oper]).
6562 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6563                                        SourceLocation OpLoc,
6564                                        ArrayRef<Expr *> Args,
6565                                        OverloadCandidateSet& CandidateSet,
6566                                        SourceRange OpRange) {
6567   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6568 
6569   // C++ [over.match.oper]p3:
6570   //   For a unary operator @ with an operand of a type whose
6571   //   cv-unqualified version is T1, and for a binary operator @ with
6572   //   a left operand of a type whose cv-unqualified version is T1 and
6573   //   a right operand of a type whose cv-unqualified version is T2,
6574   //   three sets of candidate functions, designated member
6575   //   candidates, non-member candidates and built-in candidates, are
6576   //   constructed as follows:
6577   QualType T1 = Args[0]->getType();
6578 
6579   //     -- If T1 is a complete class type or a class currently being
6580   //        defined, the set of member candidates is the result of the
6581   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6582   //        the set of member candidates is empty.
6583   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6584     // Complete the type if it can be completed.
6585     RequireCompleteType(OpLoc, T1, 0);
6586     // If the type is neither complete nor being defined, bail out now.
6587     if (!T1Rec->getDecl()->getDefinition())
6588       return;
6589 
6590     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6591     LookupQualifiedName(Operators, T1Rec->getDecl());
6592     Operators.suppressDiagnostics();
6593 
6594     for (LookupResult::iterator Oper = Operators.begin(),
6595                              OperEnd = Operators.end();
6596          Oper != OperEnd;
6597          ++Oper)
6598       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6599                          Args[0]->Classify(Context),
6600                          Args.slice(1),
6601                          CandidateSet,
6602                          /* SuppressUserConversions = */ false);
6603   }
6604 }
6605 
6606 /// AddBuiltinCandidate - Add a candidate for a built-in
6607 /// operator. ResultTy and ParamTys are the result and parameter types
6608 /// of the built-in candidate, respectively. Args and NumArgs are the
6609 /// arguments being passed to the candidate. IsAssignmentOperator
6610 /// should be true when this built-in candidate is an assignment
6611 /// operator. NumContextualBoolArguments is the number of arguments
6612 /// (at the beginning of the argument list) that will be contextually
6613 /// converted to bool.
6614 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6615                                ArrayRef<Expr *> Args,
6616                                OverloadCandidateSet& CandidateSet,
6617                                bool IsAssignmentOperator,
6618                                unsigned NumContextualBoolArguments) {
6619   // Overload resolution is always an unevaluated context.
6620   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6621 
6622   // Add this candidate
6623   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6624   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6625   Candidate.Function = nullptr;
6626   Candidate.IsSurrogate = false;
6627   Candidate.IgnoreObjectArgument = false;
6628   Candidate.BuiltinTypes.ResultTy = ResultTy;
6629   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6630     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6631 
6632   // Determine the implicit conversion sequences for each of the
6633   // arguments.
6634   Candidate.Viable = true;
6635   Candidate.ExplicitCallArguments = Args.size();
6636   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6637     // C++ [over.match.oper]p4:
6638     //   For the built-in assignment operators, conversions of the
6639     //   left operand are restricted as follows:
6640     //     -- no temporaries are introduced to hold the left operand, and
6641     //     -- no user-defined conversions are applied to the left
6642     //        operand to achieve a type match with the left-most
6643     //        parameter of a built-in candidate.
6644     //
6645     // We block these conversions by turning off user-defined
6646     // conversions, since that is the only way that initialization of
6647     // a reference to a non-class type can occur from something that
6648     // is not of the same type.
6649     if (ArgIdx < NumContextualBoolArguments) {
6650       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6651              "Contextual conversion to bool requires bool type");
6652       Candidate.Conversions[ArgIdx]
6653         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6654     } else {
6655       Candidate.Conversions[ArgIdx]
6656         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6657                                 ArgIdx == 0 && IsAssignmentOperator,
6658                                 /*InOverloadResolution=*/false,
6659                                 /*AllowObjCWritebackConversion=*/
6660                                   getLangOpts().ObjCAutoRefCount);
6661     }
6662     if (Candidate.Conversions[ArgIdx].isBad()) {
6663       Candidate.Viable = false;
6664       Candidate.FailureKind = ovl_fail_bad_conversion;
6665       break;
6666     }
6667   }
6668 }
6669 
6670 namespace {
6671 
6672 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6673 /// candidate operator functions for built-in operators (C++
6674 /// [over.built]). The types are separated into pointer types and
6675 /// enumeration types.
6676 class BuiltinCandidateTypeSet  {
6677   /// TypeSet - A set of types.
6678   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6679 
6680   /// PointerTypes - The set of pointer types that will be used in the
6681   /// built-in candidates.
6682   TypeSet PointerTypes;
6683 
6684   /// MemberPointerTypes - The set of member pointer types that will be
6685   /// used in the built-in candidates.
6686   TypeSet MemberPointerTypes;
6687 
6688   /// EnumerationTypes - The set of enumeration types that will be
6689   /// used in the built-in candidates.
6690   TypeSet EnumerationTypes;
6691 
6692   /// \brief The set of vector types that will be used in the built-in
6693   /// candidates.
6694   TypeSet VectorTypes;
6695 
6696   /// \brief A flag indicating non-record types are viable candidates
6697   bool HasNonRecordTypes;
6698 
6699   /// \brief A flag indicating whether either arithmetic or enumeration types
6700   /// were present in the candidate set.
6701   bool HasArithmeticOrEnumeralTypes;
6702 
6703   /// \brief A flag indicating whether the nullptr type was present in the
6704   /// candidate set.
6705   bool HasNullPtrType;
6706 
6707   /// Sema - The semantic analysis instance where we are building the
6708   /// candidate type set.
6709   Sema &SemaRef;
6710 
6711   /// Context - The AST context in which we will build the type sets.
6712   ASTContext &Context;
6713 
6714   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6715                                                const Qualifiers &VisibleQuals);
6716   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6717 
6718 public:
6719   /// iterator - Iterates through the types that are part of the set.
6720   typedef TypeSet::iterator iterator;
6721 
6722   BuiltinCandidateTypeSet(Sema &SemaRef)
6723     : HasNonRecordTypes(false),
6724       HasArithmeticOrEnumeralTypes(false),
6725       HasNullPtrType(false),
6726       SemaRef(SemaRef),
6727       Context(SemaRef.Context) { }
6728 
6729   void AddTypesConvertedFrom(QualType Ty,
6730                              SourceLocation Loc,
6731                              bool AllowUserConversions,
6732                              bool AllowExplicitConversions,
6733                              const Qualifiers &VisibleTypeConversionsQuals);
6734 
6735   /// pointer_begin - First pointer type found;
6736   iterator pointer_begin() { return PointerTypes.begin(); }
6737 
6738   /// pointer_end - Past the last pointer type found;
6739   iterator pointer_end() { return PointerTypes.end(); }
6740 
6741   /// member_pointer_begin - First member pointer type found;
6742   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6743 
6744   /// member_pointer_end - Past the last member pointer type found;
6745   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6746 
6747   /// enumeration_begin - First enumeration type found;
6748   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6749 
6750   /// enumeration_end - Past the last enumeration type found;
6751   iterator enumeration_end() { return EnumerationTypes.end(); }
6752 
6753   iterator vector_begin() { return VectorTypes.begin(); }
6754   iterator vector_end() { return VectorTypes.end(); }
6755 
6756   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6757   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6758   bool hasNullPtrType() const { return HasNullPtrType; }
6759 };
6760 
6761 } // end anonymous namespace
6762 
6763 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6764 /// the set of pointer types along with any more-qualified variants of
6765 /// that type. For example, if @p Ty is "int const *", this routine
6766 /// will add "int const *", "int const volatile *", "int const
6767 /// restrict *", and "int const volatile restrict *" to the set of
6768 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6769 /// false otherwise.
6770 ///
6771 /// FIXME: what to do about extended qualifiers?
6772 bool
6773 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6774                                              const Qualifiers &VisibleQuals) {
6775 
6776   // Insert this type.
6777   if (!PointerTypes.insert(Ty).second)
6778     return false;
6779 
6780   QualType PointeeTy;
6781   const PointerType *PointerTy = Ty->getAs<PointerType>();
6782   bool buildObjCPtr = false;
6783   if (!PointerTy) {
6784     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6785     PointeeTy = PTy->getPointeeType();
6786     buildObjCPtr = true;
6787   } else {
6788     PointeeTy = PointerTy->getPointeeType();
6789   }
6790 
6791   // Don't add qualified variants of arrays. For one, they're not allowed
6792   // (the qualifier would sink to the element type), and for another, the
6793   // only overload situation where it matters is subscript or pointer +- int,
6794   // and those shouldn't have qualifier variants anyway.
6795   if (PointeeTy->isArrayType())
6796     return true;
6797 
6798   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6799   bool hasVolatile = VisibleQuals.hasVolatile();
6800   bool hasRestrict = VisibleQuals.hasRestrict();
6801 
6802   // Iterate through all strict supersets of BaseCVR.
6803   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6804     if ((CVR | BaseCVR) != CVR) continue;
6805     // Skip over volatile if no volatile found anywhere in the types.
6806     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6807 
6808     // Skip over restrict if no restrict found anywhere in the types, or if
6809     // the type cannot be restrict-qualified.
6810     if ((CVR & Qualifiers::Restrict) &&
6811         (!hasRestrict ||
6812          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6813       continue;
6814 
6815     // Build qualified pointee type.
6816     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6817 
6818     // Build qualified pointer type.
6819     QualType QPointerTy;
6820     if (!buildObjCPtr)
6821       QPointerTy = Context.getPointerType(QPointeeTy);
6822     else
6823       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6824 
6825     // Insert qualified pointer type.
6826     PointerTypes.insert(QPointerTy);
6827   }
6828 
6829   return true;
6830 }
6831 
6832 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6833 /// to the set of pointer types along with any more-qualified variants of
6834 /// that type. For example, if @p Ty is "int const *", this routine
6835 /// will add "int const *", "int const volatile *", "int const
6836 /// restrict *", and "int const volatile restrict *" to the set of
6837 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6838 /// false otherwise.
6839 ///
6840 /// FIXME: what to do about extended qualifiers?
6841 bool
6842 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6843     QualType Ty) {
6844   // Insert this type.
6845   if (!MemberPointerTypes.insert(Ty).second)
6846     return false;
6847 
6848   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6849   assert(PointerTy && "type was not a member pointer type!");
6850 
6851   QualType PointeeTy = PointerTy->getPointeeType();
6852   // Don't add qualified variants of arrays. For one, they're not allowed
6853   // (the qualifier would sink to the element type), and for another, the
6854   // only overload situation where it matters is subscript or pointer +- int,
6855   // and those shouldn't have qualifier variants anyway.
6856   if (PointeeTy->isArrayType())
6857     return true;
6858   const Type *ClassTy = PointerTy->getClass();
6859 
6860   // Iterate through all strict supersets of the pointee type's CVR
6861   // qualifiers.
6862   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6863   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6864     if ((CVR | BaseCVR) != CVR) continue;
6865 
6866     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6867     MemberPointerTypes.insert(
6868       Context.getMemberPointerType(QPointeeTy, ClassTy));
6869   }
6870 
6871   return true;
6872 }
6873 
6874 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6875 /// Ty can be implicit converted to the given set of @p Types. We're
6876 /// primarily interested in pointer types and enumeration types. We also
6877 /// take member pointer types, for the conditional operator.
6878 /// AllowUserConversions is true if we should look at the conversion
6879 /// functions of a class type, and AllowExplicitConversions if we
6880 /// should also include the explicit conversion functions of a class
6881 /// type.
6882 void
6883 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6884                                                SourceLocation Loc,
6885                                                bool AllowUserConversions,
6886                                                bool AllowExplicitConversions,
6887                                                const Qualifiers &VisibleQuals) {
6888   // Only deal with canonical types.
6889   Ty = Context.getCanonicalType(Ty);
6890 
6891   // Look through reference types; they aren't part of the type of an
6892   // expression for the purposes of conversions.
6893   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6894     Ty = RefTy->getPointeeType();
6895 
6896   // If we're dealing with an array type, decay to the pointer.
6897   if (Ty->isArrayType())
6898     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6899 
6900   // Otherwise, we don't care about qualifiers on the type.
6901   Ty = Ty.getLocalUnqualifiedType();
6902 
6903   // Flag if we ever add a non-record type.
6904   const RecordType *TyRec = Ty->getAs<RecordType>();
6905   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6906 
6907   // Flag if we encounter an arithmetic type.
6908   HasArithmeticOrEnumeralTypes =
6909     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6910 
6911   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6912     PointerTypes.insert(Ty);
6913   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6914     // Insert our type, and its more-qualified variants, into the set
6915     // of types.
6916     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6917       return;
6918   } else if (Ty->isMemberPointerType()) {
6919     // Member pointers are far easier, since the pointee can't be converted.
6920     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6921       return;
6922   } else if (Ty->isEnumeralType()) {
6923     HasArithmeticOrEnumeralTypes = true;
6924     EnumerationTypes.insert(Ty);
6925   } else if (Ty->isVectorType()) {
6926     // We treat vector types as arithmetic types in many contexts as an
6927     // extension.
6928     HasArithmeticOrEnumeralTypes = true;
6929     VectorTypes.insert(Ty);
6930   } else if (Ty->isNullPtrType()) {
6931     HasNullPtrType = true;
6932   } else if (AllowUserConversions && TyRec) {
6933     // No conversion functions in incomplete types.
6934     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6935       return;
6936 
6937     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6938     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
6939       if (isa<UsingShadowDecl>(D))
6940         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6941 
6942       // Skip conversion function templates; they don't tell us anything
6943       // about which builtin types we can convert to.
6944       if (isa<FunctionTemplateDecl>(D))
6945         continue;
6946 
6947       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6948       if (AllowExplicitConversions || !Conv->isExplicit()) {
6949         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6950                               VisibleQuals);
6951       }
6952     }
6953   }
6954 }
6955 
6956 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6957 /// the volatile- and non-volatile-qualified assignment operators for the
6958 /// given type to the candidate set.
6959 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6960                                                    QualType T,
6961                                                    ArrayRef<Expr *> Args,
6962                                     OverloadCandidateSet &CandidateSet) {
6963   QualType ParamTypes[2];
6964 
6965   // T& operator=(T&, T)
6966   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6967   ParamTypes[1] = T;
6968   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6969                         /*IsAssignmentOperator=*/true);
6970 
6971   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6972     // volatile T& operator=(volatile T&, T)
6973     ParamTypes[0]
6974       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6975     ParamTypes[1] = T;
6976     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6977                           /*IsAssignmentOperator=*/true);
6978   }
6979 }
6980 
6981 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6982 /// if any, found in visible type conversion functions found in ArgExpr's type.
6983 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6984     Qualifiers VRQuals;
6985     const RecordType *TyRec;
6986     if (const MemberPointerType *RHSMPType =
6987         ArgExpr->getType()->getAs<MemberPointerType>())
6988       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6989     else
6990       TyRec = ArgExpr->getType()->getAs<RecordType>();
6991     if (!TyRec) {
6992       // Just to be safe, assume the worst case.
6993       VRQuals.addVolatile();
6994       VRQuals.addRestrict();
6995       return VRQuals;
6996     }
6997 
6998     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6999     if (!ClassDecl->hasDefinition())
7000       return VRQuals;
7001 
7002     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7003       if (isa<UsingShadowDecl>(D))
7004         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7005       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7006         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7007         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7008           CanTy = ResTypeRef->getPointeeType();
7009         // Need to go down the pointer/mempointer chain and add qualifiers
7010         // as see them.
7011         bool done = false;
7012         while (!done) {
7013           if (CanTy.isRestrictQualified())
7014             VRQuals.addRestrict();
7015           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7016             CanTy = ResTypePtr->getPointeeType();
7017           else if (const MemberPointerType *ResTypeMPtr =
7018                 CanTy->getAs<MemberPointerType>())
7019             CanTy = ResTypeMPtr->getPointeeType();
7020           else
7021             done = true;
7022           if (CanTy.isVolatileQualified())
7023             VRQuals.addVolatile();
7024           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7025             return VRQuals;
7026         }
7027       }
7028     }
7029     return VRQuals;
7030 }
7031 
7032 namespace {
7033 
7034 /// \brief Helper class to manage the addition of builtin operator overload
7035 /// candidates. It provides shared state and utility methods used throughout
7036 /// the process, as well as a helper method to add each group of builtin
7037 /// operator overloads from the standard to a candidate set.
7038 class BuiltinOperatorOverloadBuilder {
7039   // Common instance state available to all overload candidate addition methods.
7040   Sema &S;
7041   ArrayRef<Expr *> Args;
7042   Qualifiers VisibleTypeConversionsQuals;
7043   bool HasArithmeticOrEnumeralCandidateType;
7044   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7045   OverloadCandidateSet &CandidateSet;
7046 
7047   // Define some constants used to index and iterate over the arithemetic types
7048   // provided via the getArithmeticType() method below.
7049   // The "promoted arithmetic types" are the arithmetic
7050   // types are that preserved by promotion (C++ [over.built]p2).
7051   static const unsigned FirstIntegralType = 3;
7052   static const unsigned LastIntegralType = 20;
7053   static const unsigned FirstPromotedIntegralType = 3,
7054                         LastPromotedIntegralType = 11;
7055   static const unsigned FirstPromotedArithmeticType = 0,
7056                         LastPromotedArithmeticType = 11;
7057   static const unsigned NumArithmeticTypes = 20;
7058 
7059   /// \brief Get the canonical type for a given arithmetic type index.
7060   CanQualType getArithmeticType(unsigned index) {
7061     assert(index < NumArithmeticTypes);
7062     static CanQualType ASTContext::* const
7063       ArithmeticTypes[NumArithmeticTypes] = {
7064       // Start of promoted types.
7065       &ASTContext::FloatTy,
7066       &ASTContext::DoubleTy,
7067       &ASTContext::LongDoubleTy,
7068 
7069       // Start of integral types.
7070       &ASTContext::IntTy,
7071       &ASTContext::LongTy,
7072       &ASTContext::LongLongTy,
7073       &ASTContext::Int128Ty,
7074       &ASTContext::UnsignedIntTy,
7075       &ASTContext::UnsignedLongTy,
7076       &ASTContext::UnsignedLongLongTy,
7077       &ASTContext::UnsignedInt128Ty,
7078       // End of promoted types.
7079 
7080       &ASTContext::BoolTy,
7081       &ASTContext::CharTy,
7082       &ASTContext::WCharTy,
7083       &ASTContext::Char16Ty,
7084       &ASTContext::Char32Ty,
7085       &ASTContext::SignedCharTy,
7086       &ASTContext::ShortTy,
7087       &ASTContext::UnsignedCharTy,
7088       &ASTContext::UnsignedShortTy,
7089       // End of integral types.
7090       // FIXME: What about complex? What about half?
7091     };
7092     return S.Context.*ArithmeticTypes[index];
7093   }
7094 
7095   /// \brief Gets the canonical type resulting from the usual arithemetic
7096   /// converions for the given arithmetic types.
7097   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7098     // Accelerator table for performing the usual arithmetic conversions.
7099     // The rules are basically:
7100     //   - if either is floating-point, use the wider floating-point
7101     //   - if same signedness, use the higher rank
7102     //   - if same size, use unsigned of the higher rank
7103     //   - use the larger type
7104     // These rules, together with the axiom that higher ranks are
7105     // never smaller, are sufficient to precompute all of these results
7106     // *except* when dealing with signed types of higher rank.
7107     // (we could precompute SLL x UI for all known platforms, but it's
7108     // better not to make any assumptions).
7109     // We assume that int128 has a higher rank than long long on all platforms.
7110     enum PromotedType {
7111             Dep=-1,
7112             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7113     };
7114     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7115                                         [LastPromotedArithmeticType] = {
7116 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7117 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7118 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7119 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7120 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7121 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7122 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7123 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7124 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7125 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7126 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7127     };
7128 
7129     assert(L < LastPromotedArithmeticType);
7130     assert(R < LastPromotedArithmeticType);
7131     int Idx = ConversionsTable[L][R];
7132 
7133     // Fast path: the table gives us a concrete answer.
7134     if (Idx != Dep) return getArithmeticType(Idx);
7135 
7136     // Slow path: we need to compare widths.
7137     // An invariant is that the signed type has higher rank.
7138     CanQualType LT = getArithmeticType(L),
7139                 RT = getArithmeticType(R);
7140     unsigned LW = S.Context.getIntWidth(LT),
7141              RW = S.Context.getIntWidth(RT);
7142 
7143     // If they're different widths, use the signed type.
7144     if (LW > RW) return LT;
7145     else if (LW < RW) return RT;
7146 
7147     // Otherwise, use the unsigned type of the signed type's rank.
7148     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7149     assert(L == SLL || R == SLL);
7150     return S.Context.UnsignedLongLongTy;
7151   }
7152 
7153   /// \brief Helper method to factor out the common pattern of adding overloads
7154   /// for '++' and '--' builtin operators.
7155   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7156                                            bool HasVolatile,
7157                                            bool HasRestrict) {
7158     QualType ParamTypes[2] = {
7159       S.Context.getLValueReferenceType(CandidateTy),
7160       S.Context.IntTy
7161     };
7162 
7163     // Non-volatile version.
7164     if (Args.size() == 1)
7165       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7166     else
7167       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7168 
7169     // Use a heuristic to reduce number of builtin candidates in the set:
7170     // add volatile version only if there are conversions to a volatile type.
7171     if (HasVolatile) {
7172       ParamTypes[0] =
7173         S.Context.getLValueReferenceType(
7174           S.Context.getVolatileType(CandidateTy));
7175       if (Args.size() == 1)
7176         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7177       else
7178         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7179     }
7180 
7181     // Add restrict version only if there are conversions to a restrict type
7182     // and our candidate type is a non-restrict-qualified pointer.
7183     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7184         !CandidateTy.isRestrictQualified()) {
7185       ParamTypes[0]
7186         = S.Context.getLValueReferenceType(
7187             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7188       if (Args.size() == 1)
7189         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7190       else
7191         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7192 
7193       if (HasVolatile) {
7194         ParamTypes[0]
7195           = S.Context.getLValueReferenceType(
7196               S.Context.getCVRQualifiedType(CandidateTy,
7197                                             (Qualifiers::Volatile |
7198                                              Qualifiers::Restrict)));
7199         if (Args.size() == 1)
7200           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7201         else
7202           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7203       }
7204     }
7205 
7206   }
7207 
7208 public:
7209   BuiltinOperatorOverloadBuilder(
7210     Sema &S, ArrayRef<Expr *> Args,
7211     Qualifiers VisibleTypeConversionsQuals,
7212     bool HasArithmeticOrEnumeralCandidateType,
7213     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7214     OverloadCandidateSet &CandidateSet)
7215     : S(S), Args(Args),
7216       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7217       HasArithmeticOrEnumeralCandidateType(
7218         HasArithmeticOrEnumeralCandidateType),
7219       CandidateTypes(CandidateTypes),
7220       CandidateSet(CandidateSet) {
7221     // Validate some of our static helper constants in debug builds.
7222     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7223            "Invalid first promoted integral type");
7224     assert(getArithmeticType(LastPromotedIntegralType - 1)
7225              == S.Context.UnsignedInt128Ty &&
7226            "Invalid last promoted integral type");
7227     assert(getArithmeticType(FirstPromotedArithmeticType)
7228              == S.Context.FloatTy &&
7229            "Invalid first promoted arithmetic type");
7230     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7231              == S.Context.UnsignedInt128Ty &&
7232            "Invalid last promoted arithmetic type");
7233   }
7234 
7235   // C++ [over.built]p3:
7236   //
7237   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7238   //   is either volatile or empty, there exist candidate operator
7239   //   functions of the form
7240   //
7241   //       VQ T&      operator++(VQ T&);
7242   //       T          operator++(VQ T&, int);
7243   //
7244   // C++ [over.built]p4:
7245   //
7246   //   For every pair (T, VQ), where T is an arithmetic type other
7247   //   than bool, and VQ is either volatile or empty, there exist
7248   //   candidate operator functions of the form
7249   //
7250   //       VQ T&      operator--(VQ T&);
7251   //       T          operator--(VQ T&, int);
7252   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7253     if (!HasArithmeticOrEnumeralCandidateType)
7254       return;
7255 
7256     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7257          Arith < NumArithmeticTypes; ++Arith) {
7258       addPlusPlusMinusMinusStyleOverloads(
7259         getArithmeticType(Arith),
7260         VisibleTypeConversionsQuals.hasVolatile(),
7261         VisibleTypeConversionsQuals.hasRestrict());
7262     }
7263   }
7264 
7265   // C++ [over.built]p5:
7266   //
7267   //   For every pair (T, VQ), where T is a cv-qualified or
7268   //   cv-unqualified object type, and VQ is either volatile or
7269   //   empty, there exist candidate operator functions of the form
7270   //
7271   //       T*VQ&      operator++(T*VQ&);
7272   //       T*VQ&      operator--(T*VQ&);
7273   //       T*         operator++(T*VQ&, int);
7274   //       T*         operator--(T*VQ&, int);
7275   void addPlusPlusMinusMinusPointerOverloads() {
7276     for (BuiltinCandidateTypeSet::iterator
7277               Ptr = CandidateTypes[0].pointer_begin(),
7278            PtrEnd = CandidateTypes[0].pointer_end();
7279          Ptr != PtrEnd; ++Ptr) {
7280       // Skip pointer types that aren't pointers to object types.
7281       if (!(*Ptr)->getPointeeType()->isObjectType())
7282         continue;
7283 
7284       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7285         (!(*Ptr).isVolatileQualified() &&
7286          VisibleTypeConversionsQuals.hasVolatile()),
7287         (!(*Ptr).isRestrictQualified() &&
7288          VisibleTypeConversionsQuals.hasRestrict()));
7289     }
7290   }
7291 
7292   // C++ [over.built]p6:
7293   //   For every cv-qualified or cv-unqualified object type T, there
7294   //   exist candidate operator functions of the form
7295   //
7296   //       T&         operator*(T*);
7297   //
7298   // C++ [over.built]p7:
7299   //   For every function type T that does not have cv-qualifiers or a
7300   //   ref-qualifier, there exist candidate operator functions of the form
7301   //       T&         operator*(T*);
7302   void addUnaryStarPointerOverloads() {
7303     for (BuiltinCandidateTypeSet::iterator
7304               Ptr = CandidateTypes[0].pointer_begin(),
7305            PtrEnd = CandidateTypes[0].pointer_end();
7306          Ptr != PtrEnd; ++Ptr) {
7307       QualType ParamTy = *Ptr;
7308       QualType PointeeTy = ParamTy->getPointeeType();
7309       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7310         continue;
7311 
7312       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7313         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7314           continue;
7315 
7316       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7317                             &ParamTy, Args, CandidateSet);
7318     }
7319   }
7320 
7321   // C++ [over.built]p9:
7322   //  For every promoted arithmetic type T, there exist candidate
7323   //  operator functions of the form
7324   //
7325   //       T         operator+(T);
7326   //       T         operator-(T);
7327   void addUnaryPlusOrMinusArithmeticOverloads() {
7328     if (!HasArithmeticOrEnumeralCandidateType)
7329       return;
7330 
7331     for (unsigned Arith = FirstPromotedArithmeticType;
7332          Arith < LastPromotedArithmeticType; ++Arith) {
7333       QualType ArithTy = getArithmeticType(Arith);
7334       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7335     }
7336 
7337     // Extension: We also add these operators for vector types.
7338     for (BuiltinCandidateTypeSet::iterator
7339               Vec = CandidateTypes[0].vector_begin(),
7340            VecEnd = CandidateTypes[0].vector_end();
7341          Vec != VecEnd; ++Vec) {
7342       QualType VecTy = *Vec;
7343       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7344     }
7345   }
7346 
7347   // C++ [over.built]p8:
7348   //   For every type T, there exist candidate operator functions of
7349   //   the form
7350   //
7351   //       T*         operator+(T*);
7352   void addUnaryPlusPointerOverloads() {
7353     for (BuiltinCandidateTypeSet::iterator
7354               Ptr = CandidateTypes[0].pointer_begin(),
7355            PtrEnd = CandidateTypes[0].pointer_end();
7356          Ptr != PtrEnd; ++Ptr) {
7357       QualType ParamTy = *Ptr;
7358       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7359     }
7360   }
7361 
7362   // C++ [over.built]p10:
7363   //   For every promoted integral type T, there exist candidate
7364   //   operator functions of the form
7365   //
7366   //        T         operator~(T);
7367   void addUnaryTildePromotedIntegralOverloads() {
7368     if (!HasArithmeticOrEnumeralCandidateType)
7369       return;
7370 
7371     for (unsigned Int = FirstPromotedIntegralType;
7372          Int < LastPromotedIntegralType; ++Int) {
7373       QualType IntTy = getArithmeticType(Int);
7374       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7375     }
7376 
7377     // Extension: We also add this operator for vector types.
7378     for (BuiltinCandidateTypeSet::iterator
7379               Vec = CandidateTypes[0].vector_begin(),
7380            VecEnd = CandidateTypes[0].vector_end();
7381          Vec != VecEnd; ++Vec) {
7382       QualType VecTy = *Vec;
7383       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7384     }
7385   }
7386 
7387   // C++ [over.match.oper]p16:
7388   //   For every pointer to member type T, there exist candidate operator
7389   //   functions of the form
7390   //
7391   //        bool operator==(T,T);
7392   //        bool operator!=(T,T);
7393   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7394     /// Set of (canonical) types that we've already handled.
7395     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7396 
7397     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7398       for (BuiltinCandidateTypeSet::iterator
7399                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7400              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7401            MemPtr != MemPtrEnd;
7402            ++MemPtr) {
7403         // Don't add the same builtin candidate twice.
7404         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7405           continue;
7406 
7407         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7408         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7409       }
7410     }
7411   }
7412 
7413   // C++ [over.built]p15:
7414   //
7415   //   For every T, where T is an enumeration type, a pointer type, or
7416   //   std::nullptr_t, there exist candidate operator functions of the form
7417   //
7418   //        bool       operator<(T, T);
7419   //        bool       operator>(T, T);
7420   //        bool       operator<=(T, T);
7421   //        bool       operator>=(T, T);
7422   //        bool       operator==(T, T);
7423   //        bool       operator!=(T, T);
7424   void addRelationalPointerOrEnumeralOverloads() {
7425     // C++ [over.match.oper]p3:
7426     //   [...]the built-in candidates include all of the candidate operator
7427     //   functions defined in 13.6 that, compared to the given operator, [...]
7428     //   do not have the same parameter-type-list as any non-template non-member
7429     //   candidate.
7430     //
7431     // Note that in practice, this only affects enumeration types because there
7432     // aren't any built-in candidates of record type, and a user-defined operator
7433     // must have an operand of record or enumeration type. Also, the only other
7434     // overloaded operator with enumeration arguments, operator=,
7435     // cannot be overloaded for enumeration types, so this is the only place
7436     // where we must suppress candidates like this.
7437     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7438       UserDefinedBinaryOperators;
7439 
7440     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7441       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7442           CandidateTypes[ArgIdx].enumeration_end()) {
7443         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7444                                          CEnd = CandidateSet.end();
7445              C != CEnd; ++C) {
7446           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7447             continue;
7448 
7449           if (C->Function->isFunctionTemplateSpecialization())
7450             continue;
7451 
7452           QualType FirstParamType =
7453             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7454           QualType SecondParamType =
7455             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7456 
7457           // Skip if either parameter isn't of enumeral type.
7458           if (!FirstParamType->isEnumeralType() ||
7459               !SecondParamType->isEnumeralType())
7460             continue;
7461 
7462           // Add this operator to the set of known user-defined operators.
7463           UserDefinedBinaryOperators.insert(
7464             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7465                            S.Context.getCanonicalType(SecondParamType)));
7466         }
7467       }
7468     }
7469 
7470     /// Set of (canonical) types that we've already handled.
7471     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7472 
7473     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7474       for (BuiltinCandidateTypeSet::iterator
7475                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7476              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7477            Ptr != PtrEnd; ++Ptr) {
7478         // Don't add the same builtin candidate twice.
7479         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7480           continue;
7481 
7482         QualType ParamTypes[2] = { *Ptr, *Ptr };
7483         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7484       }
7485       for (BuiltinCandidateTypeSet::iterator
7486                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7487              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7488            Enum != EnumEnd; ++Enum) {
7489         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7490 
7491         // Don't add the same builtin candidate twice, or if a user defined
7492         // candidate exists.
7493         if (!AddedTypes.insert(CanonType).second ||
7494             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7495                                                             CanonType)))
7496           continue;
7497 
7498         QualType ParamTypes[2] = { *Enum, *Enum };
7499         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7500       }
7501 
7502       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7503         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7504         if (AddedTypes.insert(NullPtrTy).second &&
7505             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7506                                                              NullPtrTy))) {
7507           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7508           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7509                                 CandidateSet);
7510         }
7511       }
7512     }
7513   }
7514 
7515   // C++ [over.built]p13:
7516   //
7517   //   For every cv-qualified or cv-unqualified object type T
7518   //   there exist candidate operator functions of the form
7519   //
7520   //      T*         operator+(T*, ptrdiff_t);
7521   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7522   //      T*         operator-(T*, ptrdiff_t);
7523   //      T*         operator+(ptrdiff_t, T*);
7524   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7525   //
7526   // C++ [over.built]p14:
7527   //
7528   //   For every T, where T is a pointer to object type, there
7529   //   exist candidate operator functions of the form
7530   //
7531   //      ptrdiff_t  operator-(T, T);
7532   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7533     /// Set of (canonical) types that we've already handled.
7534     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7535 
7536     for (int Arg = 0; Arg < 2; ++Arg) {
7537       QualType AsymetricParamTypes[2] = {
7538         S.Context.getPointerDiffType(),
7539         S.Context.getPointerDiffType(),
7540       };
7541       for (BuiltinCandidateTypeSet::iterator
7542                 Ptr = CandidateTypes[Arg].pointer_begin(),
7543              PtrEnd = CandidateTypes[Arg].pointer_end();
7544            Ptr != PtrEnd; ++Ptr) {
7545         QualType PointeeTy = (*Ptr)->getPointeeType();
7546         if (!PointeeTy->isObjectType())
7547           continue;
7548 
7549         AsymetricParamTypes[Arg] = *Ptr;
7550         if (Arg == 0 || Op == OO_Plus) {
7551           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7552           // T* operator+(ptrdiff_t, T*);
7553           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7554         }
7555         if (Op == OO_Minus) {
7556           // ptrdiff_t operator-(T, T);
7557           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7558             continue;
7559 
7560           QualType ParamTypes[2] = { *Ptr, *Ptr };
7561           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7562                                 Args, CandidateSet);
7563         }
7564       }
7565     }
7566   }
7567 
7568   // C++ [over.built]p12:
7569   //
7570   //   For every pair of promoted arithmetic types L and R, there
7571   //   exist candidate operator functions of the form
7572   //
7573   //        LR         operator*(L, R);
7574   //        LR         operator/(L, R);
7575   //        LR         operator+(L, R);
7576   //        LR         operator-(L, R);
7577   //        bool       operator<(L, R);
7578   //        bool       operator>(L, R);
7579   //        bool       operator<=(L, R);
7580   //        bool       operator>=(L, R);
7581   //        bool       operator==(L, R);
7582   //        bool       operator!=(L, R);
7583   //
7584   //   where LR is the result of the usual arithmetic conversions
7585   //   between types L and R.
7586   //
7587   // C++ [over.built]p24:
7588   //
7589   //   For every pair of promoted arithmetic types L and R, there exist
7590   //   candidate operator functions of the form
7591   //
7592   //        LR       operator?(bool, L, R);
7593   //
7594   //   where LR is the result of the usual arithmetic conversions
7595   //   between types L and R.
7596   // Our candidates ignore the first parameter.
7597   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7598     if (!HasArithmeticOrEnumeralCandidateType)
7599       return;
7600 
7601     for (unsigned Left = FirstPromotedArithmeticType;
7602          Left < LastPromotedArithmeticType; ++Left) {
7603       for (unsigned Right = FirstPromotedArithmeticType;
7604            Right < LastPromotedArithmeticType; ++Right) {
7605         QualType LandR[2] = { getArithmeticType(Left),
7606                               getArithmeticType(Right) };
7607         QualType Result =
7608           isComparison ? S.Context.BoolTy
7609                        : getUsualArithmeticConversions(Left, Right);
7610         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7611       }
7612     }
7613 
7614     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7615     // conditional operator for vector types.
7616     for (BuiltinCandidateTypeSet::iterator
7617               Vec1 = CandidateTypes[0].vector_begin(),
7618            Vec1End = CandidateTypes[0].vector_end();
7619          Vec1 != Vec1End; ++Vec1) {
7620       for (BuiltinCandidateTypeSet::iterator
7621                 Vec2 = CandidateTypes[1].vector_begin(),
7622              Vec2End = CandidateTypes[1].vector_end();
7623            Vec2 != Vec2End; ++Vec2) {
7624         QualType LandR[2] = { *Vec1, *Vec2 };
7625         QualType Result = S.Context.BoolTy;
7626         if (!isComparison) {
7627           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7628             Result = *Vec1;
7629           else
7630             Result = *Vec2;
7631         }
7632 
7633         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7634       }
7635     }
7636   }
7637 
7638   // C++ [over.built]p17:
7639   //
7640   //   For every pair of promoted integral types L and R, there
7641   //   exist candidate operator functions of the form
7642   //
7643   //      LR         operator%(L, R);
7644   //      LR         operator&(L, R);
7645   //      LR         operator^(L, R);
7646   //      LR         operator|(L, R);
7647   //      L          operator<<(L, R);
7648   //      L          operator>>(L, R);
7649   //
7650   //   where LR is the result of the usual arithmetic conversions
7651   //   between types L and R.
7652   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7653     if (!HasArithmeticOrEnumeralCandidateType)
7654       return;
7655 
7656     for (unsigned Left = FirstPromotedIntegralType;
7657          Left < LastPromotedIntegralType; ++Left) {
7658       for (unsigned Right = FirstPromotedIntegralType;
7659            Right < LastPromotedIntegralType; ++Right) {
7660         QualType LandR[2] = { getArithmeticType(Left),
7661                               getArithmeticType(Right) };
7662         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7663             ? LandR[0]
7664             : getUsualArithmeticConversions(Left, Right);
7665         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7666       }
7667     }
7668   }
7669 
7670   // C++ [over.built]p20:
7671   //
7672   //   For every pair (T, VQ), where T is an enumeration or
7673   //   pointer to member type and VQ is either volatile or
7674   //   empty, there exist candidate operator functions of the form
7675   //
7676   //        VQ T&      operator=(VQ T&, T);
7677   void addAssignmentMemberPointerOrEnumeralOverloads() {
7678     /// Set of (canonical) types that we've already handled.
7679     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7680 
7681     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7682       for (BuiltinCandidateTypeSet::iterator
7683                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7684              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7685            Enum != EnumEnd; ++Enum) {
7686         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7687           continue;
7688 
7689         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7690       }
7691 
7692       for (BuiltinCandidateTypeSet::iterator
7693                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7694              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7695            MemPtr != MemPtrEnd; ++MemPtr) {
7696         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7697           continue;
7698 
7699         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7700       }
7701     }
7702   }
7703 
7704   // C++ [over.built]p19:
7705   //
7706   //   For every pair (T, VQ), where T is any type and VQ is either
7707   //   volatile or empty, there exist candidate operator functions
7708   //   of the form
7709   //
7710   //        T*VQ&      operator=(T*VQ&, T*);
7711   //
7712   // C++ [over.built]p21:
7713   //
7714   //   For every pair (T, VQ), where T is a cv-qualified or
7715   //   cv-unqualified object type and VQ is either volatile or
7716   //   empty, there exist candidate operator functions of the form
7717   //
7718   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7719   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7720   void addAssignmentPointerOverloads(bool isEqualOp) {
7721     /// Set of (canonical) types that we've already handled.
7722     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7723 
7724     for (BuiltinCandidateTypeSet::iterator
7725               Ptr = CandidateTypes[0].pointer_begin(),
7726            PtrEnd = CandidateTypes[0].pointer_end();
7727          Ptr != PtrEnd; ++Ptr) {
7728       // If this is operator=, keep track of the builtin candidates we added.
7729       if (isEqualOp)
7730         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7731       else if (!(*Ptr)->getPointeeType()->isObjectType())
7732         continue;
7733 
7734       // non-volatile version
7735       QualType ParamTypes[2] = {
7736         S.Context.getLValueReferenceType(*Ptr),
7737         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7738       };
7739       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7740                             /*IsAssigmentOperator=*/ isEqualOp);
7741 
7742       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7743                           VisibleTypeConversionsQuals.hasVolatile();
7744       if (NeedVolatile) {
7745         // volatile version
7746         ParamTypes[0] =
7747           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7748         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7749                               /*IsAssigmentOperator=*/isEqualOp);
7750       }
7751 
7752       if (!(*Ptr).isRestrictQualified() &&
7753           VisibleTypeConversionsQuals.hasRestrict()) {
7754         // restrict version
7755         ParamTypes[0]
7756           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7757         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7758                               /*IsAssigmentOperator=*/isEqualOp);
7759 
7760         if (NeedVolatile) {
7761           // volatile restrict version
7762           ParamTypes[0]
7763             = S.Context.getLValueReferenceType(
7764                 S.Context.getCVRQualifiedType(*Ptr,
7765                                               (Qualifiers::Volatile |
7766                                                Qualifiers::Restrict)));
7767           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7768                                 /*IsAssigmentOperator=*/isEqualOp);
7769         }
7770       }
7771     }
7772 
7773     if (isEqualOp) {
7774       for (BuiltinCandidateTypeSet::iterator
7775                 Ptr = CandidateTypes[1].pointer_begin(),
7776              PtrEnd = CandidateTypes[1].pointer_end();
7777            Ptr != PtrEnd; ++Ptr) {
7778         // Make sure we don't add the same candidate twice.
7779         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7780           continue;
7781 
7782         QualType ParamTypes[2] = {
7783           S.Context.getLValueReferenceType(*Ptr),
7784           *Ptr,
7785         };
7786 
7787         // non-volatile version
7788         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7789                               /*IsAssigmentOperator=*/true);
7790 
7791         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7792                            VisibleTypeConversionsQuals.hasVolatile();
7793         if (NeedVolatile) {
7794           // volatile version
7795           ParamTypes[0] =
7796             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7797           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7798                                 /*IsAssigmentOperator=*/true);
7799         }
7800 
7801         if (!(*Ptr).isRestrictQualified() &&
7802             VisibleTypeConversionsQuals.hasRestrict()) {
7803           // restrict version
7804           ParamTypes[0]
7805             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7806           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7807                                 /*IsAssigmentOperator=*/true);
7808 
7809           if (NeedVolatile) {
7810             // volatile restrict version
7811             ParamTypes[0]
7812               = S.Context.getLValueReferenceType(
7813                   S.Context.getCVRQualifiedType(*Ptr,
7814                                                 (Qualifiers::Volatile |
7815                                                  Qualifiers::Restrict)));
7816             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7817                                   /*IsAssigmentOperator=*/true);
7818           }
7819         }
7820       }
7821     }
7822   }
7823 
7824   // C++ [over.built]p18:
7825   //
7826   //   For every triple (L, VQ, R), where L is an arithmetic type,
7827   //   VQ is either volatile or empty, and R is a promoted
7828   //   arithmetic type, there exist candidate operator functions of
7829   //   the form
7830   //
7831   //        VQ L&      operator=(VQ L&, R);
7832   //        VQ L&      operator*=(VQ L&, R);
7833   //        VQ L&      operator/=(VQ L&, R);
7834   //        VQ L&      operator+=(VQ L&, R);
7835   //        VQ L&      operator-=(VQ L&, R);
7836   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7837     if (!HasArithmeticOrEnumeralCandidateType)
7838       return;
7839 
7840     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7841       for (unsigned Right = FirstPromotedArithmeticType;
7842            Right < LastPromotedArithmeticType; ++Right) {
7843         QualType ParamTypes[2];
7844         ParamTypes[1] = getArithmeticType(Right);
7845 
7846         // Add this built-in operator as a candidate (VQ is empty).
7847         ParamTypes[0] =
7848           S.Context.getLValueReferenceType(getArithmeticType(Left));
7849         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7850                               /*IsAssigmentOperator=*/isEqualOp);
7851 
7852         // Add this built-in operator as a candidate (VQ is 'volatile').
7853         if (VisibleTypeConversionsQuals.hasVolatile()) {
7854           ParamTypes[0] =
7855             S.Context.getVolatileType(getArithmeticType(Left));
7856           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7857           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7858                                 /*IsAssigmentOperator=*/isEqualOp);
7859         }
7860       }
7861     }
7862 
7863     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7864     for (BuiltinCandidateTypeSet::iterator
7865               Vec1 = CandidateTypes[0].vector_begin(),
7866            Vec1End = CandidateTypes[0].vector_end();
7867          Vec1 != Vec1End; ++Vec1) {
7868       for (BuiltinCandidateTypeSet::iterator
7869                 Vec2 = CandidateTypes[1].vector_begin(),
7870              Vec2End = CandidateTypes[1].vector_end();
7871            Vec2 != Vec2End; ++Vec2) {
7872         QualType ParamTypes[2];
7873         ParamTypes[1] = *Vec2;
7874         // Add this built-in operator as a candidate (VQ is empty).
7875         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7876         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7877                               /*IsAssigmentOperator=*/isEqualOp);
7878 
7879         // Add this built-in operator as a candidate (VQ is 'volatile').
7880         if (VisibleTypeConversionsQuals.hasVolatile()) {
7881           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7882           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7883           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7884                                 /*IsAssigmentOperator=*/isEqualOp);
7885         }
7886       }
7887     }
7888   }
7889 
7890   // C++ [over.built]p22:
7891   //
7892   //   For every triple (L, VQ, R), where L is an integral type, VQ
7893   //   is either volatile or empty, and R is a promoted integral
7894   //   type, there exist candidate operator functions of the form
7895   //
7896   //        VQ L&       operator%=(VQ L&, R);
7897   //        VQ L&       operator<<=(VQ L&, R);
7898   //        VQ L&       operator>>=(VQ L&, R);
7899   //        VQ L&       operator&=(VQ L&, R);
7900   //        VQ L&       operator^=(VQ L&, R);
7901   //        VQ L&       operator|=(VQ L&, R);
7902   void addAssignmentIntegralOverloads() {
7903     if (!HasArithmeticOrEnumeralCandidateType)
7904       return;
7905 
7906     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7907       for (unsigned Right = FirstPromotedIntegralType;
7908            Right < LastPromotedIntegralType; ++Right) {
7909         QualType ParamTypes[2];
7910         ParamTypes[1] = getArithmeticType(Right);
7911 
7912         // Add this built-in operator as a candidate (VQ is empty).
7913         ParamTypes[0] =
7914           S.Context.getLValueReferenceType(getArithmeticType(Left));
7915         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7916         if (VisibleTypeConversionsQuals.hasVolatile()) {
7917           // Add this built-in operator as a candidate (VQ is 'volatile').
7918           ParamTypes[0] = getArithmeticType(Left);
7919           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7920           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7921           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7922         }
7923       }
7924     }
7925   }
7926 
7927   // C++ [over.operator]p23:
7928   //
7929   //   There also exist candidate operator functions of the form
7930   //
7931   //        bool        operator!(bool);
7932   //        bool        operator&&(bool, bool);
7933   //        bool        operator||(bool, bool);
7934   void addExclaimOverload() {
7935     QualType ParamTy = S.Context.BoolTy;
7936     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7937                           /*IsAssignmentOperator=*/false,
7938                           /*NumContextualBoolArguments=*/1);
7939   }
7940   void addAmpAmpOrPipePipeOverload() {
7941     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7942     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7943                           /*IsAssignmentOperator=*/false,
7944                           /*NumContextualBoolArguments=*/2);
7945   }
7946 
7947   // C++ [over.built]p13:
7948   //
7949   //   For every cv-qualified or cv-unqualified object type T there
7950   //   exist candidate operator functions of the form
7951   //
7952   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7953   //        T&         operator[](T*, ptrdiff_t);
7954   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7955   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7956   //        T&         operator[](ptrdiff_t, T*);
7957   void addSubscriptOverloads() {
7958     for (BuiltinCandidateTypeSet::iterator
7959               Ptr = CandidateTypes[0].pointer_begin(),
7960            PtrEnd = CandidateTypes[0].pointer_end();
7961          Ptr != PtrEnd; ++Ptr) {
7962       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7963       QualType PointeeType = (*Ptr)->getPointeeType();
7964       if (!PointeeType->isObjectType())
7965         continue;
7966 
7967       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7968 
7969       // T& operator[](T*, ptrdiff_t)
7970       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7971     }
7972 
7973     for (BuiltinCandidateTypeSet::iterator
7974               Ptr = CandidateTypes[1].pointer_begin(),
7975            PtrEnd = CandidateTypes[1].pointer_end();
7976          Ptr != PtrEnd; ++Ptr) {
7977       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7978       QualType PointeeType = (*Ptr)->getPointeeType();
7979       if (!PointeeType->isObjectType())
7980         continue;
7981 
7982       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7983 
7984       // T& operator[](ptrdiff_t, T*)
7985       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7986     }
7987   }
7988 
7989   // C++ [over.built]p11:
7990   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7991   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7992   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7993   //    there exist candidate operator functions of the form
7994   //
7995   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7996   //
7997   //    where CV12 is the union of CV1 and CV2.
7998   void addArrowStarOverloads() {
7999     for (BuiltinCandidateTypeSet::iterator
8000              Ptr = CandidateTypes[0].pointer_begin(),
8001            PtrEnd = CandidateTypes[0].pointer_end();
8002          Ptr != PtrEnd; ++Ptr) {
8003       QualType C1Ty = (*Ptr);
8004       QualType C1;
8005       QualifierCollector Q1;
8006       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8007       if (!isa<RecordType>(C1))
8008         continue;
8009       // heuristic to reduce number of builtin candidates in the set.
8010       // Add volatile/restrict version only if there are conversions to a
8011       // volatile/restrict type.
8012       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8013         continue;
8014       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8015         continue;
8016       for (BuiltinCandidateTypeSet::iterator
8017                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8018              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8019            MemPtr != MemPtrEnd; ++MemPtr) {
8020         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8021         QualType C2 = QualType(mptr->getClass(), 0);
8022         C2 = C2.getUnqualifiedType();
8023         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8024           break;
8025         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8026         // build CV12 T&
8027         QualType T = mptr->getPointeeType();
8028         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8029             T.isVolatileQualified())
8030           continue;
8031         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8032             T.isRestrictQualified())
8033           continue;
8034         T = Q1.apply(S.Context, T);
8035         QualType ResultTy = S.Context.getLValueReferenceType(T);
8036         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8037       }
8038     }
8039   }
8040 
8041   // Note that we don't consider the first argument, since it has been
8042   // contextually converted to bool long ago. The candidates below are
8043   // therefore added as binary.
8044   //
8045   // C++ [over.built]p25:
8046   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8047   //   enumeration type, there exist candidate operator functions of the form
8048   //
8049   //        T        operator?(bool, T, T);
8050   //
8051   void addConditionalOperatorOverloads() {
8052     /// Set of (canonical) types that we've already handled.
8053     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8054 
8055     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8056       for (BuiltinCandidateTypeSet::iterator
8057                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8058              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8059            Ptr != PtrEnd; ++Ptr) {
8060         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8061           continue;
8062 
8063         QualType ParamTypes[2] = { *Ptr, *Ptr };
8064         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8065       }
8066 
8067       for (BuiltinCandidateTypeSet::iterator
8068                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8069              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8070            MemPtr != MemPtrEnd; ++MemPtr) {
8071         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8072           continue;
8073 
8074         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8075         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8076       }
8077 
8078       if (S.getLangOpts().CPlusPlus11) {
8079         for (BuiltinCandidateTypeSet::iterator
8080                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8081                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8082              Enum != EnumEnd; ++Enum) {
8083           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8084             continue;
8085 
8086           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8087             continue;
8088 
8089           QualType ParamTypes[2] = { *Enum, *Enum };
8090           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8091         }
8092       }
8093     }
8094   }
8095 };
8096 
8097 } // end anonymous namespace
8098 
8099 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8100 /// operator overloads to the candidate set (C++ [over.built]), based
8101 /// on the operator @p Op and the arguments given. For example, if the
8102 /// operator is a binary '+', this routine might add "int
8103 /// operator+(int, int)" to cover integer addition.
8104 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8105                                         SourceLocation OpLoc,
8106                                         ArrayRef<Expr *> Args,
8107                                         OverloadCandidateSet &CandidateSet) {
8108   // Find all of the types that the arguments can convert to, but only
8109   // if the operator we're looking at has built-in operator candidates
8110   // that make use of these types. Also record whether we encounter non-record
8111   // candidate types or either arithmetic or enumeral candidate types.
8112   Qualifiers VisibleTypeConversionsQuals;
8113   VisibleTypeConversionsQuals.addConst();
8114   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8115     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8116 
8117   bool HasNonRecordCandidateType = false;
8118   bool HasArithmeticOrEnumeralCandidateType = false;
8119   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8120   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8121     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
8122     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8123                                                  OpLoc,
8124                                                  true,
8125                                                  (Op == OO_Exclaim ||
8126                                                   Op == OO_AmpAmp ||
8127                                                   Op == OO_PipePipe),
8128                                                  VisibleTypeConversionsQuals);
8129     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8130         CandidateTypes[ArgIdx].hasNonRecordTypes();
8131     HasArithmeticOrEnumeralCandidateType =
8132         HasArithmeticOrEnumeralCandidateType ||
8133         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8134   }
8135 
8136   // Exit early when no non-record types have been added to the candidate set
8137   // for any of the arguments to the operator.
8138   //
8139   // We can't exit early for !, ||, or &&, since there we have always have
8140   // 'bool' overloads.
8141   if (!HasNonRecordCandidateType &&
8142       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8143     return;
8144 
8145   // Setup an object to manage the common state for building overloads.
8146   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8147                                            VisibleTypeConversionsQuals,
8148                                            HasArithmeticOrEnumeralCandidateType,
8149                                            CandidateTypes, CandidateSet);
8150 
8151   // Dispatch over the operation to add in only those overloads which apply.
8152   switch (Op) {
8153   case OO_None:
8154   case NUM_OVERLOADED_OPERATORS:
8155     llvm_unreachable("Expected an overloaded operator");
8156 
8157   case OO_New:
8158   case OO_Delete:
8159   case OO_Array_New:
8160   case OO_Array_Delete:
8161   case OO_Call:
8162     llvm_unreachable(
8163                     "Special operators don't use AddBuiltinOperatorCandidates");
8164 
8165   case OO_Comma:
8166   case OO_Arrow:
8167     // C++ [over.match.oper]p3:
8168     //   -- For the operator ',', the unary operator '&', or the
8169     //      operator '->', the built-in candidates set is empty.
8170     break;
8171 
8172   case OO_Plus: // '+' is either unary or binary
8173     if (Args.size() == 1)
8174       OpBuilder.addUnaryPlusPointerOverloads();
8175     // Fall through.
8176 
8177   case OO_Minus: // '-' is either unary or binary
8178     if (Args.size() == 1) {
8179       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8180     } else {
8181       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8182       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8183     }
8184     break;
8185 
8186   case OO_Star: // '*' is either unary or binary
8187     if (Args.size() == 1)
8188       OpBuilder.addUnaryStarPointerOverloads();
8189     else
8190       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8191     break;
8192 
8193   case OO_Slash:
8194     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8195     break;
8196 
8197   case OO_PlusPlus:
8198   case OO_MinusMinus:
8199     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8200     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8201     break;
8202 
8203   case OO_EqualEqual:
8204   case OO_ExclaimEqual:
8205     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8206     // Fall through.
8207 
8208   case OO_Less:
8209   case OO_Greater:
8210   case OO_LessEqual:
8211   case OO_GreaterEqual:
8212     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8213     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8214     break;
8215 
8216   case OO_Percent:
8217   case OO_Caret:
8218   case OO_Pipe:
8219   case OO_LessLess:
8220   case OO_GreaterGreater:
8221     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8222     break;
8223 
8224   case OO_Amp: // '&' is either unary or binary
8225     if (Args.size() == 1)
8226       // C++ [over.match.oper]p3:
8227       //   -- For the operator ',', the unary operator '&', or the
8228       //      operator '->', the built-in candidates set is empty.
8229       break;
8230 
8231     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8232     break;
8233 
8234   case OO_Tilde:
8235     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8236     break;
8237 
8238   case OO_Equal:
8239     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8240     // Fall through.
8241 
8242   case OO_PlusEqual:
8243   case OO_MinusEqual:
8244     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8245     // Fall through.
8246 
8247   case OO_StarEqual:
8248   case OO_SlashEqual:
8249     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8250     break;
8251 
8252   case OO_PercentEqual:
8253   case OO_LessLessEqual:
8254   case OO_GreaterGreaterEqual:
8255   case OO_AmpEqual:
8256   case OO_CaretEqual:
8257   case OO_PipeEqual:
8258     OpBuilder.addAssignmentIntegralOverloads();
8259     break;
8260 
8261   case OO_Exclaim:
8262     OpBuilder.addExclaimOverload();
8263     break;
8264 
8265   case OO_AmpAmp:
8266   case OO_PipePipe:
8267     OpBuilder.addAmpAmpOrPipePipeOverload();
8268     break;
8269 
8270   case OO_Subscript:
8271     OpBuilder.addSubscriptOverloads();
8272     break;
8273 
8274   case OO_ArrowStar:
8275     OpBuilder.addArrowStarOverloads();
8276     break;
8277 
8278   case OO_Conditional:
8279     OpBuilder.addConditionalOperatorOverloads();
8280     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8281     break;
8282   }
8283 }
8284 
8285 /// \brief Add function candidates found via argument-dependent lookup
8286 /// to the set of overloading candidates.
8287 ///
8288 /// This routine performs argument-dependent name lookup based on the
8289 /// given function name (which may also be an operator name) and adds
8290 /// all of the overload candidates found by ADL to the overload
8291 /// candidate set (C++ [basic.lookup.argdep]).
8292 void
8293 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8294                                            SourceLocation Loc,
8295                                            ArrayRef<Expr *> Args,
8296                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8297                                            OverloadCandidateSet& CandidateSet,
8298                                            bool PartialOverloading) {
8299   ADLResult Fns;
8300 
8301   // FIXME: This approach for uniquing ADL results (and removing
8302   // redundant candidates from the set) relies on pointer-equality,
8303   // which means we need to key off the canonical decl.  However,
8304   // always going back to the canonical decl might not get us the
8305   // right set of default arguments.  What default arguments are
8306   // we supposed to consider on ADL candidates, anyway?
8307 
8308   // FIXME: Pass in the explicit template arguments?
8309   ArgumentDependentLookup(Name, Loc, Args, Fns);
8310 
8311   // Erase all of the candidates we already knew about.
8312   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8313                                    CandEnd = CandidateSet.end();
8314        Cand != CandEnd; ++Cand)
8315     if (Cand->Function) {
8316       Fns.erase(Cand->Function);
8317       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8318         Fns.erase(FunTmpl);
8319     }
8320 
8321   // For each of the ADL candidates we found, add it to the overload
8322   // set.
8323   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8324     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8325     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8326       if (ExplicitTemplateArgs)
8327         continue;
8328 
8329       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8330                            PartialOverloading);
8331     } else
8332       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8333                                    FoundDecl, ExplicitTemplateArgs,
8334                                    Args, CandidateSet, PartialOverloading);
8335   }
8336 }
8337 
8338 /// isBetterOverloadCandidate - Determines whether the first overload
8339 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8340 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8341                                       const OverloadCandidate &Cand2,
8342                                       SourceLocation Loc,
8343                                       bool UserDefinedConversion) {
8344   // Define viable functions to be better candidates than non-viable
8345   // functions.
8346   if (!Cand2.Viable)
8347     return Cand1.Viable;
8348   else if (!Cand1.Viable)
8349     return false;
8350 
8351   // C++ [over.match.best]p1:
8352   //
8353   //   -- if F is a static member function, ICS1(F) is defined such
8354   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8355   //      any function G, and, symmetrically, ICS1(G) is neither
8356   //      better nor worse than ICS1(F).
8357   unsigned StartArg = 0;
8358   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8359     StartArg = 1;
8360 
8361   // C++ [over.match.best]p1:
8362   //   A viable function F1 is defined to be a better function than another
8363   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8364   //   conversion sequence than ICSi(F2), and then...
8365   unsigned NumArgs = Cand1.NumConversions;
8366   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8367   bool HasBetterConversion = false;
8368   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8369     switch (CompareImplicitConversionSequences(S,
8370                                                Cand1.Conversions[ArgIdx],
8371                                                Cand2.Conversions[ArgIdx])) {
8372     case ImplicitConversionSequence::Better:
8373       // Cand1 has a better conversion sequence.
8374       HasBetterConversion = true;
8375       break;
8376 
8377     case ImplicitConversionSequence::Worse:
8378       // Cand1 can't be better than Cand2.
8379       return false;
8380 
8381     case ImplicitConversionSequence::Indistinguishable:
8382       // Do nothing.
8383       break;
8384     }
8385   }
8386 
8387   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8388   //       ICSj(F2), or, if not that,
8389   if (HasBetterConversion)
8390     return true;
8391 
8392   //   -- the context is an initialization by user-defined conversion
8393   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8394   //      from the return type of F1 to the destination type (i.e.,
8395   //      the type of the entity being initialized) is a better
8396   //      conversion sequence than the standard conversion sequence
8397   //      from the return type of F2 to the destination type.
8398   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8399       isa<CXXConversionDecl>(Cand1.Function) &&
8400       isa<CXXConversionDecl>(Cand2.Function)) {
8401     // First check whether we prefer one of the conversion functions over the
8402     // other. This only distinguishes the results in non-standard, extension
8403     // cases such as the conversion from a lambda closure type to a function
8404     // pointer or block.
8405     ImplicitConversionSequence::CompareKind Result =
8406         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8407     if (Result == ImplicitConversionSequence::Indistinguishable)
8408       Result = CompareStandardConversionSequences(S,
8409                                                   Cand1.FinalConversion,
8410                                                   Cand2.FinalConversion);
8411 
8412     if (Result != ImplicitConversionSequence::Indistinguishable)
8413       return Result == ImplicitConversionSequence::Better;
8414 
8415     // FIXME: Compare kind of reference binding if conversion functions
8416     // convert to a reference type used in direct reference binding, per
8417     // C++14 [over.match.best]p1 section 2 bullet 3.
8418   }
8419 
8420   //    -- F1 is a non-template function and F2 is a function template
8421   //       specialization, or, if not that,
8422   bool Cand1IsSpecialization = Cand1.Function &&
8423                                Cand1.Function->getPrimaryTemplate();
8424   bool Cand2IsSpecialization = Cand2.Function &&
8425                                Cand2.Function->getPrimaryTemplate();
8426   if (Cand1IsSpecialization != Cand2IsSpecialization)
8427     return Cand2IsSpecialization;
8428 
8429   //   -- F1 and F2 are function template specializations, and the function
8430   //      template for F1 is more specialized than the template for F2
8431   //      according to the partial ordering rules described in 14.5.5.2, or,
8432   //      if not that,
8433   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8434     if (FunctionTemplateDecl *BetterTemplate
8435           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8436                                          Cand2.Function->getPrimaryTemplate(),
8437                                          Loc,
8438                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8439                                                              : TPOC_Call,
8440                                          Cand1.ExplicitCallArguments,
8441                                          Cand2.ExplicitCallArguments))
8442       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8443   }
8444 
8445   // Check for enable_if value-based overload resolution.
8446   if (Cand1.Function && Cand2.Function &&
8447       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8448        Cand2.Function->hasAttr<EnableIfAttr>())) {
8449     // FIXME: The next several lines are just
8450     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8451     // instead of reverse order which is how they're stored in the AST.
8452     AttrVec Cand1Attrs;
8453     if (Cand1.Function->hasAttrs()) {
8454       Cand1Attrs = Cand1.Function->getAttrs();
8455       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8456                                       IsNotEnableIfAttr),
8457                        Cand1Attrs.end());
8458       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8459     }
8460 
8461     AttrVec Cand2Attrs;
8462     if (Cand2.Function->hasAttrs()) {
8463       Cand2Attrs = Cand2.Function->getAttrs();
8464       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8465                                       IsNotEnableIfAttr),
8466                        Cand2Attrs.end());
8467       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8468     }
8469 
8470     // Candidate 1 is better if it has strictly more attributes and
8471     // the common sequence is identical.
8472     if (Cand1Attrs.size() <= Cand2Attrs.size())
8473       return false;
8474 
8475     auto Cand1I = Cand1Attrs.begin();
8476     for (auto &Cand2A : Cand2Attrs) {
8477       auto &Cand1A = *Cand1I++;
8478       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8479       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8480                                                      S.getASTContext(), true);
8481       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8482                                                      S.getASTContext(), true);
8483       if (Cand1ID != Cand2ID)
8484         return false;
8485     }
8486 
8487     return true;
8488   }
8489 
8490   return false;
8491 }
8492 
8493 /// \brief Computes the best viable function (C++ 13.3.3)
8494 /// within an overload candidate set.
8495 ///
8496 /// \param Loc The location of the function name (or operator symbol) for
8497 /// which overload resolution occurs.
8498 ///
8499 /// \param Best If overload resolution was successful or found a deleted
8500 /// function, \p Best points to the candidate function found.
8501 ///
8502 /// \returns The result of overload resolution.
8503 OverloadingResult
8504 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8505                                          iterator &Best,
8506                                          bool UserDefinedConversion) {
8507   // Find the best viable function.
8508   Best = end();
8509   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8510     if (Cand->Viable)
8511       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8512                                                      UserDefinedConversion))
8513         Best = Cand;
8514   }
8515 
8516   // If we didn't find any viable functions, abort.
8517   if (Best == end())
8518     return OR_No_Viable_Function;
8519 
8520   // Make sure that this function is better than every other viable
8521   // function. If not, we have an ambiguity.
8522   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8523     if (Cand->Viable &&
8524         Cand != Best &&
8525         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8526                                    UserDefinedConversion)) {
8527       Best = end();
8528       return OR_Ambiguous;
8529     }
8530   }
8531 
8532   // Best is the best viable function.
8533   if (Best->Function &&
8534       (Best->Function->isDeleted() ||
8535        S.isFunctionConsideredUnavailable(Best->Function)))
8536     return OR_Deleted;
8537 
8538   return OR_Success;
8539 }
8540 
8541 namespace {
8542 
8543 enum OverloadCandidateKind {
8544   oc_function,
8545   oc_method,
8546   oc_constructor,
8547   oc_function_template,
8548   oc_method_template,
8549   oc_constructor_template,
8550   oc_implicit_default_constructor,
8551   oc_implicit_copy_constructor,
8552   oc_implicit_move_constructor,
8553   oc_implicit_copy_assignment,
8554   oc_implicit_move_assignment,
8555   oc_implicit_inherited_constructor
8556 };
8557 
8558 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8559                                                 FunctionDecl *Fn,
8560                                                 std::string &Description) {
8561   bool isTemplate = false;
8562 
8563   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8564     isTemplate = true;
8565     Description = S.getTemplateArgumentBindingsText(
8566       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8567   }
8568 
8569   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8570     if (!Ctor->isImplicit())
8571       return isTemplate ? oc_constructor_template : oc_constructor;
8572 
8573     if (Ctor->getInheritedConstructor())
8574       return oc_implicit_inherited_constructor;
8575 
8576     if (Ctor->isDefaultConstructor())
8577       return oc_implicit_default_constructor;
8578 
8579     if (Ctor->isMoveConstructor())
8580       return oc_implicit_move_constructor;
8581 
8582     assert(Ctor->isCopyConstructor() &&
8583            "unexpected sort of implicit constructor");
8584     return oc_implicit_copy_constructor;
8585   }
8586 
8587   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8588     // This actually gets spelled 'candidate function' for now, but
8589     // it doesn't hurt to split it out.
8590     if (!Meth->isImplicit())
8591       return isTemplate ? oc_method_template : oc_method;
8592 
8593     if (Meth->isMoveAssignmentOperator())
8594       return oc_implicit_move_assignment;
8595 
8596     if (Meth->isCopyAssignmentOperator())
8597       return oc_implicit_copy_assignment;
8598 
8599     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8600     return oc_method;
8601   }
8602 
8603   return isTemplate ? oc_function_template : oc_function;
8604 }
8605 
8606 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8607   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8608   if (!Ctor) return;
8609 
8610   Ctor = Ctor->getInheritedConstructor();
8611   if (!Ctor) return;
8612 
8613   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8614 }
8615 
8616 } // end anonymous namespace
8617 
8618 // Notes the location of an overload candidate.
8619 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8620   std::string FnDesc;
8621   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8622   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8623                              << (unsigned) K << FnDesc;
8624   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8625   Diag(Fn->getLocation(), PD);
8626   MaybeEmitInheritedConstructorNote(*this, Fn);
8627 }
8628 
8629 // Notes the location of all overload candidates designated through
8630 // OverloadedExpr
8631 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8632   assert(OverloadedExpr->getType() == Context.OverloadTy);
8633 
8634   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8635   OverloadExpr *OvlExpr = Ovl.Expression;
8636 
8637   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8638                             IEnd = OvlExpr->decls_end();
8639        I != IEnd; ++I) {
8640     if (FunctionTemplateDecl *FunTmpl =
8641                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8642       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8643     } else if (FunctionDecl *Fun
8644                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8645       NoteOverloadCandidate(Fun, DestType);
8646     }
8647   }
8648 }
8649 
8650 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8651 /// "lead" diagnostic; it will be given two arguments, the source and
8652 /// target types of the conversion.
8653 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8654                                  Sema &S,
8655                                  SourceLocation CaretLoc,
8656                                  const PartialDiagnostic &PDiag) const {
8657   S.Diag(CaretLoc, PDiag)
8658     << Ambiguous.getFromType() << Ambiguous.getToType();
8659   // FIXME: The note limiting machinery is borrowed from
8660   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8661   // refactoring here.
8662   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8663   unsigned CandsShown = 0;
8664   AmbiguousConversionSequence::const_iterator I, E;
8665   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8666     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8667       break;
8668     ++CandsShown;
8669     S.NoteOverloadCandidate(*I);
8670   }
8671   if (I != E)
8672     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8673 }
8674 
8675 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8676                                   unsigned I) {
8677   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8678   assert(Conv.isBad());
8679   assert(Cand->Function && "for now, candidate must be a function");
8680   FunctionDecl *Fn = Cand->Function;
8681 
8682   // There's a conversion slot for the object argument if this is a
8683   // non-constructor method.  Note that 'I' corresponds the
8684   // conversion-slot index.
8685   bool isObjectArgument = false;
8686   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8687     if (I == 0)
8688       isObjectArgument = true;
8689     else
8690       I--;
8691   }
8692 
8693   std::string FnDesc;
8694   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8695 
8696   Expr *FromExpr = Conv.Bad.FromExpr;
8697   QualType FromTy = Conv.Bad.getFromType();
8698   QualType ToTy = Conv.Bad.getToType();
8699 
8700   if (FromTy == S.Context.OverloadTy) {
8701     assert(FromExpr && "overload set argument came from implicit argument?");
8702     Expr *E = FromExpr->IgnoreParens();
8703     if (isa<UnaryOperator>(E))
8704       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8705     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8706 
8707     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8708       << (unsigned) FnKind << FnDesc
8709       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8710       << ToTy << Name << I+1;
8711     MaybeEmitInheritedConstructorNote(S, Fn);
8712     return;
8713   }
8714 
8715   // Do some hand-waving analysis to see if the non-viability is due
8716   // to a qualifier mismatch.
8717   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8718   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8719   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8720     CToTy = RT->getPointeeType();
8721   else {
8722     // TODO: detect and diagnose the full richness of const mismatches.
8723     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8724       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8725         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8726   }
8727 
8728   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8729       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8730     Qualifiers FromQs = CFromTy.getQualifiers();
8731     Qualifiers ToQs = CToTy.getQualifiers();
8732 
8733     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8734       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8735         << (unsigned) FnKind << FnDesc
8736         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8737         << FromTy
8738         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8739         << (unsigned) isObjectArgument << I+1;
8740       MaybeEmitInheritedConstructorNote(S, Fn);
8741       return;
8742     }
8743 
8744     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8745       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8746         << (unsigned) FnKind << FnDesc
8747         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8748         << FromTy
8749         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8750         << (unsigned) isObjectArgument << I+1;
8751       MaybeEmitInheritedConstructorNote(S, Fn);
8752       return;
8753     }
8754 
8755     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8756       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8757       << (unsigned) FnKind << FnDesc
8758       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8759       << FromTy
8760       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8761       << (unsigned) isObjectArgument << I+1;
8762       MaybeEmitInheritedConstructorNote(S, Fn);
8763       return;
8764     }
8765 
8766     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8767     assert(CVR && "unexpected qualifiers mismatch");
8768 
8769     if (isObjectArgument) {
8770       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8771         << (unsigned) FnKind << FnDesc
8772         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8773         << FromTy << (CVR - 1);
8774     } else {
8775       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8776         << (unsigned) FnKind << FnDesc
8777         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8778         << FromTy << (CVR - 1) << I+1;
8779     }
8780     MaybeEmitInheritedConstructorNote(S, Fn);
8781     return;
8782   }
8783 
8784   // Special diagnostic for failure to convert an initializer list, since
8785   // telling the user that it has type void is not useful.
8786   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8787     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8788       << (unsigned) FnKind << FnDesc
8789       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8790       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8791     MaybeEmitInheritedConstructorNote(S, Fn);
8792     return;
8793   }
8794 
8795   // Diagnose references or pointers to incomplete types differently,
8796   // since it's far from impossible that the incompleteness triggered
8797   // the failure.
8798   QualType TempFromTy = FromTy.getNonReferenceType();
8799   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8800     TempFromTy = PTy->getPointeeType();
8801   if (TempFromTy->isIncompleteType()) {
8802     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8803       << (unsigned) FnKind << FnDesc
8804       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8805       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8806     MaybeEmitInheritedConstructorNote(S, Fn);
8807     return;
8808   }
8809 
8810   // Diagnose base -> derived pointer conversions.
8811   unsigned BaseToDerivedConversion = 0;
8812   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8813     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8814       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8815                                                FromPtrTy->getPointeeType()) &&
8816           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8817           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8818           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8819                           FromPtrTy->getPointeeType()))
8820         BaseToDerivedConversion = 1;
8821     }
8822   } else if (const ObjCObjectPointerType *FromPtrTy
8823                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8824     if (const ObjCObjectPointerType *ToPtrTy
8825                                         = ToTy->getAs<ObjCObjectPointerType>())
8826       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8827         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8828           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8829                                                 FromPtrTy->getPointeeType()) &&
8830               FromIface->isSuperClassOf(ToIface))
8831             BaseToDerivedConversion = 2;
8832   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8833     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8834         !FromTy->isIncompleteType() &&
8835         !ToRefTy->getPointeeType()->isIncompleteType() &&
8836         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8837       BaseToDerivedConversion = 3;
8838     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8839                ToTy.getNonReferenceType().getCanonicalType() ==
8840                FromTy.getNonReferenceType().getCanonicalType()) {
8841       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8842         << (unsigned) FnKind << FnDesc
8843         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8844         << (unsigned) isObjectArgument << I + 1;
8845       MaybeEmitInheritedConstructorNote(S, Fn);
8846       return;
8847     }
8848   }
8849 
8850   if (BaseToDerivedConversion) {
8851     S.Diag(Fn->getLocation(),
8852            diag::note_ovl_candidate_bad_base_to_derived_conv)
8853       << (unsigned) FnKind << FnDesc
8854       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8855       << (BaseToDerivedConversion - 1)
8856       << FromTy << ToTy << I+1;
8857     MaybeEmitInheritedConstructorNote(S, Fn);
8858     return;
8859   }
8860 
8861   if (isa<ObjCObjectPointerType>(CFromTy) &&
8862       isa<PointerType>(CToTy)) {
8863       Qualifiers FromQs = CFromTy.getQualifiers();
8864       Qualifiers ToQs = CToTy.getQualifiers();
8865       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8866         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8867         << (unsigned) FnKind << FnDesc
8868         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8869         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8870         MaybeEmitInheritedConstructorNote(S, Fn);
8871         return;
8872       }
8873   }
8874 
8875   // Emit the generic diagnostic and, optionally, add the hints to it.
8876   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8877   FDiag << (unsigned) FnKind << FnDesc
8878     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8879     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8880     << (unsigned) (Cand->Fix.Kind);
8881 
8882   // If we can fix the conversion, suggest the FixIts.
8883   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8884        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8885     FDiag << *HI;
8886   S.Diag(Fn->getLocation(), FDiag);
8887 
8888   MaybeEmitInheritedConstructorNote(S, Fn);
8889 }
8890 
8891 /// Additional arity mismatch diagnosis specific to a function overload
8892 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8893 /// over a candidate in any candidate set.
8894 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8895                                unsigned NumArgs) {
8896   FunctionDecl *Fn = Cand->Function;
8897   unsigned MinParams = Fn->getMinRequiredArguments();
8898 
8899   // With invalid overloaded operators, it's possible that we think we
8900   // have an arity mismatch when in fact it looks like we have the
8901   // right number of arguments, because only overloaded operators have
8902   // the weird behavior of overloading member and non-member functions.
8903   // Just don't report anything.
8904   if (Fn->isInvalidDecl() &&
8905       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8906     return true;
8907 
8908   if (NumArgs < MinParams) {
8909     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8910            (Cand->FailureKind == ovl_fail_bad_deduction &&
8911             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8912   } else {
8913     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8914            (Cand->FailureKind == ovl_fail_bad_deduction &&
8915             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8916   }
8917 
8918   return false;
8919 }
8920 
8921 /// General arity mismatch diagnosis over a candidate in a candidate set.
8922 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8923   assert(isa<FunctionDecl>(D) &&
8924       "The templated declaration should at least be a function"
8925       " when diagnosing bad template argument deduction due to too many"
8926       " or too few arguments");
8927 
8928   FunctionDecl *Fn = cast<FunctionDecl>(D);
8929 
8930   // TODO: treat calls to a missing default constructor as a special case
8931   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8932   unsigned MinParams = Fn->getMinRequiredArguments();
8933 
8934   // at least / at most / exactly
8935   unsigned mode, modeCount;
8936   if (NumFormalArgs < MinParams) {
8937     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8938         FnTy->isTemplateVariadic())
8939       mode = 0; // "at least"
8940     else
8941       mode = 2; // "exactly"
8942     modeCount = MinParams;
8943   } else {
8944     if (MinParams != FnTy->getNumParams())
8945       mode = 1; // "at most"
8946     else
8947       mode = 2; // "exactly"
8948     modeCount = FnTy->getNumParams();
8949   }
8950 
8951   std::string Description;
8952   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8953 
8954   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8955     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8956       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8957       << mode << Fn->getParamDecl(0) << NumFormalArgs;
8958   else
8959     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8960       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8961       << mode << modeCount << NumFormalArgs;
8962   MaybeEmitInheritedConstructorNote(S, Fn);
8963 }
8964 
8965 /// Arity mismatch diagnosis specific to a function overload candidate.
8966 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8967                                   unsigned NumFormalArgs) {
8968   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8969     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8970 }
8971 
8972 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
8973   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8974     return FD->getDescribedFunctionTemplate();
8975   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8976     return RD->getDescribedClassTemplate();
8977 
8978   llvm_unreachable("Unsupported: Getting the described template declaration"
8979                    " for bad deduction diagnosis");
8980 }
8981 
8982 /// Diagnose a failed template-argument deduction.
8983 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8984                                  DeductionFailureInfo &DeductionFailure,
8985                                  unsigned NumArgs) {
8986   TemplateParameter Param = DeductionFailure.getTemplateParameter();
8987   NamedDecl *ParamD;
8988   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8989   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8990   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8991   switch (DeductionFailure.Result) {
8992   case Sema::TDK_Success:
8993     llvm_unreachable("TDK_success while diagnosing bad deduction");
8994 
8995   case Sema::TDK_Incomplete: {
8996     assert(ParamD && "no parameter found for incomplete deduction result");
8997     S.Diag(Templated->getLocation(),
8998            diag::note_ovl_candidate_incomplete_deduction)
8999         << ParamD->getDeclName();
9000     MaybeEmitInheritedConstructorNote(S, Templated);
9001     return;
9002   }
9003 
9004   case Sema::TDK_Underqualified: {
9005     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9006     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9007 
9008     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9009 
9010     // Param will have been canonicalized, but it should just be a
9011     // qualified version of ParamD, so move the qualifiers to that.
9012     QualifierCollector Qs;
9013     Qs.strip(Param);
9014     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9015     assert(S.Context.hasSameType(Param, NonCanonParam));
9016 
9017     // Arg has also been canonicalized, but there's nothing we can do
9018     // about that.  It also doesn't matter as much, because it won't
9019     // have any template parameters in it (because deduction isn't
9020     // done on dependent types).
9021     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9022 
9023     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9024         << ParamD->getDeclName() << Arg << NonCanonParam;
9025     MaybeEmitInheritedConstructorNote(S, Templated);
9026     return;
9027   }
9028 
9029   case Sema::TDK_Inconsistent: {
9030     assert(ParamD && "no parameter found for inconsistent deduction result");
9031     int which = 0;
9032     if (isa<TemplateTypeParmDecl>(ParamD))
9033       which = 0;
9034     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9035       which = 1;
9036     else {
9037       which = 2;
9038     }
9039 
9040     S.Diag(Templated->getLocation(),
9041            diag::note_ovl_candidate_inconsistent_deduction)
9042         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9043         << *DeductionFailure.getSecondArg();
9044     MaybeEmitInheritedConstructorNote(S, Templated);
9045     return;
9046   }
9047 
9048   case Sema::TDK_InvalidExplicitArguments:
9049     assert(ParamD && "no parameter found for invalid explicit arguments");
9050     if (ParamD->getDeclName())
9051       S.Diag(Templated->getLocation(),
9052              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9053           << ParamD->getDeclName();
9054     else {
9055       int index = 0;
9056       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9057         index = TTP->getIndex();
9058       else if (NonTypeTemplateParmDecl *NTTP
9059                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9060         index = NTTP->getIndex();
9061       else
9062         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9063       S.Diag(Templated->getLocation(),
9064              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9065           << (index + 1);
9066     }
9067     MaybeEmitInheritedConstructorNote(S, Templated);
9068     return;
9069 
9070   case Sema::TDK_TooManyArguments:
9071   case Sema::TDK_TooFewArguments:
9072     DiagnoseArityMismatch(S, Templated, NumArgs);
9073     return;
9074 
9075   case Sema::TDK_InstantiationDepth:
9076     S.Diag(Templated->getLocation(),
9077            diag::note_ovl_candidate_instantiation_depth);
9078     MaybeEmitInheritedConstructorNote(S, Templated);
9079     return;
9080 
9081   case Sema::TDK_SubstitutionFailure: {
9082     // Format the template argument list into the argument string.
9083     SmallString<128> TemplateArgString;
9084     if (TemplateArgumentList *Args =
9085             DeductionFailure.getTemplateArgumentList()) {
9086       TemplateArgString = " ";
9087       TemplateArgString += S.getTemplateArgumentBindingsText(
9088           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9089     }
9090 
9091     // If this candidate was disabled by enable_if, say so.
9092     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9093     if (PDiag && PDiag->second.getDiagID() ==
9094           diag::err_typename_nested_not_found_enable_if) {
9095       // FIXME: Use the source range of the condition, and the fully-qualified
9096       //        name of the enable_if template. These are both present in PDiag.
9097       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9098         << "'enable_if'" << TemplateArgString;
9099       return;
9100     }
9101 
9102     // Format the SFINAE diagnostic into the argument string.
9103     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9104     //        formatted message in another diagnostic.
9105     SmallString<128> SFINAEArgString;
9106     SourceRange R;
9107     if (PDiag) {
9108       SFINAEArgString = ": ";
9109       R = SourceRange(PDiag->first, PDiag->first);
9110       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9111     }
9112 
9113     S.Diag(Templated->getLocation(),
9114            diag::note_ovl_candidate_substitution_failure)
9115         << TemplateArgString << SFINAEArgString << R;
9116     MaybeEmitInheritedConstructorNote(S, Templated);
9117     return;
9118   }
9119 
9120   case Sema::TDK_FailedOverloadResolution: {
9121     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9122     S.Diag(Templated->getLocation(),
9123            diag::note_ovl_candidate_failed_overload_resolution)
9124         << R.Expression->getName();
9125     return;
9126   }
9127 
9128   case Sema::TDK_NonDeducedMismatch: {
9129     // FIXME: Provide a source location to indicate what we couldn't match.
9130     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9131     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9132     if (FirstTA.getKind() == TemplateArgument::Template &&
9133         SecondTA.getKind() == TemplateArgument::Template) {
9134       TemplateName FirstTN = FirstTA.getAsTemplate();
9135       TemplateName SecondTN = SecondTA.getAsTemplate();
9136       if (FirstTN.getKind() == TemplateName::Template &&
9137           SecondTN.getKind() == TemplateName::Template) {
9138         if (FirstTN.getAsTemplateDecl()->getName() ==
9139             SecondTN.getAsTemplateDecl()->getName()) {
9140           // FIXME: This fixes a bad diagnostic where both templates are named
9141           // the same.  This particular case is a bit difficult since:
9142           // 1) It is passed as a string to the diagnostic printer.
9143           // 2) The diagnostic printer only attempts to find a better
9144           //    name for types, not decls.
9145           // Ideally, this should folded into the diagnostic printer.
9146           S.Diag(Templated->getLocation(),
9147                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9148               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9149           return;
9150         }
9151       }
9152     }
9153     // FIXME: For generic lambda parameters, check if the function is a lambda
9154     // call operator, and if so, emit a prettier and more informative
9155     // diagnostic that mentions 'auto' and lambda in addition to
9156     // (or instead of?) the canonical template type parameters.
9157     S.Diag(Templated->getLocation(),
9158            diag::note_ovl_candidate_non_deduced_mismatch)
9159         << FirstTA << SecondTA;
9160     return;
9161   }
9162   // TODO: diagnose these individually, then kill off
9163   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9164   case Sema::TDK_MiscellaneousDeductionFailure:
9165     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9166     MaybeEmitInheritedConstructorNote(S, Templated);
9167     return;
9168   }
9169 }
9170 
9171 /// Diagnose a failed template-argument deduction, for function calls.
9172 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9173                                  unsigned NumArgs) {
9174   unsigned TDK = Cand->DeductionFailure.Result;
9175   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9176     if (CheckArityMismatch(S, Cand, NumArgs))
9177       return;
9178   }
9179   DiagnoseBadDeduction(S, Cand->Function, // pattern
9180                        Cand->DeductionFailure, NumArgs);
9181 }
9182 
9183 /// CUDA: diagnose an invalid call across targets.
9184 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9185   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9186   FunctionDecl *Callee = Cand->Function;
9187 
9188   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9189                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9190 
9191   std::string FnDesc;
9192   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9193 
9194   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9195       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9196 
9197   // This could be an implicit constructor for which we could not infer the
9198   // target due to a collsion. Diagnose that case.
9199   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9200   if (Meth != nullptr && Meth->isImplicit()) {
9201     CXXRecordDecl *ParentClass = Meth->getParent();
9202     Sema::CXXSpecialMember CSM;
9203 
9204     switch (FnKind) {
9205     default:
9206       return;
9207     case oc_implicit_default_constructor:
9208       CSM = Sema::CXXDefaultConstructor;
9209       break;
9210     case oc_implicit_copy_constructor:
9211       CSM = Sema::CXXCopyConstructor;
9212       break;
9213     case oc_implicit_move_constructor:
9214       CSM = Sema::CXXMoveConstructor;
9215       break;
9216     case oc_implicit_copy_assignment:
9217       CSM = Sema::CXXCopyAssignment;
9218       break;
9219     case oc_implicit_move_assignment:
9220       CSM = Sema::CXXMoveAssignment;
9221       break;
9222     };
9223 
9224     bool ConstRHS = false;
9225     if (Meth->getNumParams()) {
9226       if (const ReferenceType *RT =
9227               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9228         ConstRHS = RT->getPointeeType().isConstQualified();
9229       }
9230     }
9231 
9232     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9233                                               /* ConstRHS */ ConstRHS,
9234                                               /* Diagnose */ true);
9235   }
9236 }
9237 
9238 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9239   FunctionDecl *Callee = Cand->Function;
9240   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9241 
9242   S.Diag(Callee->getLocation(),
9243          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9244       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9245 }
9246 
9247 /// Generates a 'note' diagnostic for an overload candidate.  We've
9248 /// already generated a primary error at the call site.
9249 ///
9250 /// It really does need to be a single diagnostic with its caret
9251 /// pointed at the candidate declaration.  Yes, this creates some
9252 /// major challenges of technical writing.  Yes, this makes pointing
9253 /// out problems with specific arguments quite awkward.  It's still
9254 /// better than generating twenty screens of text for every failed
9255 /// overload.
9256 ///
9257 /// It would be great to be able to express per-candidate problems
9258 /// more richly for those diagnostic clients that cared, but we'd
9259 /// still have to be just as careful with the default diagnostics.
9260 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9261                                   unsigned NumArgs) {
9262   FunctionDecl *Fn = Cand->Function;
9263 
9264   // Note deleted candidates, but only if they're viable.
9265   if (Cand->Viable && (Fn->isDeleted() ||
9266       S.isFunctionConsideredUnavailable(Fn))) {
9267     std::string FnDesc;
9268     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9269 
9270     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9271       << FnKind << FnDesc
9272       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9273     MaybeEmitInheritedConstructorNote(S, Fn);
9274     return;
9275   }
9276 
9277   // We don't really have anything else to say about viable candidates.
9278   if (Cand->Viable) {
9279     S.NoteOverloadCandidate(Fn);
9280     return;
9281   }
9282 
9283   switch (Cand->FailureKind) {
9284   case ovl_fail_too_many_arguments:
9285   case ovl_fail_too_few_arguments:
9286     return DiagnoseArityMismatch(S, Cand, NumArgs);
9287 
9288   case ovl_fail_bad_deduction:
9289     return DiagnoseBadDeduction(S, Cand, NumArgs);
9290 
9291   case ovl_fail_illegal_constructor: {
9292     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9293       << (Fn->getPrimaryTemplate() ? 1 : 0);
9294     MaybeEmitInheritedConstructorNote(S, Fn);
9295     return;
9296   }
9297 
9298   case ovl_fail_trivial_conversion:
9299   case ovl_fail_bad_final_conversion:
9300   case ovl_fail_final_conversion_not_exact:
9301     return S.NoteOverloadCandidate(Fn);
9302 
9303   case ovl_fail_bad_conversion: {
9304     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9305     for (unsigned N = Cand->NumConversions; I != N; ++I)
9306       if (Cand->Conversions[I].isBad())
9307         return DiagnoseBadConversion(S, Cand, I);
9308 
9309     // FIXME: this currently happens when we're called from SemaInit
9310     // when user-conversion overload fails.  Figure out how to handle
9311     // those conditions and diagnose them well.
9312     return S.NoteOverloadCandidate(Fn);
9313   }
9314 
9315   case ovl_fail_bad_target:
9316     return DiagnoseBadTarget(S, Cand);
9317 
9318   case ovl_fail_enable_if:
9319     return DiagnoseFailedEnableIfAttr(S, Cand);
9320   }
9321 }
9322 
9323 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9324   // Desugar the type of the surrogate down to a function type,
9325   // retaining as many typedefs as possible while still showing
9326   // the function type (and, therefore, its parameter types).
9327   QualType FnType = Cand->Surrogate->getConversionType();
9328   bool isLValueReference = false;
9329   bool isRValueReference = false;
9330   bool isPointer = false;
9331   if (const LValueReferenceType *FnTypeRef =
9332         FnType->getAs<LValueReferenceType>()) {
9333     FnType = FnTypeRef->getPointeeType();
9334     isLValueReference = true;
9335   } else if (const RValueReferenceType *FnTypeRef =
9336                FnType->getAs<RValueReferenceType>()) {
9337     FnType = FnTypeRef->getPointeeType();
9338     isRValueReference = true;
9339   }
9340   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9341     FnType = FnTypePtr->getPointeeType();
9342     isPointer = true;
9343   }
9344   // Desugar down to a function type.
9345   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9346   // Reconstruct the pointer/reference as appropriate.
9347   if (isPointer) FnType = S.Context.getPointerType(FnType);
9348   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9349   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9350 
9351   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9352     << FnType;
9353   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9354 }
9355 
9356 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9357                                          SourceLocation OpLoc,
9358                                          OverloadCandidate *Cand) {
9359   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9360   std::string TypeStr("operator");
9361   TypeStr += Opc;
9362   TypeStr += "(";
9363   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9364   if (Cand->NumConversions == 1) {
9365     TypeStr += ")";
9366     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9367   } else {
9368     TypeStr += ", ";
9369     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9370     TypeStr += ")";
9371     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9372   }
9373 }
9374 
9375 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9376                                          OverloadCandidate *Cand) {
9377   unsigned NoOperands = Cand->NumConversions;
9378   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9379     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9380     if (ICS.isBad()) break; // all meaningless after first invalid
9381     if (!ICS.isAmbiguous()) continue;
9382 
9383     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9384                               S.PDiag(diag::note_ambiguous_type_conversion));
9385   }
9386 }
9387 
9388 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9389   if (Cand->Function)
9390     return Cand->Function->getLocation();
9391   if (Cand->IsSurrogate)
9392     return Cand->Surrogate->getLocation();
9393   return SourceLocation();
9394 }
9395 
9396 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9397   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9398   case Sema::TDK_Success:
9399     llvm_unreachable("TDK_success while diagnosing bad deduction");
9400 
9401   case Sema::TDK_Invalid:
9402   case Sema::TDK_Incomplete:
9403     return 1;
9404 
9405   case Sema::TDK_Underqualified:
9406   case Sema::TDK_Inconsistent:
9407     return 2;
9408 
9409   case Sema::TDK_SubstitutionFailure:
9410   case Sema::TDK_NonDeducedMismatch:
9411   case Sema::TDK_MiscellaneousDeductionFailure:
9412     return 3;
9413 
9414   case Sema::TDK_InstantiationDepth:
9415   case Sema::TDK_FailedOverloadResolution:
9416     return 4;
9417 
9418   case Sema::TDK_InvalidExplicitArguments:
9419     return 5;
9420 
9421   case Sema::TDK_TooManyArguments:
9422   case Sema::TDK_TooFewArguments:
9423     return 6;
9424   }
9425   llvm_unreachable("Unhandled deduction result");
9426 }
9427 
9428 namespace {
9429 struct CompareOverloadCandidatesForDisplay {
9430   Sema &S;
9431   size_t NumArgs;
9432 
9433   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9434       : S(S), NumArgs(nArgs) {}
9435 
9436   bool operator()(const OverloadCandidate *L,
9437                   const OverloadCandidate *R) {
9438     // Fast-path this check.
9439     if (L == R) return false;
9440 
9441     // Order first by viability.
9442     if (L->Viable) {
9443       if (!R->Viable) return true;
9444 
9445       // TODO: introduce a tri-valued comparison for overload
9446       // candidates.  Would be more worthwhile if we had a sort
9447       // that could exploit it.
9448       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9449       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9450     } else if (R->Viable)
9451       return false;
9452 
9453     assert(L->Viable == R->Viable);
9454 
9455     // Criteria by which we can sort non-viable candidates:
9456     if (!L->Viable) {
9457       // 1. Arity mismatches come after other candidates.
9458       if (L->FailureKind == ovl_fail_too_many_arguments ||
9459           L->FailureKind == ovl_fail_too_few_arguments) {
9460         if (R->FailureKind == ovl_fail_too_many_arguments ||
9461             R->FailureKind == ovl_fail_too_few_arguments) {
9462           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9463           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9464           if (LDist == RDist) {
9465             if (L->FailureKind == R->FailureKind)
9466               // Sort non-surrogates before surrogates.
9467               return !L->IsSurrogate && R->IsSurrogate;
9468             // Sort candidates requiring fewer parameters than there were
9469             // arguments given after candidates requiring more parameters
9470             // than there were arguments given.
9471             return L->FailureKind == ovl_fail_too_many_arguments;
9472           }
9473           return LDist < RDist;
9474         }
9475         return false;
9476       }
9477       if (R->FailureKind == ovl_fail_too_many_arguments ||
9478           R->FailureKind == ovl_fail_too_few_arguments)
9479         return true;
9480 
9481       // 2. Bad conversions come first and are ordered by the number
9482       // of bad conversions and quality of good conversions.
9483       if (L->FailureKind == ovl_fail_bad_conversion) {
9484         if (R->FailureKind != ovl_fail_bad_conversion)
9485           return true;
9486 
9487         // The conversion that can be fixed with a smaller number of changes,
9488         // comes first.
9489         unsigned numLFixes = L->Fix.NumConversionsFixed;
9490         unsigned numRFixes = R->Fix.NumConversionsFixed;
9491         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9492         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9493         if (numLFixes != numRFixes) {
9494           if (numLFixes < numRFixes)
9495             return true;
9496           else
9497             return false;
9498         }
9499 
9500         // If there's any ordering between the defined conversions...
9501         // FIXME: this might not be transitive.
9502         assert(L->NumConversions == R->NumConversions);
9503 
9504         int leftBetter = 0;
9505         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9506         for (unsigned E = L->NumConversions; I != E; ++I) {
9507           switch (CompareImplicitConversionSequences(S,
9508                                                      L->Conversions[I],
9509                                                      R->Conversions[I])) {
9510           case ImplicitConversionSequence::Better:
9511             leftBetter++;
9512             break;
9513 
9514           case ImplicitConversionSequence::Worse:
9515             leftBetter--;
9516             break;
9517 
9518           case ImplicitConversionSequence::Indistinguishable:
9519             break;
9520           }
9521         }
9522         if (leftBetter > 0) return true;
9523         if (leftBetter < 0) return false;
9524 
9525       } else if (R->FailureKind == ovl_fail_bad_conversion)
9526         return false;
9527 
9528       if (L->FailureKind == ovl_fail_bad_deduction) {
9529         if (R->FailureKind != ovl_fail_bad_deduction)
9530           return true;
9531 
9532         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9533           return RankDeductionFailure(L->DeductionFailure)
9534                < RankDeductionFailure(R->DeductionFailure);
9535       } else if (R->FailureKind == ovl_fail_bad_deduction)
9536         return false;
9537 
9538       // TODO: others?
9539     }
9540 
9541     // Sort everything else by location.
9542     SourceLocation LLoc = GetLocationForCandidate(L);
9543     SourceLocation RLoc = GetLocationForCandidate(R);
9544 
9545     // Put candidates without locations (e.g. builtins) at the end.
9546     if (LLoc.isInvalid()) return false;
9547     if (RLoc.isInvalid()) return true;
9548 
9549     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9550   }
9551 };
9552 }
9553 
9554 /// CompleteNonViableCandidate - Normally, overload resolution only
9555 /// computes up to the first. Produces the FixIt set if possible.
9556 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9557                                        ArrayRef<Expr *> Args) {
9558   assert(!Cand->Viable);
9559 
9560   // Don't do anything on failures other than bad conversion.
9561   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9562 
9563   // We only want the FixIts if all the arguments can be corrected.
9564   bool Unfixable = false;
9565   // Use a implicit copy initialization to check conversion fixes.
9566   Cand->Fix.setConversionChecker(TryCopyInitialization);
9567 
9568   // Skip forward to the first bad conversion.
9569   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9570   unsigned ConvCount = Cand->NumConversions;
9571   while (true) {
9572     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9573     ConvIdx++;
9574     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9575       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9576       break;
9577     }
9578   }
9579 
9580   if (ConvIdx == ConvCount)
9581     return;
9582 
9583   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9584          "remaining conversion is initialized?");
9585 
9586   // FIXME: this should probably be preserved from the overload
9587   // operation somehow.
9588   bool SuppressUserConversions = false;
9589 
9590   const FunctionProtoType* Proto;
9591   unsigned ArgIdx = ConvIdx;
9592 
9593   if (Cand->IsSurrogate) {
9594     QualType ConvType
9595       = Cand->Surrogate->getConversionType().getNonReferenceType();
9596     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9597       ConvType = ConvPtrType->getPointeeType();
9598     Proto = ConvType->getAs<FunctionProtoType>();
9599     ArgIdx--;
9600   } else if (Cand->Function) {
9601     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9602     if (isa<CXXMethodDecl>(Cand->Function) &&
9603         !isa<CXXConstructorDecl>(Cand->Function))
9604       ArgIdx--;
9605   } else {
9606     // Builtin binary operator with a bad first conversion.
9607     assert(ConvCount <= 3);
9608     for (; ConvIdx != ConvCount; ++ConvIdx)
9609       Cand->Conversions[ConvIdx]
9610         = TryCopyInitialization(S, Args[ConvIdx],
9611                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9612                                 SuppressUserConversions,
9613                                 /*InOverloadResolution*/ true,
9614                                 /*AllowObjCWritebackConversion=*/
9615                                   S.getLangOpts().ObjCAutoRefCount);
9616     return;
9617   }
9618 
9619   // Fill in the rest of the conversions.
9620   unsigned NumParams = Proto->getNumParams();
9621   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9622     if (ArgIdx < NumParams) {
9623       Cand->Conversions[ConvIdx] = TryCopyInitialization(
9624           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9625           /*InOverloadResolution=*/true,
9626           /*AllowObjCWritebackConversion=*/
9627           S.getLangOpts().ObjCAutoRefCount);
9628       // Store the FixIt in the candidate if it exists.
9629       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9630         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9631     }
9632     else
9633       Cand->Conversions[ConvIdx].setEllipsis();
9634   }
9635 }
9636 
9637 /// PrintOverloadCandidates - When overload resolution fails, prints
9638 /// diagnostic messages containing the candidates in the candidate
9639 /// set.
9640 void OverloadCandidateSet::NoteCandidates(Sema &S,
9641                                           OverloadCandidateDisplayKind OCD,
9642                                           ArrayRef<Expr *> Args,
9643                                           StringRef Opc,
9644                                           SourceLocation OpLoc) {
9645   // Sort the candidates by viability and position.  Sorting directly would
9646   // be prohibitive, so we make a set of pointers and sort those.
9647   SmallVector<OverloadCandidate*, 32> Cands;
9648   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9649   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9650     if (Cand->Viable)
9651       Cands.push_back(Cand);
9652     else if (OCD == OCD_AllCandidates) {
9653       CompleteNonViableCandidate(S, Cand, Args);
9654       if (Cand->Function || Cand->IsSurrogate)
9655         Cands.push_back(Cand);
9656       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9657       // want to list every possible builtin candidate.
9658     }
9659   }
9660 
9661   std::sort(Cands.begin(), Cands.end(),
9662             CompareOverloadCandidatesForDisplay(S, Args.size()));
9663 
9664   bool ReportedAmbiguousConversions = false;
9665 
9666   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9667   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9668   unsigned CandsShown = 0;
9669   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9670     OverloadCandidate *Cand = *I;
9671 
9672     // Set an arbitrary limit on the number of candidate functions we'll spam
9673     // the user with.  FIXME: This limit should depend on details of the
9674     // candidate list.
9675     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9676       break;
9677     }
9678     ++CandsShown;
9679 
9680     if (Cand->Function)
9681       NoteFunctionCandidate(S, Cand, Args.size());
9682     else if (Cand->IsSurrogate)
9683       NoteSurrogateCandidate(S, Cand);
9684     else {
9685       assert(Cand->Viable &&
9686              "Non-viable built-in candidates are not added to Cands.");
9687       // Generally we only see ambiguities including viable builtin
9688       // operators if overload resolution got screwed up by an
9689       // ambiguous user-defined conversion.
9690       //
9691       // FIXME: It's quite possible for different conversions to see
9692       // different ambiguities, though.
9693       if (!ReportedAmbiguousConversions) {
9694         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9695         ReportedAmbiguousConversions = true;
9696       }
9697 
9698       // If this is a viable builtin, print it.
9699       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9700     }
9701   }
9702 
9703   if (I != E)
9704     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9705 }
9706 
9707 static SourceLocation
9708 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9709   return Cand->Specialization ? Cand->Specialization->getLocation()
9710                               : SourceLocation();
9711 }
9712 
9713 namespace {
9714 struct CompareTemplateSpecCandidatesForDisplay {
9715   Sema &S;
9716   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9717 
9718   bool operator()(const TemplateSpecCandidate *L,
9719                   const TemplateSpecCandidate *R) {
9720     // Fast-path this check.
9721     if (L == R)
9722       return false;
9723 
9724     // Assuming that both candidates are not matches...
9725 
9726     // Sort by the ranking of deduction failures.
9727     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9728       return RankDeductionFailure(L->DeductionFailure) <
9729              RankDeductionFailure(R->DeductionFailure);
9730 
9731     // Sort everything else by location.
9732     SourceLocation LLoc = GetLocationForCandidate(L);
9733     SourceLocation RLoc = GetLocationForCandidate(R);
9734 
9735     // Put candidates without locations (e.g. builtins) at the end.
9736     if (LLoc.isInvalid())
9737       return false;
9738     if (RLoc.isInvalid())
9739       return true;
9740 
9741     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9742   }
9743 };
9744 }
9745 
9746 /// Diagnose a template argument deduction failure.
9747 /// We are treating these failures as overload failures due to bad
9748 /// deductions.
9749 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9750   DiagnoseBadDeduction(S, Specialization, // pattern
9751                        DeductionFailure, /*NumArgs=*/0);
9752 }
9753 
9754 void TemplateSpecCandidateSet::destroyCandidates() {
9755   for (iterator i = begin(), e = end(); i != e; ++i) {
9756     i->DeductionFailure.Destroy();
9757   }
9758 }
9759 
9760 void TemplateSpecCandidateSet::clear() {
9761   destroyCandidates();
9762   Candidates.clear();
9763 }
9764 
9765 /// NoteCandidates - When no template specialization match is found, prints
9766 /// diagnostic messages containing the non-matching specializations that form
9767 /// the candidate set.
9768 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9769 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9770 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9771   // Sort the candidates by position (assuming no candidate is a match).
9772   // Sorting directly would be prohibitive, so we make a set of pointers
9773   // and sort those.
9774   SmallVector<TemplateSpecCandidate *, 32> Cands;
9775   Cands.reserve(size());
9776   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9777     if (Cand->Specialization)
9778       Cands.push_back(Cand);
9779     // Otherwise, this is a non-matching builtin candidate.  We do not,
9780     // in general, want to list every possible builtin candidate.
9781   }
9782 
9783   std::sort(Cands.begin(), Cands.end(),
9784             CompareTemplateSpecCandidatesForDisplay(S));
9785 
9786   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9787   // for generalization purposes (?).
9788   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9789 
9790   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9791   unsigned CandsShown = 0;
9792   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9793     TemplateSpecCandidate *Cand = *I;
9794 
9795     // Set an arbitrary limit on the number of candidates we'll spam
9796     // the user with.  FIXME: This limit should depend on details of the
9797     // candidate list.
9798     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9799       break;
9800     ++CandsShown;
9801 
9802     assert(Cand->Specialization &&
9803            "Non-matching built-in candidates are not added to Cands.");
9804     Cand->NoteDeductionFailure(S);
9805   }
9806 
9807   if (I != E)
9808     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9809 }
9810 
9811 // [PossiblyAFunctionType]  -->   [Return]
9812 // NonFunctionType --> NonFunctionType
9813 // R (A) --> R(A)
9814 // R (*)(A) --> R (A)
9815 // R (&)(A) --> R (A)
9816 // R (S::*)(A) --> R (A)
9817 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9818   QualType Ret = PossiblyAFunctionType;
9819   if (const PointerType *ToTypePtr =
9820     PossiblyAFunctionType->getAs<PointerType>())
9821     Ret = ToTypePtr->getPointeeType();
9822   else if (const ReferenceType *ToTypeRef =
9823     PossiblyAFunctionType->getAs<ReferenceType>())
9824     Ret = ToTypeRef->getPointeeType();
9825   else if (const MemberPointerType *MemTypePtr =
9826     PossiblyAFunctionType->getAs<MemberPointerType>())
9827     Ret = MemTypePtr->getPointeeType();
9828   Ret =
9829     Context.getCanonicalType(Ret).getUnqualifiedType();
9830   return Ret;
9831 }
9832 
9833 namespace {
9834 // A helper class to help with address of function resolution
9835 // - allows us to avoid passing around all those ugly parameters
9836 class AddressOfFunctionResolver {
9837   Sema& S;
9838   Expr* SourceExpr;
9839   const QualType& TargetType;
9840   QualType TargetFunctionType; // Extracted function type from target type
9841 
9842   bool Complain;
9843   //DeclAccessPair& ResultFunctionAccessPair;
9844   ASTContext& Context;
9845 
9846   bool TargetTypeIsNonStaticMemberFunction;
9847   bool FoundNonTemplateFunction;
9848   bool StaticMemberFunctionFromBoundPointer;
9849 
9850   OverloadExpr::FindResult OvlExprInfo;
9851   OverloadExpr *OvlExpr;
9852   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9853   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9854   TemplateSpecCandidateSet FailedCandidates;
9855 
9856 public:
9857   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9858                             const QualType &TargetType, bool Complain)
9859       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9860         Complain(Complain), Context(S.getASTContext()),
9861         TargetTypeIsNonStaticMemberFunction(
9862             !!TargetType->getAs<MemberPointerType>()),
9863         FoundNonTemplateFunction(false),
9864         StaticMemberFunctionFromBoundPointer(false),
9865         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9866         OvlExpr(OvlExprInfo.Expression),
9867         FailedCandidates(OvlExpr->getNameLoc()) {
9868     ExtractUnqualifiedFunctionTypeFromTargetType();
9869 
9870     if (TargetFunctionType->isFunctionType()) {
9871       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9872         if (!UME->isImplicitAccess() &&
9873             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9874           StaticMemberFunctionFromBoundPointer = true;
9875     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9876       DeclAccessPair dap;
9877       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9878               OvlExpr, false, &dap)) {
9879         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9880           if (!Method->isStatic()) {
9881             // If the target type is a non-function type and the function found
9882             // is a non-static member function, pretend as if that was the
9883             // target, it's the only possible type to end up with.
9884             TargetTypeIsNonStaticMemberFunction = true;
9885 
9886             // And skip adding the function if its not in the proper form.
9887             // We'll diagnose this due to an empty set of functions.
9888             if (!OvlExprInfo.HasFormOfMemberPointer)
9889               return;
9890           }
9891 
9892         Matches.push_back(std::make_pair(dap, Fn));
9893       }
9894       return;
9895     }
9896 
9897     if (OvlExpr->hasExplicitTemplateArgs())
9898       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9899 
9900     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9901       // C++ [over.over]p4:
9902       //   If more than one function is selected, [...]
9903       if (Matches.size() > 1) {
9904         if (FoundNonTemplateFunction)
9905           EliminateAllTemplateMatches();
9906         else
9907           EliminateAllExceptMostSpecializedTemplate();
9908       }
9909     }
9910   }
9911 
9912 private:
9913   bool isTargetTypeAFunction() const {
9914     return TargetFunctionType->isFunctionType();
9915   }
9916 
9917   // [ToType]     [Return]
9918 
9919   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9920   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9921   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9922   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9923     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9924   }
9925 
9926   // return true if any matching specializations were found
9927   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9928                                    const DeclAccessPair& CurAccessFunPair) {
9929     if (CXXMethodDecl *Method
9930               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9931       // Skip non-static function templates when converting to pointer, and
9932       // static when converting to member pointer.
9933       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9934         return false;
9935     }
9936     else if (TargetTypeIsNonStaticMemberFunction)
9937       return false;
9938 
9939     // C++ [over.over]p2:
9940     //   If the name is a function template, template argument deduction is
9941     //   done (14.8.2.2), and if the argument deduction succeeds, the
9942     //   resulting template argument list is used to generate a single
9943     //   function template specialization, which is added to the set of
9944     //   overloaded functions considered.
9945     FunctionDecl *Specialization = nullptr;
9946     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9947     if (Sema::TemplateDeductionResult Result
9948           = S.DeduceTemplateArguments(FunctionTemplate,
9949                                       &OvlExplicitTemplateArgs,
9950                                       TargetFunctionType, Specialization,
9951                                       Info, /*InOverloadResolution=*/true)) {
9952       // Make a note of the failed deduction for diagnostics.
9953       FailedCandidates.addCandidate()
9954           .set(FunctionTemplate->getTemplatedDecl(),
9955                MakeDeductionFailureInfo(Context, Result, Info));
9956       return false;
9957     }
9958 
9959     // Template argument deduction ensures that we have an exact match or
9960     // compatible pointer-to-function arguments that would be adjusted by ICS.
9961     // This function template specicalization works.
9962     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9963     assert(S.isSameOrCompatibleFunctionType(
9964               Context.getCanonicalType(Specialization->getType()),
9965               Context.getCanonicalType(TargetFunctionType)));
9966     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9967     return true;
9968   }
9969 
9970   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9971                                       const DeclAccessPair& CurAccessFunPair) {
9972     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9973       // Skip non-static functions when converting to pointer, and static
9974       // when converting to member pointer.
9975       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9976         return false;
9977     }
9978     else if (TargetTypeIsNonStaticMemberFunction)
9979       return false;
9980 
9981     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9982       if (S.getLangOpts().CUDA)
9983         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9984           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
9985             return false;
9986 
9987       // If any candidate has a placeholder return type, trigger its deduction
9988       // now.
9989       if (S.getLangOpts().CPlusPlus14 &&
9990           FunDecl->getReturnType()->isUndeducedType() &&
9991           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9992         return false;
9993 
9994       QualType ResultTy;
9995       if (Context.hasSameUnqualifiedType(TargetFunctionType,
9996                                          FunDecl->getType()) ||
9997           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9998                                  ResultTy)) {
9999         Matches.push_back(std::make_pair(CurAccessFunPair,
10000           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10001         FoundNonTemplateFunction = true;
10002         return true;
10003       }
10004     }
10005 
10006     return false;
10007   }
10008 
10009   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10010     bool Ret = false;
10011 
10012     // If the overload expression doesn't have the form of a pointer to
10013     // member, don't try to convert it to a pointer-to-member type.
10014     if (IsInvalidFormOfPointerToMemberFunction())
10015       return false;
10016 
10017     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10018                                E = OvlExpr->decls_end();
10019          I != E; ++I) {
10020       // Look through any using declarations to find the underlying function.
10021       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10022 
10023       // C++ [over.over]p3:
10024       //   Non-member functions and static member functions match
10025       //   targets of type "pointer-to-function" or "reference-to-function."
10026       //   Nonstatic member functions match targets of
10027       //   type "pointer-to-member-function."
10028       // Note that according to DR 247, the containing class does not matter.
10029       if (FunctionTemplateDecl *FunctionTemplate
10030                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10031         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10032           Ret = true;
10033       }
10034       // If we have explicit template arguments supplied, skip non-templates.
10035       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10036                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10037         Ret = true;
10038     }
10039     assert(Ret || Matches.empty());
10040     return Ret;
10041   }
10042 
10043   void EliminateAllExceptMostSpecializedTemplate() {
10044     //   [...] and any given function template specialization F1 is
10045     //   eliminated if the set contains a second function template
10046     //   specialization whose function template is more specialized
10047     //   than the function template of F1 according to the partial
10048     //   ordering rules of 14.5.5.2.
10049 
10050     // The algorithm specified above is quadratic. We instead use a
10051     // two-pass algorithm (similar to the one used to identify the
10052     // best viable function in an overload set) that identifies the
10053     // best function template (if it exists).
10054 
10055     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10056     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10057       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10058 
10059     // TODO: It looks like FailedCandidates does not serve much purpose
10060     // here, since the no_viable diagnostic has index 0.
10061     UnresolvedSetIterator Result = S.getMostSpecialized(
10062         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10063         SourceExpr->getLocStart(), S.PDiag(),
10064         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10065                                                      .second->getDeclName(),
10066         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10067         Complain, TargetFunctionType);
10068 
10069     if (Result != MatchesCopy.end()) {
10070       // Make it the first and only element
10071       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10072       Matches[0].second = cast<FunctionDecl>(*Result);
10073       Matches.resize(1);
10074     }
10075   }
10076 
10077   void EliminateAllTemplateMatches() {
10078     //   [...] any function template specializations in the set are
10079     //   eliminated if the set also contains a non-template function, [...]
10080     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10081       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10082         ++I;
10083       else {
10084         Matches[I] = Matches[--N];
10085         Matches.set_size(N);
10086       }
10087     }
10088   }
10089 
10090 public:
10091   void ComplainNoMatchesFound() const {
10092     assert(Matches.empty());
10093     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10094         << OvlExpr->getName() << TargetFunctionType
10095         << OvlExpr->getSourceRange();
10096     if (FailedCandidates.empty())
10097       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10098     else {
10099       // We have some deduction failure messages. Use them to diagnose
10100       // the function templates, and diagnose the non-template candidates
10101       // normally.
10102       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10103                                  IEnd = OvlExpr->decls_end();
10104            I != IEnd; ++I)
10105         if (FunctionDecl *Fun =
10106                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10107           S.NoteOverloadCandidate(Fun, TargetFunctionType);
10108       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10109     }
10110   }
10111 
10112   bool IsInvalidFormOfPointerToMemberFunction() const {
10113     return TargetTypeIsNonStaticMemberFunction &&
10114       !OvlExprInfo.HasFormOfMemberPointer;
10115   }
10116 
10117   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10118       // TODO: Should we condition this on whether any functions might
10119       // have matched, or is it more appropriate to do that in callers?
10120       // TODO: a fixit wouldn't hurt.
10121       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10122         << TargetType << OvlExpr->getSourceRange();
10123   }
10124 
10125   bool IsStaticMemberFunctionFromBoundPointer() const {
10126     return StaticMemberFunctionFromBoundPointer;
10127   }
10128 
10129   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10130     S.Diag(OvlExpr->getLocStart(),
10131            diag::err_invalid_form_pointer_member_function)
10132       << OvlExpr->getSourceRange();
10133   }
10134 
10135   void ComplainOfInvalidConversion() const {
10136     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10137       << OvlExpr->getName() << TargetType;
10138   }
10139 
10140   void ComplainMultipleMatchesFound() const {
10141     assert(Matches.size() > 1);
10142     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10143       << OvlExpr->getName()
10144       << OvlExpr->getSourceRange();
10145     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10146   }
10147 
10148   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10149 
10150   int getNumMatches() const { return Matches.size(); }
10151 
10152   FunctionDecl* getMatchingFunctionDecl() const {
10153     if (Matches.size() != 1) return nullptr;
10154     return Matches[0].second;
10155   }
10156 
10157   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10158     if (Matches.size() != 1) return nullptr;
10159     return &Matches[0].first;
10160   }
10161 };
10162 }
10163 
10164 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10165 /// an overloaded function (C++ [over.over]), where @p From is an
10166 /// expression with overloaded function type and @p ToType is the type
10167 /// we're trying to resolve to. For example:
10168 ///
10169 /// @code
10170 /// int f(double);
10171 /// int f(int);
10172 ///
10173 /// int (*pfd)(double) = f; // selects f(double)
10174 /// @endcode
10175 ///
10176 /// This routine returns the resulting FunctionDecl if it could be
10177 /// resolved, and NULL otherwise. When @p Complain is true, this
10178 /// routine will emit diagnostics if there is an error.
10179 FunctionDecl *
10180 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10181                                          QualType TargetType,
10182                                          bool Complain,
10183                                          DeclAccessPair &FoundResult,
10184                                          bool *pHadMultipleCandidates) {
10185   assert(AddressOfExpr->getType() == Context.OverloadTy);
10186 
10187   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10188                                      Complain);
10189   int NumMatches = Resolver.getNumMatches();
10190   FunctionDecl *Fn = nullptr;
10191   if (NumMatches == 0 && Complain) {
10192     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10193       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10194     else
10195       Resolver.ComplainNoMatchesFound();
10196   }
10197   else if (NumMatches > 1 && Complain)
10198     Resolver.ComplainMultipleMatchesFound();
10199   else if (NumMatches == 1) {
10200     Fn = Resolver.getMatchingFunctionDecl();
10201     assert(Fn);
10202     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10203     if (Complain) {
10204       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10205         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10206       else
10207         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10208     }
10209   }
10210 
10211   if (pHadMultipleCandidates)
10212     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10213   return Fn;
10214 }
10215 
10216 /// \brief Given an expression that refers to an overloaded function, try to
10217 /// resolve that overloaded function expression down to a single function.
10218 ///
10219 /// This routine can only resolve template-ids that refer to a single function
10220 /// template, where that template-id refers to a single template whose template
10221 /// arguments are either provided by the template-id or have defaults,
10222 /// as described in C++0x [temp.arg.explicit]p3.
10223 ///
10224 /// If no template-ids are found, no diagnostics are emitted and NULL is
10225 /// returned.
10226 FunctionDecl *
10227 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10228                                                   bool Complain,
10229                                                   DeclAccessPair *FoundResult) {
10230   // C++ [over.over]p1:
10231   //   [...] [Note: any redundant set of parentheses surrounding the
10232   //   overloaded function name is ignored (5.1). ]
10233   // C++ [over.over]p1:
10234   //   [...] The overloaded function name can be preceded by the &
10235   //   operator.
10236 
10237   // If we didn't actually find any template-ids, we're done.
10238   if (!ovl->hasExplicitTemplateArgs())
10239     return nullptr;
10240 
10241   TemplateArgumentListInfo ExplicitTemplateArgs;
10242   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10243   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10244 
10245   // Look through all of the overloaded functions, searching for one
10246   // whose type matches exactly.
10247   FunctionDecl *Matched = nullptr;
10248   for (UnresolvedSetIterator I = ovl->decls_begin(),
10249          E = ovl->decls_end(); I != E; ++I) {
10250     // C++0x [temp.arg.explicit]p3:
10251     //   [...] In contexts where deduction is done and fails, or in contexts
10252     //   where deduction is not done, if a template argument list is
10253     //   specified and it, along with any default template arguments,
10254     //   identifies a single function template specialization, then the
10255     //   template-id is an lvalue for the function template specialization.
10256     FunctionTemplateDecl *FunctionTemplate
10257       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10258 
10259     // C++ [over.over]p2:
10260     //   If the name is a function template, template argument deduction is
10261     //   done (14.8.2.2), and if the argument deduction succeeds, the
10262     //   resulting template argument list is used to generate a single
10263     //   function template specialization, which is added to the set of
10264     //   overloaded functions considered.
10265     FunctionDecl *Specialization = nullptr;
10266     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10267     if (TemplateDeductionResult Result
10268           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10269                                     Specialization, Info,
10270                                     /*InOverloadResolution=*/true)) {
10271       // Make a note of the failed deduction for diagnostics.
10272       // TODO: Actually use the failed-deduction info?
10273       FailedCandidates.addCandidate()
10274           .set(FunctionTemplate->getTemplatedDecl(),
10275                MakeDeductionFailureInfo(Context, Result, Info));
10276       continue;
10277     }
10278 
10279     assert(Specialization && "no specialization and no error?");
10280 
10281     // Multiple matches; we can't resolve to a single declaration.
10282     if (Matched) {
10283       if (Complain) {
10284         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10285           << ovl->getName();
10286         NoteAllOverloadCandidates(ovl);
10287       }
10288       return nullptr;
10289     }
10290 
10291     Matched = Specialization;
10292     if (FoundResult) *FoundResult = I.getPair();
10293   }
10294 
10295   if (Matched && getLangOpts().CPlusPlus14 &&
10296       Matched->getReturnType()->isUndeducedType() &&
10297       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10298     return nullptr;
10299 
10300   return Matched;
10301 }
10302 
10303 
10304 
10305 
10306 // Resolve and fix an overloaded expression that can be resolved
10307 // because it identifies a single function template specialization.
10308 //
10309 // Last three arguments should only be supplied if Complain = true
10310 //
10311 // Return true if it was logically possible to so resolve the
10312 // expression, regardless of whether or not it succeeded.  Always
10313 // returns true if 'complain' is set.
10314 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10315                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10316                    bool complain, const SourceRange& OpRangeForComplaining,
10317                                            QualType DestTypeForComplaining,
10318                                             unsigned DiagIDForComplaining) {
10319   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10320 
10321   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10322 
10323   DeclAccessPair found;
10324   ExprResult SingleFunctionExpression;
10325   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10326                            ovl.Expression, /*complain*/ false, &found)) {
10327     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10328       SrcExpr = ExprError();
10329       return true;
10330     }
10331 
10332     // It is only correct to resolve to an instance method if we're
10333     // resolving a form that's permitted to be a pointer to member.
10334     // Otherwise we'll end up making a bound member expression, which
10335     // is illegal in all the contexts we resolve like this.
10336     if (!ovl.HasFormOfMemberPointer &&
10337         isa<CXXMethodDecl>(fn) &&
10338         cast<CXXMethodDecl>(fn)->isInstance()) {
10339       if (!complain) return false;
10340 
10341       Diag(ovl.Expression->getExprLoc(),
10342            diag::err_bound_member_function)
10343         << 0 << ovl.Expression->getSourceRange();
10344 
10345       // TODO: I believe we only end up here if there's a mix of
10346       // static and non-static candidates (otherwise the expression
10347       // would have 'bound member' type, not 'overload' type).
10348       // Ideally we would note which candidate was chosen and why
10349       // the static candidates were rejected.
10350       SrcExpr = ExprError();
10351       return true;
10352     }
10353 
10354     // Fix the expression to refer to 'fn'.
10355     SingleFunctionExpression =
10356         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10357 
10358     // If desired, do function-to-pointer decay.
10359     if (doFunctionPointerConverion) {
10360       SingleFunctionExpression =
10361         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10362       if (SingleFunctionExpression.isInvalid()) {
10363         SrcExpr = ExprError();
10364         return true;
10365       }
10366     }
10367   }
10368 
10369   if (!SingleFunctionExpression.isUsable()) {
10370     if (complain) {
10371       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10372         << ovl.Expression->getName()
10373         << DestTypeForComplaining
10374         << OpRangeForComplaining
10375         << ovl.Expression->getQualifierLoc().getSourceRange();
10376       NoteAllOverloadCandidates(SrcExpr.get());
10377 
10378       SrcExpr = ExprError();
10379       return true;
10380     }
10381 
10382     return false;
10383   }
10384 
10385   SrcExpr = SingleFunctionExpression;
10386   return true;
10387 }
10388 
10389 /// \brief Add a single candidate to the overload set.
10390 static void AddOverloadedCallCandidate(Sema &S,
10391                                        DeclAccessPair FoundDecl,
10392                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10393                                        ArrayRef<Expr *> Args,
10394                                        OverloadCandidateSet &CandidateSet,
10395                                        bool PartialOverloading,
10396                                        bool KnownValid) {
10397   NamedDecl *Callee = FoundDecl.getDecl();
10398   if (isa<UsingShadowDecl>(Callee))
10399     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10400 
10401   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10402     if (ExplicitTemplateArgs) {
10403       assert(!KnownValid && "Explicit template arguments?");
10404       return;
10405     }
10406     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10407                            /*SuppressUsedConversions=*/false,
10408                            PartialOverloading);
10409     return;
10410   }
10411 
10412   if (FunctionTemplateDecl *FuncTemplate
10413       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10414     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10415                                    ExplicitTemplateArgs, Args, CandidateSet,
10416                                    /*SuppressUsedConversions=*/false,
10417                                    PartialOverloading);
10418     return;
10419   }
10420 
10421   assert(!KnownValid && "unhandled case in overloaded call candidate");
10422 }
10423 
10424 /// \brief Add the overload candidates named by callee and/or found by argument
10425 /// dependent lookup to the given overload set.
10426 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10427                                        ArrayRef<Expr *> Args,
10428                                        OverloadCandidateSet &CandidateSet,
10429                                        bool PartialOverloading) {
10430 
10431 #ifndef NDEBUG
10432   // Verify that ArgumentDependentLookup is consistent with the rules
10433   // in C++0x [basic.lookup.argdep]p3:
10434   //
10435   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10436   //   and let Y be the lookup set produced by argument dependent
10437   //   lookup (defined as follows). If X contains
10438   //
10439   //     -- a declaration of a class member, or
10440   //
10441   //     -- a block-scope function declaration that is not a
10442   //        using-declaration, or
10443   //
10444   //     -- a declaration that is neither a function or a function
10445   //        template
10446   //
10447   //   then Y is empty.
10448 
10449   if (ULE->requiresADL()) {
10450     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10451            E = ULE->decls_end(); I != E; ++I) {
10452       assert(!(*I)->getDeclContext()->isRecord());
10453       assert(isa<UsingShadowDecl>(*I) ||
10454              !(*I)->getDeclContext()->isFunctionOrMethod());
10455       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10456     }
10457   }
10458 #endif
10459 
10460   // It would be nice to avoid this copy.
10461   TemplateArgumentListInfo TABuffer;
10462   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10463   if (ULE->hasExplicitTemplateArgs()) {
10464     ULE->copyTemplateArgumentsInto(TABuffer);
10465     ExplicitTemplateArgs = &TABuffer;
10466   }
10467 
10468   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10469          E = ULE->decls_end(); I != E; ++I)
10470     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10471                                CandidateSet, PartialOverloading,
10472                                /*KnownValid*/ true);
10473 
10474   if (ULE->requiresADL())
10475     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10476                                          Args, ExplicitTemplateArgs,
10477                                          CandidateSet, PartialOverloading);
10478 }
10479 
10480 /// Determine whether a declaration with the specified name could be moved into
10481 /// a different namespace.
10482 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10483   switch (Name.getCXXOverloadedOperator()) {
10484   case OO_New: case OO_Array_New:
10485   case OO_Delete: case OO_Array_Delete:
10486     return false;
10487 
10488   default:
10489     return true;
10490   }
10491 }
10492 
10493 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10494 /// template, where the non-dependent name was declared after the template
10495 /// was defined. This is common in code written for a compilers which do not
10496 /// correctly implement two-stage name lookup.
10497 ///
10498 /// Returns true if a viable candidate was found and a diagnostic was issued.
10499 static bool
10500 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10501                        const CXXScopeSpec &SS, LookupResult &R,
10502                        OverloadCandidateSet::CandidateSetKind CSK,
10503                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10504                        ArrayRef<Expr *> Args) {
10505   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10506     return false;
10507 
10508   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10509     if (DC->isTransparentContext())
10510       continue;
10511 
10512     SemaRef.LookupQualifiedName(R, DC);
10513 
10514     if (!R.empty()) {
10515       R.suppressDiagnostics();
10516 
10517       if (isa<CXXRecordDecl>(DC)) {
10518         // Don't diagnose names we find in classes; we get much better
10519         // diagnostics for these from DiagnoseEmptyLookup.
10520         R.clear();
10521         return false;
10522       }
10523 
10524       OverloadCandidateSet Candidates(FnLoc, CSK);
10525       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10526         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10527                                    ExplicitTemplateArgs, Args,
10528                                    Candidates, false, /*KnownValid*/ false);
10529 
10530       OverloadCandidateSet::iterator Best;
10531       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10532         // No viable functions. Don't bother the user with notes for functions
10533         // which don't work and shouldn't be found anyway.
10534         R.clear();
10535         return false;
10536       }
10537 
10538       // Find the namespaces where ADL would have looked, and suggest
10539       // declaring the function there instead.
10540       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10541       Sema::AssociatedClassSet AssociatedClasses;
10542       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10543                                                  AssociatedNamespaces,
10544                                                  AssociatedClasses);
10545       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10546       if (canBeDeclaredInNamespace(R.getLookupName())) {
10547         DeclContext *Std = SemaRef.getStdNamespace();
10548         for (Sema::AssociatedNamespaceSet::iterator
10549                it = AssociatedNamespaces.begin(),
10550                end = AssociatedNamespaces.end(); it != end; ++it) {
10551           // Never suggest declaring a function within namespace 'std'.
10552           if (Std && Std->Encloses(*it))
10553             continue;
10554 
10555           // Never suggest declaring a function within a namespace with a
10556           // reserved name, like __gnu_cxx.
10557           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10558           if (NS &&
10559               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10560             continue;
10561 
10562           SuggestedNamespaces.insert(*it);
10563         }
10564       }
10565 
10566       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10567         << R.getLookupName();
10568       if (SuggestedNamespaces.empty()) {
10569         SemaRef.Diag(Best->Function->getLocation(),
10570                      diag::note_not_found_by_two_phase_lookup)
10571           << R.getLookupName() << 0;
10572       } else if (SuggestedNamespaces.size() == 1) {
10573         SemaRef.Diag(Best->Function->getLocation(),
10574                      diag::note_not_found_by_two_phase_lookup)
10575           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10576       } else {
10577         // FIXME: It would be useful to list the associated namespaces here,
10578         // but the diagnostics infrastructure doesn't provide a way to produce
10579         // a localized representation of a list of items.
10580         SemaRef.Diag(Best->Function->getLocation(),
10581                      diag::note_not_found_by_two_phase_lookup)
10582           << R.getLookupName() << 2;
10583       }
10584 
10585       // Try to recover by calling this function.
10586       return true;
10587     }
10588 
10589     R.clear();
10590   }
10591 
10592   return false;
10593 }
10594 
10595 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10596 /// template, where the non-dependent operator was declared after the template
10597 /// was defined.
10598 ///
10599 /// Returns true if a viable candidate was found and a diagnostic was issued.
10600 static bool
10601 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10602                                SourceLocation OpLoc,
10603                                ArrayRef<Expr *> Args) {
10604   DeclarationName OpName =
10605     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10606   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10607   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10608                                 OverloadCandidateSet::CSK_Operator,
10609                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10610 }
10611 
10612 namespace {
10613 class BuildRecoveryCallExprRAII {
10614   Sema &SemaRef;
10615 public:
10616   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10617     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10618     SemaRef.IsBuildingRecoveryCallExpr = true;
10619   }
10620 
10621   ~BuildRecoveryCallExprRAII() {
10622     SemaRef.IsBuildingRecoveryCallExpr = false;
10623   }
10624 };
10625 
10626 }
10627 
10628 static std::unique_ptr<CorrectionCandidateCallback>
10629 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10630               bool HasTemplateArgs, bool AllowTypoCorrection) {
10631   if (!AllowTypoCorrection)
10632     return llvm::make_unique<NoTypoCorrectionCCC>();
10633   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10634                                                   HasTemplateArgs, ME);
10635 }
10636 
10637 /// Attempts to recover from a call where no functions were found.
10638 ///
10639 /// Returns true if new candidates were found.
10640 static ExprResult
10641 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10642                       UnresolvedLookupExpr *ULE,
10643                       SourceLocation LParenLoc,
10644                       MutableArrayRef<Expr *> Args,
10645                       SourceLocation RParenLoc,
10646                       bool EmptyLookup, bool AllowTypoCorrection) {
10647   // Do not try to recover if it is already building a recovery call.
10648   // This stops infinite loops for template instantiations like
10649   //
10650   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10651   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10652   //
10653   if (SemaRef.IsBuildingRecoveryCallExpr)
10654     return ExprError();
10655   BuildRecoveryCallExprRAII RCE(SemaRef);
10656 
10657   CXXScopeSpec SS;
10658   SS.Adopt(ULE->getQualifierLoc());
10659   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10660 
10661   TemplateArgumentListInfo TABuffer;
10662   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10663   if (ULE->hasExplicitTemplateArgs()) {
10664     ULE->copyTemplateArgumentsInto(TABuffer);
10665     ExplicitTemplateArgs = &TABuffer;
10666   }
10667 
10668   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10669                  Sema::LookupOrdinaryName);
10670   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10671                               OverloadCandidateSet::CSK_Normal,
10672                               ExplicitTemplateArgs, Args) &&
10673       (!EmptyLookup ||
10674        SemaRef.DiagnoseEmptyLookup(
10675            S, SS, R,
10676            MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10677                          ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10678            ExplicitTemplateArgs, Args)))
10679     return ExprError();
10680 
10681   assert(!R.empty() && "lookup results empty despite recovery");
10682 
10683   // Build an implicit member call if appropriate.  Just drop the
10684   // casts and such from the call, we don't really care.
10685   ExprResult NewFn = ExprError();
10686   if ((*R.begin())->isCXXClassMember())
10687     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10688                                                     R, ExplicitTemplateArgs);
10689   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10690     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10691                                         ExplicitTemplateArgs);
10692   else
10693     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10694 
10695   if (NewFn.isInvalid())
10696     return ExprError();
10697 
10698   // This shouldn't cause an infinite loop because we're giving it
10699   // an expression with viable lookup results, which should never
10700   // end up here.
10701   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10702                                MultiExprArg(Args.data(), Args.size()),
10703                                RParenLoc);
10704 }
10705 
10706 /// \brief Constructs and populates an OverloadedCandidateSet from
10707 /// the given function.
10708 /// \returns true when an the ExprResult output parameter has been set.
10709 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10710                                   UnresolvedLookupExpr *ULE,
10711                                   MultiExprArg Args,
10712                                   SourceLocation RParenLoc,
10713                                   OverloadCandidateSet *CandidateSet,
10714                                   ExprResult *Result) {
10715 #ifndef NDEBUG
10716   if (ULE->requiresADL()) {
10717     // To do ADL, we must have found an unqualified name.
10718     assert(!ULE->getQualifier() && "qualified name with ADL");
10719 
10720     // We don't perform ADL for implicit declarations of builtins.
10721     // Verify that this was correctly set up.
10722     FunctionDecl *F;
10723     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10724         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10725         F->getBuiltinID() && F->isImplicit())
10726       llvm_unreachable("performing ADL for builtin");
10727 
10728     // We don't perform ADL in C.
10729     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10730   }
10731 #endif
10732 
10733   UnbridgedCastsSet UnbridgedCasts;
10734   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10735     *Result = ExprError();
10736     return true;
10737   }
10738 
10739   // Add the functions denoted by the callee to the set of candidate
10740   // functions, including those from argument-dependent lookup.
10741   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10742 
10743   // If we found nothing, try to recover.
10744   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10745   // out if it fails.
10746   if (CandidateSet->empty()) {
10747     // In Microsoft mode, if we are inside a template class member function then
10748     // create a type dependent CallExpr. The goal is to postpone name lookup
10749     // to instantiation time to be able to search into type dependent base
10750     // classes.
10751     if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
10752         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10753       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10754                                             Context.DependentTy, VK_RValue,
10755                                             RParenLoc);
10756       CE->setTypeDependent(true);
10757       *Result = CE;
10758       return true;
10759     }
10760     return false;
10761   }
10762 
10763   UnbridgedCasts.restore();
10764   return false;
10765 }
10766 
10767 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10768 /// the completed call expression. If overload resolution fails, emits
10769 /// diagnostics and returns ExprError()
10770 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10771                                            UnresolvedLookupExpr *ULE,
10772                                            SourceLocation LParenLoc,
10773                                            MultiExprArg Args,
10774                                            SourceLocation RParenLoc,
10775                                            Expr *ExecConfig,
10776                                            OverloadCandidateSet *CandidateSet,
10777                                            OverloadCandidateSet::iterator *Best,
10778                                            OverloadingResult OverloadResult,
10779                                            bool AllowTypoCorrection) {
10780   if (CandidateSet->empty())
10781     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10782                                  RParenLoc, /*EmptyLookup=*/true,
10783                                  AllowTypoCorrection);
10784 
10785   switch (OverloadResult) {
10786   case OR_Success: {
10787     FunctionDecl *FDecl = (*Best)->Function;
10788     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10789     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10790       return ExprError();
10791     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10792     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10793                                          ExecConfig);
10794   }
10795 
10796   case OR_No_Viable_Function: {
10797     // Try to recover by looking for viable functions which the user might
10798     // have meant to call.
10799     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10800                                                 Args, RParenLoc,
10801                                                 /*EmptyLookup=*/false,
10802                                                 AllowTypoCorrection);
10803     if (!Recovery.isInvalid())
10804       return Recovery;
10805 
10806     SemaRef.Diag(Fn->getLocStart(),
10807          diag::err_ovl_no_viable_function_in_call)
10808       << ULE->getName() << Fn->getSourceRange();
10809     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10810     break;
10811   }
10812 
10813   case OR_Ambiguous:
10814     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10815       << ULE->getName() << Fn->getSourceRange();
10816     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10817     break;
10818 
10819   case OR_Deleted: {
10820     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10821       << (*Best)->Function->isDeleted()
10822       << ULE->getName()
10823       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10824       << Fn->getSourceRange();
10825     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10826 
10827     // We emitted an error for the unvailable/deleted function call but keep
10828     // the call in the AST.
10829     FunctionDecl *FDecl = (*Best)->Function;
10830     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10831     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10832                                          ExecConfig);
10833   }
10834   }
10835 
10836   // Overload resolution failed.
10837   return ExprError();
10838 }
10839 
10840 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10841 /// (which eventually refers to the declaration Func) and the call
10842 /// arguments Args/NumArgs, attempt to resolve the function call down
10843 /// to a specific function. If overload resolution succeeds, returns
10844 /// the call expression produced by overload resolution.
10845 /// Otherwise, emits diagnostics and returns ExprError.
10846 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10847                                          UnresolvedLookupExpr *ULE,
10848                                          SourceLocation LParenLoc,
10849                                          MultiExprArg Args,
10850                                          SourceLocation RParenLoc,
10851                                          Expr *ExecConfig,
10852                                          bool AllowTypoCorrection) {
10853   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10854                                     OverloadCandidateSet::CSK_Normal);
10855   ExprResult result;
10856 
10857   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10858                              &result))
10859     return result;
10860 
10861   OverloadCandidateSet::iterator Best;
10862   OverloadingResult OverloadResult =
10863       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10864 
10865   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10866                                   RParenLoc, ExecConfig, &CandidateSet,
10867                                   &Best, OverloadResult,
10868                                   AllowTypoCorrection);
10869 }
10870 
10871 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10872   return Functions.size() > 1 ||
10873     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10874 }
10875 
10876 /// \brief Create a unary operation that may resolve to an overloaded
10877 /// operator.
10878 ///
10879 /// \param OpLoc The location of the operator itself (e.g., '*').
10880 ///
10881 /// \param OpcIn The UnaryOperator::Opcode that describes this
10882 /// operator.
10883 ///
10884 /// \param Fns The set of non-member functions that will be
10885 /// considered by overload resolution. The caller needs to build this
10886 /// set based on the context using, e.g.,
10887 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10888 /// set should not contain any member functions; those will be added
10889 /// by CreateOverloadedUnaryOp().
10890 ///
10891 /// \param Input The input argument.
10892 ExprResult
10893 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10894                               const UnresolvedSetImpl &Fns,
10895                               Expr *Input) {
10896   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10897 
10898   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10899   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10900   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10901   // TODO: provide better source location info.
10902   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10903 
10904   if (checkPlaceholderForOverload(*this, Input))
10905     return ExprError();
10906 
10907   Expr *Args[2] = { Input, nullptr };
10908   unsigned NumArgs = 1;
10909 
10910   // For post-increment and post-decrement, add the implicit '0' as
10911   // the second argument, so that we know this is a post-increment or
10912   // post-decrement.
10913   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10914     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10915     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10916                                      SourceLocation());
10917     NumArgs = 2;
10918   }
10919 
10920   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10921 
10922   if (Input->isTypeDependent()) {
10923     if (Fns.empty())
10924       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10925                                          VK_RValue, OK_Ordinary, OpLoc);
10926 
10927     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10928     UnresolvedLookupExpr *Fn
10929       = UnresolvedLookupExpr::Create(Context, NamingClass,
10930                                      NestedNameSpecifierLoc(), OpNameInfo,
10931                                      /*ADL*/ true, IsOverloaded(Fns),
10932                                      Fns.begin(), Fns.end());
10933     return new (Context)
10934         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10935                             VK_RValue, OpLoc, false);
10936   }
10937 
10938   // Build an empty overload set.
10939   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10940 
10941   // Add the candidates from the given function set.
10942   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
10943 
10944   // Add operator candidates that are member functions.
10945   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10946 
10947   // Add candidates from ADL.
10948   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10949                                        /*ExplicitTemplateArgs*/nullptr,
10950                                        CandidateSet);
10951 
10952   // Add builtin operator candidates.
10953   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10954 
10955   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10956 
10957   // Perform overload resolution.
10958   OverloadCandidateSet::iterator Best;
10959   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10960   case OR_Success: {
10961     // We found a built-in operator or an overloaded operator.
10962     FunctionDecl *FnDecl = Best->Function;
10963 
10964     if (FnDecl) {
10965       // We matched an overloaded operator. Build a call to that
10966       // operator.
10967 
10968       // Convert the arguments.
10969       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10970         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10971 
10972         ExprResult InputRes =
10973           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10974                                               Best->FoundDecl, Method);
10975         if (InputRes.isInvalid())
10976           return ExprError();
10977         Input = InputRes.get();
10978       } else {
10979         // Convert the arguments.
10980         ExprResult InputInit
10981           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10982                                                       Context,
10983                                                       FnDecl->getParamDecl(0)),
10984                                       SourceLocation(),
10985                                       Input);
10986         if (InputInit.isInvalid())
10987           return ExprError();
10988         Input = InputInit.get();
10989       }
10990 
10991       // Build the actual expression node.
10992       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10993                                                 HadMultipleCandidates, OpLoc);
10994       if (FnExpr.isInvalid())
10995         return ExprError();
10996 
10997       // Determine the result type.
10998       QualType ResultTy = FnDecl->getReturnType();
10999       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11000       ResultTy = ResultTy.getNonLValueExprType(Context);
11001 
11002       Args[0] = Input;
11003       CallExpr *TheCall =
11004         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11005                                           ResultTy, VK, OpLoc, false);
11006 
11007       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11008         return ExprError();
11009 
11010       return MaybeBindToTemporary(TheCall);
11011     } else {
11012       // We matched a built-in operator. Convert the arguments, then
11013       // break out so that we will build the appropriate built-in
11014       // operator node.
11015       ExprResult InputRes =
11016         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11017                                   Best->Conversions[0], AA_Passing);
11018       if (InputRes.isInvalid())
11019         return ExprError();
11020       Input = InputRes.get();
11021       break;
11022     }
11023   }
11024 
11025   case OR_No_Viable_Function:
11026     // This is an erroneous use of an operator which can be overloaded by
11027     // a non-member function. Check for non-member operators which were
11028     // defined too late to be candidates.
11029     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11030       // FIXME: Recover by calling the found function.
11031       return ExprError();
11032 
11033     // No viable function; fall through to handling this as a
11034     // built-in operator, which will produce an error message for us.
11035     break;
11036 
11037   case OR_Ambiguous:
11038     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11039         << UnaryOperator::getOpcodeStr(Opc)
11040         << Input->getType()
11041         << Input->getSourceRange();
11042     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11043                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11044     return ExprError();
11045 
11046   case OR_Deleted:
11047     Diag(OpLoc, diag::err_ovl_deleted_oper)
11048       << Best->Function->isDeleted()
11049       << UnaryOperator::getOpcodeStr(Opc)
11050       << getDeletedOrUnavailableSuffix(Best->Function)
11051       << Input->getSourceRange();
11052     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11053                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11054     return ExprError();
11055   }
11056 
11057   // Either we found no viable overloaded operator or we matched a
11058   // built-in operator. In either case, fall through to trying to
11059   // build a built-in operation.
11060   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11061 }
11062 
11063 /// \brief Create a binary operation that may resolve to an overloaded
11064 /// operator.
11065 ///
11066 /// \param OpLoc The location of the operator itself (e.g., '+').
11067 ///
11068 /// \param OpcIn The BinaryOperator::Opcode that describes this
11069 /// operator.
11070 ///
11071 /// \param Fns The set of non-member functions that will be
11072 /// considered by overload resolution. The caller needs to build this
11073 /// set based on the context using, e.g.,
11074 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11075 /// set should not contain any member functions; those will be added
11076 /// by CreateOverloadedBinOp().
11077 ///
11078 /// \param LHS Left-hand argument.
11079 /// \param RHS Right-hand argument.
11080 ExprResult
11081 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11082                             unsigned OpcIn,
11083                             const UnresolvedSetImpl &Fns,
11084                             Expr *LHS, Expr *RHS) {
11085   Expr *Args[2] = { LHS, RHS };
11086   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11087 
11088   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11089   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11090   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11091 
11092   // If either side is type-dependent, create an appropriate dependent
11093   // expression.
11094   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11095     if (Fns.empty()) {
11096       // If there are no functions to store, just build a dependent
11097       // BinaryOperator or CompoundAssignment.
11098       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11099         return new (Context) BinaryOperator(
11100             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11101             OpLoc, FPFeatures.fp_contract);
11102 
11103       return new (Context) CompoundAssignOperator(
11104           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11105           Context.DependentTy, Context.DependentTy, OpLoc,
11106           FPFeatures.fp_contract);
11107     }
11108 
11109     // FIXME: save results of ADL from here?
11110     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11111     // TODO: provide better source location info in DNLoc component.
11112     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11113     UnresolvedLookupExpr *Fn
11114       = UnresolvedLookupExpr::Create(Context, NamingClass,
11115                                      NestedNameSpecifierLoc(), OpNameInfo,
11116                                      /*ADL*/ true, IsOverloaded(Fns),
11117                                      Fns.begin(), Fns.end());
11118     return new (Context)
11119         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11120                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11121   }
11122 
11123   // Always do placeholder-like conversions on the RHS.
11124   if (checkPlaceholderForOverload(*this, Args[1]))
11125     return ExprError();
11126 
11127   // Do placeholder-like conversion on the LHS; note that we should
11128   // not get here with a PseudoObject LHS.
11129   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11130   if (checkPlaceholderForOverload(*this, Args[0]))
11131     return ExprError();
11132 
11133   // If this is the assignment operator, we only perform overload resolution
11134   // if the left-hand side is a class or enumeration type. This is actually
11135   // a hack. The standard requires that we do overload resolution between the
11136   // various built-in candidates, but as DR507 points out, this can lead to
11137   // problems. So we do it this way, which pretty much follows what GCC does.
11138   // Note that we go the traditional code path for compound assignment forms.
11139   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11140     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11141 
11142   // If this is the .* operator, which is not overloadable, just
11143   // create a built-in binary operator.
11144   if (Opc == BO_PtrMemD)
11145     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11146 
11147   // Build an empty overload set.
11148   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11149 
11150   // Add the candidates from the given function set.
11151   AddFunctionCandidates(Fns, Args, CandidateSet);
11152 
11153   // Add operator candidates that are member functions.
11154   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11155 
11156   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11157   // performed for an assignment operator (nor for operator[] nor operator->,
11158   // which don't get here).
11159   if (Opc != BO_Assign)
11160     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11161                                          /*ExplicitTemplateArgs*/ nullptr,
11162                                          CandidateSet);
11163 
11164   // Add builtin operator candidates.
11165   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11166 
11167   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11168 
11169   // Perform overload resolution.
11170   OverloadCandidateSet::iterator Best;
11171   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11172     case OR_Success: {
11173       // We found a built-in operator or an overloaded operator.
11174       FunctionDecl *FnDecl = Best->Function;
11175 
11176       if (FnDecl) {
11177         // We matched an overloaded operator. Build a call to that
11178         // operator.
11179 
11180         // Convert the arguments.
11181         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11182           // Best->Access is only meaningful for class members.
11183           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11184 
11185           ExprResult Arg1 =
11186             PerformCopyInitialization(
11187               InitializedEntity::InitializeParameter(Context,
11188                                                      FnDecl->getParamDecl(0)),
11189               SourceLocation(), Args[1]);
11190           if (Arg1.isInvalid())
11191             return ExprError();
11192 
11193           ExprResult Arg0 =
11194             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11195                                                 Best->FoundDecl, Method);
11196           if (Arg0.isInvalid())
11197             return ExprError();
11198           Args[0] = Arg0.getAs<Expr>();
11199           Args[1] = RHS = Arg1.getAs<Expr>();
11200         } else {
11201           // Convert the arguments.
11202           ExprResult Arg0 = PerformCopyInitialization(
11203             InitializedEntity::InitializeParameter(Context,
11204                                                    FnDecl->getParamDecl(0)),
11205             SourceLocation(), Args[0]);
11206           if (Arg0.isInvalid())
11207             return ExprError();
11208 
11209           ExprResult Arg1 =
11210             PerformCopyInitialization(
11211               InitializedEntity::InitializeParameter(Context,
11212                                                      FnDecl->getParamDecl(1)),
11213               SourceLocation(), Args[1]);
11214           if (Arg1.isInvalid())
11215             return ExprError();
11216           Args[0] = LHS = Arg0.getAs<Expr>();
11217           Args[1] = RHS = Arg1.getAs<Expr>();
11218         }
11219 
11220         // Build the actual expression node.
11221         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11222                                                   Best->FoundDecl,
11223                                                   HadMultipleCandidates, OpLoc);
11224         if (FnExpr.isInvalid())
11225           return ExprError();
11226 
11227         // Determine the result type.
11228         QualType ResultTy = FnDecl->getReturnType();
11229         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11230         ResultTy = ResultTy.getNonLValueExprType(Context);
11231 
11232         CXXOperatorCallExpr *TheCall =
11233           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11234                                             Args, ResultTy, VK, OpLoc,
11235                                             FPFeatures.fp_contract);
11236 
11237         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11238                                 FnDecl))
11239           return ExprError();
11240 
11241         ArrayRef<const Expr *> ArgsArray(Args, 2);
11242         // Cut off the implicit 'this'.
11243         if (isa<CXXMethodDecl>(FnDecl))
11244           ArgsArray = ArgsArray.slice(1);
11245 
11246         // Check for a self move.
11247         if (Op == OO_Equal)
11248           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11249 
11250         checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11251                   TheCall->getSourceRange(), VariadicDoesNotApply);
11252 
11253         return MaybeBindToTemporary(TheCall);
11254       } else {
11255         // We matched a built-in operator. Convert the arguments, then
11256         // break out so that we will build the appropriate built-in
11257         // operator node.
11258         ExprResult ArgsRes0 =
11259           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11260                                     Best->Conversions[0], AA_Passing);
11261         if (ArgsRes0.isInvalid())
11262           return ExprError();
11263         Args[0] = ArgsRes0.get();
11264 
11265         ExprResult ArgsRes1 =
11266           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11267                                     Best->Conversions[1], AA_Passing);
11268         if (ArgsRes1.isInvalid())
11269           return ExprError();
11270         Args[1] = ArgsRes1.get();
11271         break;
11272       }
11273     }
11274 
11275     case OR_No_Viable_Function: {
11276       // C++ [over.match.oper]p9:
11277       //   If the operator is the operator , [...] and there are no
11278       //   viable functions, then the operator is assumed to be the
11279       //   built-in operator and interpreted according to clause 5.
11280       if (Opc == BO_Comma)
11281         break;
11282 
11283       // For class as left operand for assignment or compound assigment
11284       // operator do not fall through to handling in built-in, but report that
11285       // no overloaded assignment operator found
11286       ExprResult Result = ExprError();
11287       if (Args[0]->getType()->isRecordType() &&
11288           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11289         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11290              << BinaryOperator::getOpcodeStr(Opc)
11291              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11292         if (Args[0]->getType()->isIncompleteType()) {
11293           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11294             << Args[0]->getType()
11295             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11296         }
11297       } else {
11298         // This is an erroneous use of an operator which can be overloaded by
11299         // a non-member function. Check for non-member operators which were
11300         // defined too late to be candidates.
11301         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11302           // FIXME: Recover by calling the found function.
11303           return ExprError();
11304 
11305         // No viable function; try to create a built-in operation, which will
11306         // produce an error. Then, show the non-viable candidates.
11307         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11308       }
11309       assert(Result.isInvalid() &&
11310              "C++ binary operator overloading is missing candidates!");
11311       if (Result.isInvalid())
11312         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11313                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11314       return Result;
11315     }
11316 
11317     case OR_Ambiguous:
11318       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11319           << BinaryOperator::getOpcodeStr(Opc)
11320           << Args[0]->getType() << Args[1]->getType()
11321           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11322       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11323                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11324       return ExprError();
11325 
11326     case OR_Deleted:
11327       if (isImplicitlyDeleted(Best->Function)) {
11328         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11329         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11330           << Context.getRecordType(Method->getParent())
11331           << getSpecialMember(Method);
11332 
11333         // The user probably meant to call this special member. Just
11334         // explain why it's deleted.
11335         NoteDeletedFunction(Method);
11336         return ExprError();
11337       } else {
11338         Diag(OpLoc, diag::err_ovl_deleted_oper)
11339           << Best->Function->isDeleted()
11340           << BinaryOperator::getOpcodeStr(Opc)
11341           << getDeletedOrUnavailableSuffix(Best->Function)
11342           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11343       }
11344       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11345                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11346       return ExprError();
11347   }
11348 
11349   // We matched a built-in operator; build it.
11350   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11351 }
11352 
11353 ExprResult
11354 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11355                                          SourceLocation RLoc,
11356                                          Expr *Base, Expr *Idx) {
11357   Expr *Args[2] = { Base, Idx };
11358   DeclarationName OpName =
11359       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11360 
11361   // If either side is type-dependent, create an appropriate dependent
11362   // expression.
11363   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11364 
11365     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11366     // CHECKME: no 'operator' keyword?
11367     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11368     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11369     UnresolvedLookupExpr *Fn
11370       = UnresolvedLookupExpr::Create(Context, NamingClass,
11371                                      NestedNameSpecifierLoc(), OpNameInfo,
11372                                      /*ADL*/ true, /*Overloaded*/ false,
11373                                      UnresolvedSetIterator(),
11374                                      UnresolvedSetIterator());
11375     // Can't add any actual overloads yet
11376 
11377     return new (Context)
11378         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11379                             Context.DependentTy, VK_RValue, RLoc, false);
11380   }
11381 
11382   // Handle placeholders on both operands.
11383   if (checkPlaceholderForOverload(*this, Args[0]))
11384     return ExprError();
11385   if (checkPlaceholderForOverload(*this, Args[1]))
11386     return ExprError();
11387 
11388   // Build an empty overload set.
11389   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11390 
11391   // Subscript can only be overloaded as a member function.
11392 
11393   // Add operator candidates that are member functions.
11394   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11395 
11396   // Add builtin operator candidates.
11397   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11398 
11399   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11400 
11401   // Perform overload resolution.
11402   OverloadCandidateSet::iterator Best;
11403   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11404     case OR_Success: {
11405       // We found a built-in operator or an overloaded operator.
11406       FunctionDecl *FnDecl = Best->Function;
11407 
11408       if (FnDecl) {
11409         // We matched an overloaded operator. Build a call to that
11410         // operator.
11411 
11412         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11413 
11414         // Convert the arguments.
11415         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11416         ExprResult Arg0 =
11417           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11418                                               Best->FoundDecl, Method);
11419         if (Arg0.isInvalid())
11420           return ExprError();
11421         Args[0] = Arg0.get();
11422 
11423         // Convert the arguments.
11424         ExprResult InputInit
11425           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11426                                                       Context,
11427                                                       FnDecl->getParamDecl(0)),
11428                                       SourceLocation(),
11429                                       Args[1]);
11430         if (InputInit.isInvalid())
11431           return ExprError();
11432 
11433         Args[1] = InputInit.getAs<Expr>();
11434 
11435         // Build the actual expression node.
11436         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11437         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11438         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11439                                                   Best->FoundDecl,
11440                                                   HadMultipleCandidates,
11441                                                   OpLocInfo.getLoc(),
11442                                                   OpLocInfo.getInfo());
11443         if (FnExpr.isInvalid())
11444           return ExprError();
11445 
11446         // Determine the result type
11447         QualType ResultTy = FnDecl->getReturnType();
11448         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11449         ResultTy = ResultTy.getNonLValueExprType(Context);
11450 
11451         CXXOperatorCallExpr *TheCall =
11452           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11453                                             FnExpr.get(), Args,
11454                                             ResultTy, VK, RLoc,
11455                                             false);
11456 
11457         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11458           return ExprError();
11459 
11460         return MaybeBindToTemporary(TheCall);
11461       } else {
11462         // We matched a built-in operator. Convert the arguments, then
11463         // break out so that we will build the appropriate built-in
11464         // operator node.
11465         ExprResult ArgsRes0 =
11466           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11467                                     Best->Conversions[0], AA_Passing);
11468         if (ArgsRes0.isInvalid())
11469           return ExprError();
11470         Args[0] = ArgsRes0.get();
11471 
11472         ExprResult ArgsRes1 =
11473           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11474                                     Best->Conversions[1], AA_Passing);
11475         if (ArgsRes1.isInvalid())
11476           return ExprError();
11477         Args[1] = ArgsRes1.get();
11478 
11479         break;
11480       }
11481     }
11482 
11483     case OR_No_Viable_Function: {
11484       if (CandidateSet.empty())
11485         Diag(LLoc, diag::err_ovl_no_oper)
11486           << Args[0]->getType() << /*subscript*/ 0
11487           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11488       else
11489         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11490           << Args[0]->getType()
11491           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11492       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11493                                   "[]", LLoc);
11494       return ExprError();
11495     }
11496 
11497     case OR_Ambiguous:
11498       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11499           << "[]"
11500           << Args[0]->getType() << Args[1]->getType()
11501           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11502       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11503                                   "[]", LLoc);
11504       return ExprError();
11505 
11506     case OR_Deleted:
11507       Diag(LLoc, diag::err_ovl_deleted_oper)
11508         << Best->Function->isDeleted() << "[]"
11509         << getDeletedOrUnavailableSuffix(Best->Function)
11510         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11511       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11512                                   "[]", LLoc);
11513       return ExprError();
11514     }
11515 
11516   // We matched a built-in operator; build it.
11517   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11518 }
11519 
11520 /// BuildCallToMemberFunction - Build a call to a member
11521 /// function. MemExpr is the expression that refers to the member
11522 /// function (and includes the object parameter), Args/NumArgs are the
11523 /// arguments to the function call (not including the object
11524 /// parameter). The caller needs to validate that the member
11525 /// expression refers to a non-static member function or an overloaded
11526 /// member function.
11527 ExprResult
11528 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11529                                 SourceLocation LParenLoc,
11530                                 MultiExprArg Args,
11531                                 SourceLocation RParenLoc) {
11532   assert(MemExprE->getType() == Context.BoundMemberTy ||
11533          MemExprE->getType() == Context.OverloadTy);
11534 
11535   // Dig out the member expression. This holds both the object
11536   // argument and the member function we're referring to.
11537   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11538 
11539   // Determine whether this is a call to a pointer-to-member function.
11540   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11541     assert(op->getType() == Context.BoundMemberTy);
11542     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11543 
11544     QualType fnType =
11545       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11546 
11547     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11548     QualType resultType = proto->getCallResultType(Context);
11549     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11550 
11551     // Check that the object type isn't more qualified than the
11552     // member function we're calling.
11553     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11554 
11555     QualType objectType = op->getLHS()->getType();
11556     if (op->getOpcode() == BO_PtrMemI)
11557       objectType = objectType->castAs<PointerType>()->getPointeeType();
11558     Qualifiers objectQuals = objectType.getQualifiers();
11559 
11560     Qualifiers difference = objectQuals - funcQuals;
11561     difference.removeObjCGCAttr();
11562     difference.removeAddressSpace();
11563     if (difference) {
11564       std::string qualsString = difference.getAsString();
11565       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11566         << fnType.getUnqualifiedType()
11567         << qualsString
11568         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11569     }
11570 
11571     if (resultType->isMemberPointerType())
11572       if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11573         RequireCompleteType(LParenLoc, resultType, 0);
11574 
11575     CXXMemberCallExpr *call
11576       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11577                                         resultType, valueKind, RParenLoc);
11578 
11579     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11580                             call, nullptr))
11581       return ExprError();
11582 
11583     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11584       return ExprError();
11585 
11586     if (CheckOtherCall(call, proto))
11587       return ExprError();
11588 
11589     return MaybeBindToTemporary(call);
11590   }
11591 
11592   UnbridgedCastsSet UnbridgedCasts;
11593   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11594     return ExprError();
11595 
11596   MemberExpr *MemExpr;
11597   CXXMethodDecl *Method = nullptr;
11598   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11599   NestedNameSpecifier *Qualifier = nullptr;
11600   if (isa<MemberExpr>(NakedMemExpr)) {
11601     MemExpr = cast<MemberExpr>(NakedMemExpr);
11602     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11603     FoundDecl = MemExpr->getFoundDecl();
11604     Qualifier = MemExpr->getQualifier();
11605     UnbridgedCasts.restore();
11606   } else {
11607     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11608     Qualifier = UnresExpr->getQualifier();
11609 
11610     QualType ObjectType = UnresExpr->getBaseType();
11611     Expr::Classification ObjectClassification
11612       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11613                             : UnresExpr->getBase()->Classify(Context);
11614 
11615     // Add overload candidates
11616     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11617                                       OverloadCandidateSet::CSK_Normal);
11618 
11619     // FIXME: avoid copy.
11620     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11621     if (UnresExpr->hasExplicitTemplateArgs()) {
11622       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11623       TemplateArgs = &TemplateArgsBuffer;
11624     }
11625 
11626     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11627            E = UnresExpr->decls_end(); I != E; ++I) {
11628 
11629       NamedDecl *Func = *I;
11630       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11631       if (isa<UsingShadowDecl>(Func))
11632         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11633 
11634 
11635       // Microsoft supports direct constructor calls.
11636       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11637         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11638                              Args, CandidateSet);
11639       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11640         // If explicit template arguments were provided, we can't call a
11641         // non-template member function.
11642         if (TemplateArgs)
11643           continue;
11644 
11645         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11646                            ObjectClassification, Args, CandidateSet,
11647                            /*SuppressUserConversions=*/false);
11648       } else {
11649         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11650                                    I.getPair(), ActingDC, TemplateArgs,
11651                                    ObjectType,  ObjectClassification,
11652                                    Args, CandidateSet,
11653                                    /*SuppressUsedConversions=*/false);
11654       }
11655     }
11656 
11657     DeclarationName DeclName = UnresExpr->getMemberName();
11658 
11659     UnbridgedCasts.restore();
11660 
11661     OverloadCandidateSet::iterator Best;
11662     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11663                                             Best)) {
11664     case OR_Success:
11665       Method = cast<CXXMethodDecl>(Best->Function);
11666       FoundDecl = Best->FoundDecl;
11667       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11668       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11669         return ExprError();
11670       // If FoundDecl is different from Method (such as if one is a template
11671       // and the other a specialization), make sure DiagnoseUseOfDecl is
11672       // called on both.
11673       // FIXME: This would be more comprehensively addressed by modifying
11674       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11675       // being used.
11676       if (Method != FoundDecl.getDecl() &&
11677                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11678         return ExprError();
11679       break;
11680 
11681     case OR_No_Viable_Function:
11682       Diag(UnresExpr->getMemberLoc(),
11683            diag::err_ovl_no_viable_member_function_in_call)
11684         << DeclName << MemExprE->getSourceRange();
11685       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11686       // FIXME: Leaking incoming expressions!
11687       return ExprError();
11688 
11689     case OR_Ambiguous:
11690       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11691         << DeclName << MemExprE->getSourceRange();
11692       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11693       // FIXME: Leaking incoming expressions!
11694       return ExprError();
11695 
11696     case OR_Deleted:
11697       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11698         << Best->Function->isDeleted()
11699         << DeclName
11700         << getDeletedOrUnavailableSuffix(Best->Function)
11701         << MemExprE->getSourceRange();
11702       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11703       // FIXME: Leaking incoming expressions!
11704       return ExprError();
11705     }
11706 
11707     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11708 
11709     // If overload resolution picked a static member, build a
11710     // non-member call based on that function.
11711     if (Method->isStatic()) {
11712       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11713                                    RParenLoc);
11714     }
11715 
11716     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11717   }
11718 
11719   QualType ResultType = Method->getReturnType();
11720   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11721   ResultType = ResultType.getNonLValueExprType(Context);
11722 
11723   assert(Method && "Member call to something that isn't a method?");
11724   CXXMemberCallExpr *TheCall =
11725     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11726                                     ResultType, VK, RParenLoc);
11727 
11728   // (CUDA B.1): Check for invalid calls between targets.
11729   if (getLangOpts().CUDA) {
11730     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11731       if (CheckCUDATarget(Caller, Method)) {
11732         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11733             << IdentifyCUDATarget(Method) << Method->getIdentifier()
11734             << IdentifyCUDATarget(Caller);
11735         return ExprError();
11736       }
11737     }
11738   }
11739 
11740   // Check for a valid return type.
11741   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11742                           TheCall, Method))
11743     return ExprError();
11744 
11745   // Convert the object argument (for a non-static member function call).
11746   // We only need to do this if there was actually an overload; otherwise
11747   // it was done at lookup.
11748   if (!Method->isStatic()) {
11749     ExprResult ObjectArg =
11750       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11751                                           FoundDecl, Method);
11752     if (ObjectArg.isInvalid())
11753       return ExprError();
11754     MemExpr->setBase(ObjectArg.get());
11755   }
11756 
11757   // Convert the rest of the arguments
11758   const FunctionProtoType *Proto =
11759     Method->getType()->getAs<FunctionProtoType>();
11760   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11761                               RParenLoc))
11762     return ExprError();
11763 
11764   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11765 
11766   if (CheckFunctionCall(Method, TheCall, Proto))
11767     return ExprError();
11768 
11769   if ((isa<CXXConstructorDecl>(CurContext) ||
11770        isa<CXXDestructorDecl>(CurContext)) &&
11771       TheCall->getMethodDecl()->isPure()) {
11772     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11773 
11774     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11775       Diag(MemExpr->getLocStart(),
11776            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11777         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11778         << MD->getParent()->getDeclName();
11779 
11780       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11781     }
11782   }
11783   return MaybeBindToTemporary(TheCall);
11784 }
11785 
11786 /// BuildCallToObjectOfClassType - Build a call to an object of class
11787 /// type (C++ [over.call.object]), which can end up invoking an
11788 /// overloaded function call operator (@c operator()) or performing a
11789 /// user-defined conversion on the object argument.
11790 ExprResult
11791 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11792                                    SourceLocation LParenLoc,
11793                                    MultiExprArg Args,
11794                                    SourceLocation RParenLoc) {
11795   if (checkPlaceholderForOverload(*this, Obj))
11796     return ExprError();
11797   ExprResult Object = Obj;
11798 
11799   UnbridgedCastsSet UnbridgedCasts;
11800   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11801     return ExprError();
11802 
11803   assert(Object.get()->getType()->isRecordType() &&
11804          "Requires object type argument");
11805   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11806 
11807   // C++ [over.call.object]p1:
11808   //  If the primary-expression E in the function call syntax
11809   //  evaluates to a class object of type "cv T", then the set of
11810   //  candidate functions includes at least the function call
11811   //  operators of T. The function call operators of T are obtained by
11812   //  ordinary lookup of the name operator() in the context of
11813   //  (E).operator().
11814   OverloadCandidateSet CandidateSet(LParenLoc,
11815                                     OverloadCandidateSet::CSK_Operator);
11816   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11817 
11818   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11819                           diag::err_incomplete_object_call, Object.get()))
11820     return true;
11821 
11822   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11823   LookupQualifiedName(R, Record->getDecl());
11824   R.suppressDiagnostics();
11825 
11826   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11827        Oper != OperEnd; ++Oper) {
11828     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11829                        Object.get()->Classify(Context),
11830                        Args, CandidateSet,
11831                        /*SuppressUserConversions=*/ false);
11832   }
11833 
11834   // C++ [over.call.object]p2:
11835   //   In addition, for each (non-explicit in C++0x) conversion function
11836   //   declared in T of the form
11837   //
11838   //        operator conversion-type-id () cv-qualifier;
11839   //
11840   //   where cv-qualifier is the same cv-qualification as, or a
11841   //   greater cv-qualification than, cv, and where conversion-type-id
11842   //   denotes the type "pointer to function of (P1,...,Pn) returning
11843   //   R", or the type "reference to pointer to function of
11844   //   (P1,...,Pn) returning R", or the type "reference to function
11845   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11846   //   is also considered as a candidate function. Similarly,
11847   //   surrogate call functions are added to the set of candidate
11848   //   functions for each conversion function declared in an
11849   //   accessible base class provided the function is not hidden
11850   //   within T by another intervening declaration.
11851   const auto &Conversions =
11852       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11853   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
11854     NamedDecl *D = *I;
11855     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11856     if (isa<UsingShadowDecl>(D))
11857       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11858 
11859     // Skip over templated conversion functions; they aren't
11860     // surrogates.
11861     if (isa<FunctionTemplateDecl>(D))
11862       continue;
11863 
11864     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11865     if (!Conv->isExplicit()) {
11866       // Strip the reference type (if any) and then the pointer type (if
11867       // any) to get down to what might be a function type.
11868       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11869       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11870         ConvType = ConvPtrType->getPointeeType();
11871 
11872       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11873       {
11874         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11875                               Object.get(), Args, CandidateSet);
11876       }
11877     }
11878   }
11879 
11880   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11881 
11882   // Perform overload resolution.
11883   OverloadCandidateSet::iterator Best;
11884   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11885                              Best)) {
11886   case OR_Success:
11887     // Overload resolution succeeded; we'll build the appropriate call
11888     // below.
11889     break;
11890 
11891   case OR_No_Viable_Function:
11892     if (CandidateSet.empty())
11893       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11894         << Object.get()->getType() << /*call*/ 1
11895         << Object.get()->getSourceRange();
11896     else
11897       Diag(Object.get()->getLocStart(),
11898            diag::err_ovl_no_viable_object_call)
11899         << Object.get()->getType() << Object.get()->getSourceRange();
11900     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11901     break;
11902 
11903   case OR_Ambiguous:
11904     Diag(Object.get()->getLocStart(),
11905          diag::err_ovl_ambiguous_object_call)
11906       << Object.get()->getType() << Object.get()->getSourceRange();
11907     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11908     break;
11909 
11910   case OR_Deleted:
11911     Diag(Object.get()->getLocStart(),
11912          diag::err_ovl_deleted_object_call)
11913       << Best->Function->isDeleted()
11914       << Object.get()->getType()
11915       << getDeletedOrUnavailableSuffix(Best->Function)
11916       << Object.get()->getSourceRange();
11917     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11918     break;
11919   }
11920 
11921   if (Best == CandidateSet.end())
11922     return true;
11923 
11924   UnbridgedCasts.restore();
11925 
11926   if (Best->Function == nullptr) {
11927     // Since there is no function declaration, this is one of the
11928     // surrogate candidates. Dig out the conversion function.
11929     CXXConversionDecl *Conv
11930       = cast<CXXConversionDecl>(
11931                          Best->Conversions[0].UserDefined.ConversionFunction);
11932 
11933     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11934                               Best->FoundDecl);
11935     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11936       return ExprError();
11937     assert(Conv == Best->FoundDecl.getDecl() &&
11938              "Found Decl & conversion-to-functionptr should be same, right?!");
11939     // We selected one of the surrogate functions that converts the
11940     // object parameter to a function pointer. Perform the conversion
11941     // on the object argument, then let ActOnCallExpr finish the job.
11942 
11943     // Create an implicit member expr to refer to the conversion operator.
11944     // and then call it.
11945     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11946                                              Conv, HadMultipleCandidates);
11947     if (Call.isInvalid())
11948       return ExprError();
11949     // Record usage of conversion in an implicit cast.
11950     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11951                                     CK_UserDefinedConversion, Call.get(),
11952                                     nullptr, VK_RValue);
11953 
11954     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11955   }
11956 
11957   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11958 
11959   // We found an overloaded operator(). Build a CXXOperatorCallExpr
11960   // that calls this method, using Object for the implicit object
11961   // parameter and passing along the remaining arguments.
11962   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11963 
11964   // An error diagnostic has already been printed when parsing the declaration.
11965   if (Method->isInvalidDecl())
11966     return ExprError();
11967 
11968   const FunctionProtoType *Proto =
11969     Method->getType()->getAs<FunctionProtoType>();
11970 
11971   unsigned NumParams = Proto->getNumParams();
11972 
11973   DeclarationNameInfo OpLocInfo(
11974                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11975   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11976   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11977                                            HadMultipleCandidates,
11978                                            OpLocInfo.getLoc(),
11979                                            OpLocInfo.getInfo());
11980   if (NewFn.isInvalid())
11981     return true;
11982 
11983   // Build the full argument list for the method call (the implicit object
11984   // parameter is placed at the beginning of the list).
11985   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11986   MethodArgs[0] = Object.get();
11987   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11988 
11989   // Once we've built TheCall, all of the expressions are properly
11990   // owned.
11991   QualType ResultTy = Method->getReturnType();
11992   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11993   ResultTy = ResultTy.getNonLValueExprType(Context);
11994 
11995   CXXOperatorCallExpr *TheCall = new (Context)
11996       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
11997                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11998                           ResultTy, VK, RParenLoc, false);
11999   MethodArgs.reset();
12000 
12001   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12002     return true;
12003 
12004   // We may have default arguments. If so, we need to allocate more
12005   // slots in the call for them.
12006   if (Args.size() < NumParams)
12007     TheCall->setNumArgs(Context, NumParams + 1);
12008 
12009   bool IsError = false;
12010 
12011   // Initialize the implicit object parameter.
12012   ExprResult ObjRes =
12013     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12014                                         Best->FoundDecl, Method);
12015   if (ObjRes.isInvalid())
12016     IsError = true;
12017   else
12018     Object = ObjRes;
12019   TheCall->setArg(0, Object.get());
12020 
12021   // Check the argument types.
12022   for (unsigned i = 0; i != NumParams; i++) {
12023     Expr *Arg;
12024     if (i < Args.size()) {
12025       Arg = Args[i];
12026 
12027       // Pass the argument.
12028 
12029       ExprResult InputInit
12030         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12031                                                     Context,
12032                                                     Method->getParamDecl(i)),
12033                                     SourceLocation(), Arg);
12034 
12035       IsError |= InputInit.isInvalid();
12036       Arg = InputInit.getAs<Expr>();
12037     } else {
12038       ExprResult DefArg
12039         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12040       if (DefArg.isInvalid()) {
12041         IsError = true;
12042         break;
12043       }
12044 
12045       Arg = DefArg.getAs<Expr>();
12046     }
12047 
12048     TheCall->setArg(i + 1, Arg);
12049   }
12050 
12051   // If this is a variadic call, handle args passed through "...".
12052   if (Proto->isVariadic()) {
12053     // Promote the arguments (C99 6.5.2.2p7).
12054     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12055       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12056                                                         nullptr);
12057       IsError |= Arg.isInvalid();
12058       TheCall->setArg(i + 1, Arg.get());
12059     }
12060   }
12061 
12062   if (IsError) return true;
12063 
12064   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12065 
12066   if (CheckFunctionCall(Method, TheCall, Proto))
12067     return true;
12068 
12069   return MaybeBindToTemporary(TheCall);
12070 }
12071 
12072 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12073 ///  (if one exists), where @c Base is an expression of class type and
12074 /// @c Member is the name of the member we're trying to find.
12075 ExprResult
12076 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12077                                bool *NoArrowOperatorFound) {
12078   assert(Base->getType()->isRecordType() &&
12079          "left-hand side must have class type");
12080 
12081   if (checkPlaceholderForOverload(*this, Base))
12082     return ExprError();
12083 
12084   SourceLocation Loc = Base->getExprLoc();
12085 
12086   // C++ [over.ref]p1:
12087   //
12088   //   [...] An expression x->m is interpreted as (x.operator->())->m
12089   //   for a class object x of type T if T::operator->() exists and if
12090   //   the operator is selected as the best match function by the
12091   //   overload resolution mechanism (13.3).
12092   DeclarationName OpName =
12093     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12094   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12095   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12096 
12097   if (RequireCompleteType(Loc, Base->getType(),
12098                           diag::err_typecheck_incomplete_tag, Base))
12099     return ExprError();
12100 
12101   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12102   LookupQualifiedName(R, BaseRecord->getDecl());
12103   R.suppressDiagnostics();
12104 
12105   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12106        Oper != OperEnd; ++Oper) {
12107     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12108                        None, CandidateSet, /*SuppressUserConversions=*/false);
12109   }
12110 
12111   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12112 
12113   // Perform overload resolution.
12114   OverloadCandidateSet::iterator Best;
12115   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12116   case OR_Success:
12117     // Overload resolution succeeded; we'll build the call below.
12118     break;
12119 
12120   case OR_No_Viable_Function:
12121     if (CandidateSet.empty()) {
12122       QualType BaseType = Base->getType();
12123       if (NoArrowOperatorFound) {
12124         // Report this specific error to the caller instead of emitting a
12125         // diagnostic, as requested.
12126         *NoArrowOperatorFound = true;
12127         return ExprError();
12128       }
12129       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12130         << BaseType << Base->getSourceRange();
12131       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12132         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12133           << FixItHint::CreateReplacement(OpLoc, ".");
12134       }
12135     } else
12136       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12137         << "operator->" << Base->getSourceRange();
12138     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12139     return ExprError();
12140 
12141   case OR_Ambiguous:
12142     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12143       << "->" << Base->getType() << Base->getSourceRange();
12144     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12145     return ExprError();
12146 
12147   case OR_Deleted:
12148     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12149       << Best->Function->isDeleted()
12150       << "->"
12151       << getDeletedOrUnavailableSuffix(Best->Function)
12152       << Base->getSourceRange();
12153     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12154     return ExprError();
12155   }
12156 
12157   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12158 
12159   // Convert the object parameter.
12160   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12161   ExprResult BaseResult =
12162     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12163                                         Best->FoundDecl, Method);
12164   if (BaseResult.isInvalid())
12165     return ExprError();
12166   Base = BaseResult.get();
12167 
12168   // Build the operator call.
12169   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12170                                             HadMultipleCandidates, OpLoc);
12171   if (FnExpr.isInvalid())
12172     return ExprError();
12173 
12174   QualType ResultTy = Method->getReturnType();
12175   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12176   ResultTy = ResultTy.getNonLValueExprType(Context);
12177   CXXOperatorCallExpr *TheCall =
12178     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12179                                       Base, ResultTy, VK, OpLoc, false);
12180 
12181   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12182           return ExprError();
12183 
12184   return MaybeBindToTemporary(TheCall);
12185 }
12186 
12187 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12188 /// a literal operator described by the provided lookup results.
12189 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12190                                           DeclarationNameInfo &SuffixInfo,
12191                                           ArrayRef<Expr*> Args,
12192                                           SourceLocation LitEndLoc,
12193                                        TemplateArgumentListInfo *TemplateArgs) {
12194   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12195 
12196   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12197                                     OverloadCandidateSet::CSK_Normal);
12198   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12199                         /*SuppressUserConversions=*/true);
12200 
12201   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12202 
12203   // Perform overload resolution. This will usually be trivial, but might need
12204   // to perform substitutions for a literal operator template.
12205   OverloadCandidateSet::iterator Best;
12206   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12207   case OR_Success:
12208   case OR_Deleted:
12209     break;
12210 
12211   case OR_No_Viable_Function:
12212     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12213       << R.getLookupName();
12214     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12215     return ExprError();
12216 
12217   case OR_Ambiguous:
12218     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12219     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12220     return ExprError();
12221   }
12222 
12223   FunctionDecl *FD = Best->Function;
12224   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12225                                         HadMultipleCandidates,
12226                                         SuffixInfo.getLoc(),
12227                                         SuffixInfo.getInfo());
12228   if (Fn.isInvalid())
12229     return true;
12230 
12231   // Check the argument types. This should almost always be a no-op, except
12232   // that array-to-pointer decay is applied to string literals.
12233   Expr *ConvArgs[2];
12234   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12235     ExprResult InputInit = PerformCopyInitialization(
12236       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12237       SourceLocation(), Args[ArgIdx]);
12238     if (InputInit.isInvalid())
12239       return true;
12240     ConvArgs[ArgIdx] = InputInit.get();
12241   }
12242 
12243   QualType ResultTy = FD->getReturnType();
12244   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12245   ResultTy = ResultTy.getNonLValueExprType(Context);
12246 
12247   UserDefinedLiteral *UDL =
12248     new (Context) UserDefinedLiteral(Context, Fn.get(),
12249                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12250                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12251 
12252   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12253     return ExprError();
12254 
12255   if (CheckFunctionCall(FD, UDL, nullptr))
12256     return ExprError();
12257 
12258   return MaybeBindToTemporary(UDL);
12259 }
12260 
12261 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12262 /// given LookupResult is non-empty, it is assumed to describe a member which
12263 /// will be invoked. Otherwise, the function will be found via argument
12264 /// dependent lookup.
12265 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12266 /// otherwise CallExpr is set to ExprError() and some non-success value
12267 /// is returned.
12268 Sema::ForRangeStatus
12269 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12270                                 SourceLocation RangeLoc, VarDecl *Decl,
12271                                 BeginEndFunction BEF,
12272                                 const DeclarationNameInfo &NameInfo,
12273                                 LookupResult &MemberLookup,
12274                                 OverloadCandidateSet *CandidateSet,
12275                                 Expr *Range, ExprResult *CallExpr) {
12276   CandidateSet->clear();
12277   if (!MemberLookup.empty()) {
12278     ExprResult MemberRef =
12279         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12280                                  /*IsPtr=*/false, CXXScopeSpec(),
12281                                  /*TemplateKWLoc=*/SourceLocation(),
12282                                  /*FirstQualifierInScope=*/nullptr,
12283                                  MemberLookup,
12284                                  /*TemplateArgs=*/nullptr);
12285     if (MemberRef.isInvalid()) {
12286       *CallExpr = ExprError();
12287       Diag(Range->getLocStart(), diag::note_in_for_range)
12288           << RangeLoc << BEF << Range->getType();
12289       return FRS_DiagnosticIssued;
12290     }
12291     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12292     if (CallExpr->isInvalid()) {
12293       *CallExpr = ExprError();
12294       Diag(Range->getLocStart(), diag::note_in_for_range)
12295           << RangeLoc << BEF << Range->getType();
12296       return FRS_DiagnosticIssued;
12297     }
12298   } else {
12299     UnresolvedSet<0> FoundNames;
12300     UnresolvedLookupExpr *Fn =
12301       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12302                                    NestedNameSpecifierLoc(), NameInfo,
12303                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12304                                    FoundNames.begin(), FoundNames.end());
12305 
12306     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12307                                                     CandidateSet, CallExpr);
12308     if (CandidateSet->empty() || CandidateSetError) {
12309       *CallExpr = ExprError();
12310       return FRS_NoViableFunction;
12311     }
12312     OverloadCandidateSet::iterator Best;
12313     OverloadingResult OverloadResult =
12314         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12315 
12316     if (OverloadResult == OR_No_Viable_Function) {
12317       *CallExpr = ExprError();
12318       return FRS_NoViableFunction;
12319     }
12320     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12321                                          Loc, nullptr, CandidateSet, &Best,
12322                                          OverloadResult,
12323                                          /*AllowTypoCorrection=*/false);
12324     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12325       *CallExpr = ExprError();
12326       Diag(Range->getLocStart(), diag::note_in_for_range)
12327           << RangeLoc << BEF << Range->getType();
12328       return FRS_DiagnosticIssued;
12329     }
12330   }
12331   return FRS_Success;
12332 }
12333 
12334 
12335 /// FixOverloadedFunctionReference - E is an expression that refers to
12336 /// a C++ overloaded function (possibly with some parentheses and
12337 /// perhaps a '&' around it). We have resolved the overloaded function
12338 /// to the function declaration Fn, so patch up the expression E to
12339 /// refer (possibly indirectly) to Fn. Returns the new expr.
12340 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12341                                            FunctionDecl *Fn) {
12342   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12343     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12344                                                    Found, Fn);
12345     if (SubExpr == PE->getSubExpr())
12346       return PE;
12347 
12348     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12349   }
12350 
12351   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12352     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12353                                                    Found, Fn);
12354     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12355                                SubExpr->getType()) &&
12356            "Implicit cast type cannot be determined from overload");
12357     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12358     if (SubExpr == ICE->getSubExpr())
12359       return ICE;
12360 
12361     return ImplicitCastExpr::Create(Context, ICE->getType(),
12362                                     ICE->getCastKind(),
12363                                     SubExpr, nullptr,
12364                                     ICE->getValueKind());
12365   }
12366 
12367   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12368     assert(UnOp->getOpcode() == UO_AddrOf &&
12369            "Can only take the address of an overloaded function");
12370     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12371       if (Method->isStatic()) {
12372         // Do nothing: static member functions aren't any different
12373         // from non-member functions.
12374       } else {
12375         // Fix the subexpression, which really has to be an
12376         // UnresolvedLookupExpr holding an overloaded member function
12377         // or template.
12378         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12379                                                        Found, Fn);
12380         if (SubExpr == UnOp->getSubExpr())
12381           return UnOp;
12382 
12383         assert(isa<DeclRefExpr>(SubExpr)
12384                && "fixed to something other than a decl ref");
12385         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12386                && "fixed to a member ref with no nested name qualifier");
12387 
12388         // We have taken the address of a pointer to member
12389         // function. Perform the computation here so that we get the
12390         // appropriate pointer to member type.
12391         QualType ClassType
12392           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12393         QualType MemPtrType
12394           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12395 
12396         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12397                                            VK_RValue, OK_Ordinary,
12398                                            UnOp->getOperatorLoc());
12399       }
12400     }
12401     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12402                                                    Found, Fn);
12403     if (SubExpr == UnOp->getSubExpr())
12404       return UnOp;
12405 
12406     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12407                                      Context.getPointerType(SubExpr->getType()),
12408                                        VK_RValue, OK_Ordinary,
12409                                        UnOp->getOperatorLoc());
12410   }
12411 
12412   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12413     // FIXME: avoid copy.
12414     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12415     if (ULE->hasExplicitTemplateArgs()) {
12416       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12417       TemplateArgs = &TemplateArgsBuffer;
12418     }
12419 
12420     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12421                                            ULE->getQualifierLoc(),
12422                                            ULE->getTemplateKeywordLoc(),
12423                                            Fn,
12424                                            /*enclosing*/ false, // FIXME?
12425                                            ULE->getNameLoc(),
12426                                            Fn->getType(),
12427                                            VK_LValue,
12428                                            Found.getDecl(),
12429                                            TemplateArgs);
12430     MarkDeclRefReferenced(DRE);
12431     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12432     return DRE;
12433   }
12434 
12435   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12436     // FIXME: avoid copy.
12437     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12438     if (MemExpr->hasExplicitTemplateArgs()) {
12439       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12440       TemplateArgs = &TemplateArgsBuffer;
12441     }
12442 
12443     Expr *Base;
12444 
12445     // If we're filling in a static method where we used to have an
12446     // implicit member access, rewrite to a simple decl ref.
12447     if (MemExpr->isImplicitAccess()) {
12448       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12449         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12450                                                MemExpr->getQualifierLoc(),
12451                                                MemExpr->getTemplateKeywordLoc(),
12452                                                Fn,
12453                                                /*enclosing*/ false,
12454                                                MemExpr->getMemberLoc(),
12455                                                Fn->getType(),
12456                                                VK_LValue,
12457                                                Found.getDecl(),
12458                                                TemplateArgs);
12459         MarkDeclRefReferenced(DRE);
12460         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12461         return DRE;
12462       } else {
12463         SourceLocation Loc = MemExpr->getMemberLoc();
12464         if (MemExpr->getQualifier())
12465           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12466         CheckCXXThisCapture(Loc);
12467         Base = new (Context) CXXThisExpr(Loc,
12468                                          MemExpr->getBaseType(),
12469                                          /*isImplicit=*/true);
12470       }
12471     } else
12472       Base = MemExpr->getBase();
12473 
12474     ExprValueKind valueKind;
12475     QualType type;
12476     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12477       valueKind = VK_LValue;
12478       type = Fn->getType();
12479     } else {
12480       valueKind = VK_RValue;
12481       type = Context.BoundMemberTy;
12482     }
12483 
12484     MemberExpr *ME = MemberExpr::Create(Context, Base,
12485                                         MemExpr->isArrow(),
12486                                         MemExpr->getQualifierLoc(),
12487                                         MemExpr->getTemplateKeywordLoc(),
12488                                         Fn,
12489                                         Found,
12490                                         MemExpr->getMemberNameInfo(),
12491                                         TemplateArgs,
12492                                         type, valueKind, OK_Ordinary);
12493     ME->setHadMultipleCandidates(true);
12494     MarkMemberReferenced(ME);
12495     return ME;
12496   }
12497 
12498   llvm_unreachable("Invalid reference to overloaded function");
12499 }
12500 
12501 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12502                                                 DeclAccessPair Found,
12503                                                 FunctionDecl *Fn) {
12504   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12505 }
12506