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     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
135                      // it was omitted by the patch that added
136                      // ICK_Zero_Event_Conversion
137     ICR_C_Conversion
138   };
139   return Rank[(int)Kind];
140 }
141 
142 /// GetImplicitConversionName - Return the name of this kind of
143 /// implicit conversion.
144 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
145   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
146     "No conversion",
147     "Lvalue-to-rvalue",
148     "Array-to-pointer",
149     "Function-to-pointer",
150     "Noreturn adjustment",
151     "Qualification",
152     "Integral promotion",
153     "Floating point promotion",
154     "Complex promotion",
155     "Integral conversion",
156     "Floating conversion",
157     "Complex conversion",
158     "Floating-integral conversion",
159     "Pointer conversion",
160     "Pointer-to-member conversion",
161     "Boolean conversion",
162     "Compatible-types conversion",
163     "Derived-to-base conversion",
164     "Vector conversion",
165     "Vector splat",
166     "Complex-real conversion",
167     "Block Pointer conversion",
168     "Transparent Union Conversion",
169     "Writeback conversion",
170     "OpenCL Zero Event Conversion",
171     "C specific type conversion"
172   };
173   return Name[Kind];
174 }
175 
176 /// StandardConversionSequence - Set the standard conversion
177 /// sequence to the identity conversion.
178 void StandardConversionSequence::setAsIdentityConversion() {
179   First = ICK_Identity;
180   Second = ICK_Identity;
181   Third = ICK_Identity;
182   DeprecatedStringLiteralToCharPtr = false;
183   QualificationIncludesObjCLifetime = false;
184   ReferenceBinding = false;
185   DirectBinding = false;
186   IsLvalueReference = true;
187   BindsToFunctionLvalue = false;
188   BindsToRvalue = false;
189   BindsImplicitObjectArgumentWithoutRefQualifier = false;
190   ObjCLifetimeConversionBinding = false;
191   CopyConstructor = nullptr;
192 }
193 
194 /// getRank - Retrieve the rank of this standard conversion sequence
195 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
196 /// implicit conversions.
197 ImplicitConversionRank StandardConversionSequence::getRank() const {
198   ImplicitConversionRank Rank = ICR_Exact_Match;
199   if  (GetConversionRank(First) > Rank)
200     Rank = GetConversionRank(First);
201   if  (GetConversionRank(Second) > Rank)
202     Rank = GetConversionRank(Second);
203   if  (GetConversionRank(Third) > Rank)
204     Rank = GetConversionRank(Third);
205   return Rank;
206 }
207 
208 /// isPointerConversionToBool - Determines whether this conversion is
209 /// a conversion of a pointer or pointer-to-member to bool. This is
210 /// used as part of the ranking of standard conversion sequences
211 /// (C++ 13.3.3.2p4).
212 bool StandardConversionSequence::isPointerConversionToBool() const {
213   // Note that FromType has not necessarily been transformed by the
214   // array-to-pointer or function-to-pointer implicit conversions, so
215   // check for their presence as well as checking whether FromType is
216   // a pointer.
217   if (getToType(1)->isBooleanType() &&
218       (getFromType()->isPointerType() ||
219        getFromType()->isObjCObjectPointerType() ||
220        getFromType()->isBlockPointerType() ||
221        getFromType()->isNullPtrType() ||
222        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
223     return true;
224 
225   return false;
226 }
227 
228 /// isPointerConversionToVoidPointer - Determines whether this
229 /// conversion is a conversion of a pointer to a void pointer. This is
230 /// used as part of the ranking of standard conversion sequences (C++
231 /// 13.3.3.2p4).
232 bool
233 StandardConversionSequence::
234 isPointerConversionToVoidPointer(ASTContext& Context) const {
235   QualType FromType = getFromType();
236   QualType ToType = getToType(1);
237 
238   // Note that FromType has not necessarily been transformed by the
239   // array-to-pointer implicit conversion, so check for its presence
240   // and redo the conversion to get a pointer.
241   if (First == ICK_Array_To_Pointer)
242     FromType = Context.getArrayDecayedType(FromType);
243 
244   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
245     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
246       return ToPtrType->getPointeeType()->isVoidType();
247 
248   return false;
249 }
250 
251 /// Skip any implicit casts which could be either part of a narrowing conversion
252 /// or after one in an implicit conversion.
253 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
254   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
255     switch (ICE->getCastKind()) {
256     case CK_NoOp:
257     case CK_IntegralCast:
258     case CK_IntegralToBoolean:
259     case CK_IntegralToFloating:
260     case CK_FloatingToIntegral:
261     case CK_FloatingToBoolean:
262     case CK_FloatingCast:
263       Converted = ICE->getSubExpr();
264       continue;
265 
266     default:
267       return Converted;
268     }
269   }
270 
271   return Converted;
272 }
273 
274 /// Check if this standard conversion sequence represents a narrowing
275 /// conversion, according to C++11 [dcl.init.list]p7.
276 ///
277 /// \param Ctx  The AST context.
278 /// \param Converted  The result of applying this standard conversion sequence.
279 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
280 ///        value of the expression prior to the narrowing conversion.
281 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
282 ///        type of the expression prior to the narrowing conversion.
283 NarrowingKind
284 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
285                                              const Expr *Converted,
286                                              APValue &ConstantValue,
287                                              QualType &ConstantType) const {
288   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
289 
290   // C++11 [dcl.init.list]p7:
291   //   A narrowing conversion is an implicit conversion ...
292   QualType FromType = getToType(0);
293   QualType ToType = getToType(1);
294   switch (Second) {
295   // 'bool' is an integral type; dispatch to the right place to handle it.
296   case ICK_Boolean_Conversion:
297     if (FromType->isRealFloatingType())
298       goto FloatingIntegralConversion;
299     if (FromType->isIntegralOrUnscopedEnumerationType())
300       goto IntegralConversion;
301     // Boolean conversions can be from pointers and pointers to members
302     // [conv.bool], and those aren't considered narrowing conversions.
303     return NK_Not_Narrowing;
304 
305   // -- from a floating-point type to an integer type, or
306   //
307   // -- from an integer type or unscoped enumeration type to a floating-point
308   //    type, except where the source is a constant expression and the actual
309   //    value after conversion will fit into the target type and will produce
310   //    the original value when converted back to the original type, or
311   case ICK_Floating_Integral:
312   FloatingIntegralConversion:
313     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
314       return NK_Type_Narrowing;
315     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
316       llvm::APSInt IntConstantValue;
317       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
318       if (Initializer &&
319           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
320         // Convert the integer to the floating type.
321         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
322         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
323                                 llvm::APFloat::rmNearestTiesToEven);
324         // And back.
325         llvm::APSInt ConvertedValue = IntConstantValue;
326         bool ignored;
327         Result.convertToInteger(ConvertedValue,
328                                 llvm::APFloat::rmTowardZero, &ignored);
329         // If the resulting value is different, this was a narrowing conversion.
330         if (IntConstantValue != ConvertedValue) {
331           ConstantValue = APValue(IntConstantValue);
332           ConstantType = Initializer->getType();
333           return NK_Constant_Narrowing;
334         }
335       } else {
336         // Variables are always narrowings.
337         return NK_Variable_Narrowing;
338       }
339     }
340     return NK_Not_Narrowing;
341 
342   // -- from long double to double or float, or from double to float, except
343   //    where the source is a constant expression and the actual value after
344   //    conversion is within the range of values that can be represented (even
345   //    if it cannot be represented exactly), or
346   case ICK_Floating_Conversion:
347     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
348         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
349       // FromType is larger than ToType.
350       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
351       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
352         // Constant!
353         assert(ConstantValue.isFloat());
354         llvm::APFloat FloatVal = ConstantValue.getFloat();
355         // Convert the source value into the target type.
356         bool ignored;
357         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
358           Ctx.getFloatTypeSemantics(ToType),
359           llvm::APFloat::rmNearestTiesToEven, &ignored);
360         // If there was no overflow, the source value is within the range of
361         // values that can be represented.
362         if (ConvertStatus & llvm::APFloat::opOverflow) {
363           ConstantType = Initializer->getType();
364           return NK_Constant_Narrowing;
365         }
366       } else {
367         return NK_Variable_Narrowing;
368       }
369     }
370     return NK_Not_Narrowing;
371 
372   // -- from an integer type or unscoped enumeration type to an integer type
373   //    that cannot represent all the values of the original type, except where
374   //    the source is a constant expression and the actual value after
375   //    conversion will fit into the target type and will produce the original
376   //    value when converted back to the original type.
377   case ICK_Integral_Conversion:
378   IntegralConversion: {
379     assert(FromType->isIntegralOrUnscopedEnumerationType());
380     assert(ToType->isIntegralOrUnscopedEnumerationType());
381     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
382     const unsigned FromWidth = Ctx.getIntWidth(FromType);
383     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
384     const unsigned ToWidth = Ctx.getIntWidth(ToType);
385 
386     if (FromWidth > ToWidth ||
387         (FromWidth == ToWidth && FromSigned != ToSigned) ||
388         (FromSigned && !ToSigned)) {
389       // Not all values of FromType can be represented in ToType.
390       llvm::APSInt InitializerValue;
391       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
392       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
393         // Such conversions on variables are always narrowing.
394         return NK_Variable_Narrowing;
395       }
396       bool Narrowing = false;
397       if (FromWidth < ToWidth) {
398         // Negative -> unsigned is narrowing. Otherwise, more bits is never
399         // narrowing.
400         if (InitializerValue.isSigned() && InitializerValue.isNegative())
401           Narrowing = true;
402       } else {
403         // Add a bit to the InitializerValue so we don't have to worry about
404         // signed vs. unsigned comparisons.
405         InitializerValue = InitializerValue.extend(
406           InitializerValue.getBitWidth() + 1);
407         // Convert the initializer to and from the target width and signed-ness.
408         llvm::APSInt ConvertedValue = InitializerValue;
409         ConvertedValue = ConvertedValue.trunc(ToWidth);
410         ConvertedValue.setIsSigned(ToSigned);
411         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
412         ConvertedValue.setIsSigned(InitializerValue.isSigned());
413         // If the result is different, this was a narrowing conversion.
414         if (ConvertedValue != InitializerValue)
415           Narrowing = true;
416       }
417       if (Narrowing) {
418         ConstantType = Initializer->getType();
419         ConstantValue = APValue(InitializerValue);
420         return NK_Constant_Narrowing;
421       }
422     }
423     return NK_Not_Narrowing;
424   }
425 
426   default:
427     // Other kinds of conversions are not narrowings.
428     return NK_Not_Narrowing;
429   }
430 }
431 
432 /// dump - Print this standard conversion sequence to standard
433 /// error. Useful for debugging overloading issues.
434 void StandardConversionSequence::dump() const {
435   raw_ostream &OS = llvm::errs();
436   bool PrintedSomething = false;
437   if (First != ICK_Identity) {
438     OS << GetImplicitConversionName(First);
439     PrintedSomething = true;
440   }
441 
442   if (Second != ICK_Identity) {
443     if (PrintedSomething) {
444       OS << " -> ";
445     }
446     OS << GetImplicitConversionName(Second);
447 
448     if (CopyConstructor) {
449       OS << " (by copy constructor)";
450     } else if (DirectBinding) {
451       OS << " (direct reference binding)";
452     } else if (ReferenceBinding) {
453       OS << " (reference binding)";
454     }
455     PrintedSomething = true;
456   }
457 
458   if (Third != ICK_Identity) {
459     if (PrintedSomething) {
460       OS << " -> ";
461     }
462     OS << GetImplicitConversionName(Third);
463     PrintedSomething = true;
464   }
465 
466   if (!PrintedSomething) {
467     OS << "No conversions required";
468   }
469 }
470 
471 /// dump - Print this user-defined conversion sequence to standard
472 /// error. Useful for debugging overloading issues.
473 void UserDefinedConversionSequence::dump() const {
474   raw_ostream &OS = llvm::errs();
475   if (Before.First || Before.Second || Before.Third) {
476     Before.dump();
477     OS << " -> ";
478   }
479   if (ConversionFunction)
480     OS << '\'' << *ConversionFunction << '\'';
481   else
482     OS << "aggregate initialization";
483   if (After.First || After.Second || After.Third) {
484     OS << " -> ";
485     After.dump();
486   }
487 }
488 
489 /// dump - Print this implicit conversion sequence to standard
490 /// error. Useful for debugging overloading issues.
491 void ImplicitConversionSequence::dump() const {
492   raw_ostream &OS = llvm::errs();
493   if (isStdInitializerListElement())
494     OS << "Worst std::initializer_list element conversion: ";
495   switch (ConversionKind) {
496   case StandardConversion:
497     OS << "Standard conversion: ";
498     Standard.dump();
499     break;
500   case UserDefinedConversion:
501     OS << "User-defined conversion: ";
502     UserDefined.dump();
503     break;
504   case EllipsisConversion:
505     OS << "Ellipsis conversion";
506     break;
507   case AmbiguousConversion:
508     OS << "Ambiguous conversion";
509     break;
510   case BadConversion:
511     OS << "Bad conversion";
512     break;
513   }
514 
515   OS << "\n";
516 }
517 
518 void AmbiguousConversionSequence::construct() {
519   new (&conversions()) ConversionSet();
520 }
521 
522 void AmbiguousConversionSequence::destruct() {
523   conversions().~ConversionSet();
524 }
525 
526 void
527 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
528   FromTypePtr = O.FromTypePtr;
529   ToTypePtr = O.ToTypePtr;
530   new (&conversions()) ConversionSet(O.conversions());
531 }
532 
533 namespace {
534   // Structure used by DeductionFailureInfo to store
535   // template argument information.
536   struct DFIArguments {
537     TemplateArgument FirstArg;
538     TemplateArgument SecondArg;
539   };
540   // Structure used by DeductionFailureInfo to store
541   // template parameter and template argument information.
542   struct DFIParamWithArguments : DFIArguments {
543     TemplateParameter Param;
544   };
545 }
546 
547 /// \brief Convert from Sema's representation of template deduction information
548 /// to the form used in overload-candidate information.
549 DeductionFailureInfo
550 clang::MakeDeductionFailureInfo(ASTContext &Context,
551                                 Sema::TemplateDeductionResult TDK,
552                                 TemplateDeductionInfo &Info) {
553   DeductionFailureInfo Result;
554   Result.Result = static_cast<unsigned>(TDK);
555   Result.HasDiagnostic = false;
556   Result.Data = nullptr;
557   switch (TDK) {
558   case Sema::TDK_Success:
559   case Sema::TDK_Invalid:
560   case Sema::TDK_InstantiationDepth:
561   case Sema::TDK_TooManyArguments:
562   case Sema::TDK_TooFewArguments:
563     break;
564 
565   case Sema::TDK_Incomplete:
566   case Sema::TDK_InvalidExplicitArguments:
567     Result.Data = Info.Param.getOpaqueValue();
568     break;
569 
570   case Sema::TDK_NonDeducedMismatch: {
571     // FIXME: Should allocate from normal heap so that we can free this later.
572     DFIArguments *Saved = new (Context) DFIArguments;
573     Saved->FirstArg = Info.FirstArg;
574     Saved->SecondArg = Info.SecondArg;
575     Result.Data = Saved;
576     break;
577   }
578 
579   case Sema::TDK_Inconsistent:
580   case Sema::TDK_Underqualified: {
581     // FIXME: Should allocate from normal heap so that we can free this later.
582     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
583     Saved->Param = Info.Param;
584     Saved->FirstArg = Info.FirstArg;
585     Saved->SecondArg = Info.SecondArg;
586     Result.Data = Saved;
587     break;
588   }
589 
590   case Sema::TDK_SubstitutionFailure:
591     Result.Data = Info.take();
592     if (Info.hasSFINAEDiagnostic()) {
593       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
594           SourceLocation(), PartialDiagnostic::NullDiagnostic());
595       Info.takeSFINAEDiagnostic(*Diag);
596       Result.HasDiagnostic = true;
597     }
598     break;
599 
600   case Sema::TDK_FailedOverloadResolution:
601     Result.Data = Info.Expression;
602     break;
603 
604   case Sema::TDK_MiscellaneousDeductionFailure:
605     break;
606   }
607 
608   return Result;
609 }
610 
611 void DeductionFailureInfo::Destroy() {
612   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
613   case Sema::TDK_Success:
614   case Sema::TDK_Invalid:
615   case Sema::TDK_InstantiationDepth:
616   case Sema::TDK_Incomplete:
617   case Sema::TDK_TooManyArguments:
618   case Sema::TDK_TooFewArguments:
619   case Sema::TDK_InvalidExplicitArguments:
620   case Sema::TDK_FailedOverloadResolution:
621     break;
622 
623   case Sema::TDK_Inconsistent:
624   case Sema::TDK_Underqualified:
625   case Sema::TDK_NonDeducedMismatch:
626     // FIXME: Destroy the data?
627     Data = nullptr;
628     break;
629 
630   case Sema::TDK_SubstitutionFailure:
631     // FIXME: Destroy the template argument list?
632     Data = nullptr;
633     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
634       Diag->~PartialDiagnosticAt();
635       HasDiagnostic = false;
636     }
637     break;
638 
639   // Unhandled
640   case Sema::TDK_MiscellaneousDeductionFailure:
641     break;
642   }
643 }
644 
645 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
646   if (HasDiagnostic)
647     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
648   return nullptr;
649 }
650 
651 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
652   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
653   case Sema::TDK_Success:
654   case Sema::TDK_Invalid:
655   case Sema::TDK_InstantiationDepth:
656   case Sema::TDK_TooManyArguments:
657   case Sema::TDK_TooFewArguments:
658   case Sema::TDK_SubstitutionFailure:
659   case Sema::TDK_NonDeducedMismatch:
660   case Sema::TDK_FailedOverloadResolution:
661     return TemplateParameter();
662 
663   case Sema::TDK_Incomplete:
664   case Sema::TDK_InvalidExplicitArguments:
665     return TemplateParameter::getFromOpaqueValue(Data);
666 
667   case Sema::TDK_Inconsistent:
668   case Sema::TDK_Underqualified:
669     return static_cast<DFIParamWithArguments*>(Data)->Param;
670 
671   // Unhandled
672   case Sema::TDK_MiscellaneousDeductionFailure:
673     break;
674   }
675 
676   return TemplateParameter();
677 }
678 
679 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
680   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
681   case Sema::TDK_Success:
682   case Sema::TDK_Invalid:
683   case Sema::TDK_InstantiationDepth:
684   case Sema::TDK_TooManyArguments:
685   case Sema::TDK_TooFewArguments:
686   case Sema::TDK_Incomplete:
687   case Sema::TDK_InvalidExplicitArguments:
688   case Sema::TDK_Inconsistent:
689   case Sema::TDK_Underqualified:
690   case Sema::TDK_NonDeducedMismatch:
691   case Sema::TDK_FailedOverloadResolution:
692     return nullptr;
693 
694   case Sema::TDK_SubstitutionFailure:
695     return static_cast<TemplateArgumentList*>(Data);
696 
697   // Unhandled
698   case Sema::TDK_MiscellaneousDeductionFailure:
699     break;
700   }
701 
702   return nullptr;
703 }
704 
705 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
706   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
707   case Sema::TDK_Success:
708   case Sema::TDK_Invalid:
709   case Sema::TDK_InstantiationDepth:
710   case Sema::TDK_Incomplete:
711   case Sema::TDK_TooManyArguments:
712   case Sema::TDK_TooFewArguments:
713   case Sema::TDK_InvalidExplicitArguments:
714   case Sema::TDK_SubstitutionFailure:
715   case Sema::TDK_FailedOverloadResolution:
716     return nullptr;
717 
718   case Sema::TDK_Inconsistent:
719   case Sema::TDK_Underqualified:
720   case Sema::TDK_NonDeducedMismatch:
721     return &static_cast<DFIArguments*>(Data)->FirstArg;
722 
723   // Unhandled
724   case Sema::TDK_MiscellaneousDeductionFailure:
725     break;
726   }
727 
728   return nullptr;
729 }
730 
731 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
732   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733   case Sema::TDK_Success:
734   case Sema::TDK_Invalid:
735   case Sema::TDK_InstantiationDepth:
736   case Sema::TDK_Incomplete:
737   case Sema::TDK_TooManyArguments:
738   case Sema::TDK_TooFewArguments:
739   case Sema::TDK_InvalidExplicitArguments:
740   case Sema::TDK_SubstitutionFailure:
741   case Sema::TDK_FailedOverloadResolution:
742     return nullptr;
743 
744   case Sema::TDK_Inconsistent:
745   case Sema::TDK_Underqualified:
746   case Sema::TDK_NonDeducedMismatch:
747     return &static_cast<DFIArguments*>(Data)->SecondArg;
748 
749   // Unhandled
750   case Sema::TDK_MiscellaneousDeductionFailure:
751     break;
752   }
753 
754   return nullptr;
755 }
756 
757 Expr *DeductionFailureInfo::getExpr() {
758   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
759         Sema::TDK_FailedOverloadResolution)
760     return static_cast<Expr*>(Data);
761 
762   return nullptr;
763 }
764 
765 void OverloadCandidateSet::destroyCandidates() {
766   for (iterator i = begin(), e = end(); i != e; ++i) {
767     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
768       i->Conversions[ii].~ImplicitConversionSequence();
769     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
770       i->DeductionFailure.Destroy();
771   }
772 }
773 
774 void OverloadCandidateSet::clear() {
775   destroyCandidates();
776   NumInlineSequences = 0;
777   Candidates.clear();
778   Functions.clear();
779 }
780 
781 namespace {
782   class UnbridgedCastsSet {
783     struct Entry {
784       Expr **Addr;
785       Expr *Saved;
786     };
787     SmallVector<Entry, 2> Entries;
788 
789   public:
790     void save(Sema &S, Expr *&E) {
791       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
792       Entry entry = { &E, E };
793       Entries.push_back(entry);
794       E = S.stripARCUnbridgedCast(E);
795     }
796 
797     void restore() {
798       for (SmallVectorImpl<Entry>::iterator
799              i = Entries.begin(), e = Entries.end(); i != e; ++i)
800         *i->Addr = i->Saved;
801     }
802   };
803 }
804 
805 /// checkPlaceholderForOverload - Do any interesting placeholder-like
806 /// preprocessing on the given expression.
807 ///
808 /// \param unbridgedCasts a collection to which to add unbridged casts;
809 ///   without this, they will be immediately diagnosed as errors
810 ///
811 /// Return true on unrecoverable error.
812 static bool
813 checkPlaceholderForOverload(Sema &S, Expr *&E,
814                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
815   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
816     // We can't handle overloaded expressions here because overload
817     // resolution might reasonably tweak them.
818     if (placeholder->getKind() == BuiltinType::Overload) return false;
819 
820     // If the context potentially accepts unbridged ARC casts, strip
821     // the unbridged cast and add it to the collection for later restoration.
822     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
823         unbridgedCasts) {
824       unbridgedCasts->save(S, E);
825       return false;
826     }
827 
828     // Go ahead and check everything else.
829     ExprResult result = S.CheckPlaceholderExpr(E);
830     if (result.isInvalid())
831       return true;
832 
833     E = result.get();
834     return false;
835   }
836 
837   // Nothing to do.
838   return false;
839 }
840 
841 /// checkArgPlaceholdersForOverload - Check a set of call operands for
842 /// placeholders.
843 static bool checkArgPlaceholdersForOverload(Sema &S,
844                                             MultiExprArg Args,
845                                             UnbridgedCastsSet &unbridged) {
846   for (unsigned i = 0, e = Args.size(); i != e; ++i)
847     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
848       return true;
849 
850   return false;
851 }
852 
853 // IsOverload - Determine whether the given New declaration is an
854 // overload of the declarations in Old. This routine returns false if
855 // New and Old cannot be overloaded, e.g., if New has the same
856 // signature as some function in Old (C++ 1.3.10) or if the Old
857 // declarations aren't functions (or function templates) at all. When
858 // it does return false, MatchedDecl will point to the decl that New
859 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
860 // top of the underlying declaration.
861 //
862 // Example: Given the following input:
863 //
864 //   void f(int, float); // #1
865 //   void f(int, int); // #2
866 //   int f(int, int); // #3
867 //
868 // When we process #1, there is no previous declaration of "f",
869 // so IsOverload will not be used.
870 //
871 // When we process #2, Old contains only the FunctionDecl for #1.  By
872 // comparing the parameter types, we see that #1 and #2 are overloaded
873 // (since they have different signatures), so this routine returns
874 // false; MatchedDecl is unchanged.
875 //
876 // When we process #3, Old is an overload set containing #1 and #2. We
877 // compare the signatures of #3 to #1 (they're overloaded, so we do
878 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
879 // identical (return types of functions are not part of the
880 // signature), IsOverload returns false and MatchedDecl will be set to
881 // point to the FunctionDecl for #2.
882 //
883 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
884 // into a class by a using declaration.  The rules for whether to hide
885 // shadow declarations ignore some properties which otherwise figure
886 // into a function template's signature.
887 Sema::OverloadKind
888 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
889                     NamedDecl *&Match, bool NewIsUsingDecl) {
890   for (LookupResult::iterator I = Old.begin(), E = Old.end();
891          I != E; ++I) {
892     NamedDecl *OldD = *I;
893 
894     bool OldIsUsingDecl = false;
895     if (isa<UsingShadowDecl>(OldD)) {
896       OldIsUsingDecl = true;
897 
898       // We can always introduce two using declarations into the same
899       // context, even if they have identical signatures.
900       if (NewIsUsingDecl) continue;
901 
902       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
903     }
904 
905     // A using-declaration does not conflict with another declaration
906     // if one of them is hidden.
907     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
908       continue;
909 
910     // If either declaration was introduced by a using declaration,
911     // we'll need to use slightly different rules for matching.
912     // Essentially, these rules are the normal rules, except that
913     // function templates hide function templates with different
914     // return types or template parameter lists.
915     bool UseMemberUsingDeclRules =
916       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
917       !New->getFriendObjectKind();
918 
919     if (FunctionDecl *OldF = OldD->getAsFunction()) {
920       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
921         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
922           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
923           continue;
924         }
925 
926         if (!isa<FunctionTemplateDecl>(OldD) &&
927             !shouldLinkPossiblyHiddenDecl(*I, New))
928           continue;
929 
930         Match = *I;
931         return Ovl_Match;
932       }
933     } else if (isa<UsingDecl>(OldD)) {
934       // We can overload with these, which can show up when doing
935       // redeclaration checks for UsingDecls.
936       assert(Old.getLookupKind() == LookupUsingDeclName);
937     } else if (isa<TagDecl>(OldD)) {
938       // We can always overload with tags by hiding them.
939     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
940       // Optimistically assume that an unresolved using decl will
941       // overload; if it doesn't, we'll have to diagnose during
942       // template instantiation.
943     } else {
944       // (C++ 13p1):
945       //   Only function declarations can be overloaded; object and type
946       //   declarations cannot be overloaded.
947       Match = *I;
948       return Ovl_NonFunction;
949     }
950   }
951 
952   return Ovl_Overload;
953 }
954 
955 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
956                       bool UseUsingDeclRules) {
957   // C++ [basic.start.main]p2: This function shall not be overloaded.
958   if (New->isMain())
959     return false;
960 
961   // MSVCRT user defined entry points cannot be overloaded.
962   if (New->isMSVCRTEntryPoint())
963     return false;
964 
965   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
966   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
967 
968   // C++ [temp.fct]p2:
969   //   A function template can be overloaded with other function templates
970   //   and with normal (non-template) functions.
971   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
972     return true;
973 
974   // Is the function New an overload of the function Old?
975   QualType OldQType = Context.getCanonicalType(Old->getType());
976   QualType NewQType = Context.getCanonicalType(New->getType());
977 
978   // Compare the signatures (C++ 1.3.10) of the two functions to
979   // determine whether they are overloads. If we find any mismatch
980   // in the signature, they are overloads.
981 
982   // If either of these functions is a K&R-style function (no
983   // prototype), then we consider them to have matching signatures.
984   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
985       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
986     return false;
987 
988   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
989   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
990 
991   // The signature of a function includes the types of its
992   // parameters (C++ 1.3.10), which includes the presence or absence
993   // of the ellipsis; see C++ DR 357).
994   if (OldQType != NewQType &&
995       (OldType->getNumParams() != NewType->getNumParams() ||
996        OldType->isVariadic() != NewType->isVariadic() ||
997        !FunctionParamTypesAreEqual(OldType, NewType)))
998     return true;
999 
1000   // C++ [temp.over.link]p4:
1001   //   The signature of a function template consists of its function
1002   //   signature, its return type and its template parameter list. The names
1003   //   of the template parameters are significant only for establishing the
1004   //   relationship between the template parameters and the rest of the
1005   //   signature.
1006   //
1007   // We check the return type and template parameter lists for function
1008   // templates first; the remaining checks follow.
1009   //
1010   // However, we don't consider either of these when deciding whether
1011   // a member introduced by a shadow declaration is hidden.
1012   if (!UseUsingDeclRules && NewTemplate &&
1013       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1014                                        OldTemplate->getTemplateParameters(),
1015                                        false, TPL_TemplateMatch) ||
1016        OldType->getReturnType() != NewType->getReturnType()))
1017     return true;
1018 
1019   // If the function is a class member, its signature includes the
1020   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1021   //
1022   // As part of this, also check whether one of the member functions
1023   // is static, in which case they are not overloads (C++
1024   // 13.1p2). While not part of the definition of the signature,
1025   // this check is important to determine whether these functions
1026   // can be overloaded.
1027   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1028   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1029   if (OldMethod && NewMethod &&
1030       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1031     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1032       if (!UseUsingDeclRules &&
1033           (OldMethod->getRefQualifier() == RQ_None ||
1034            NewMethod->getRefQualifier() == RQ_None)) {
1035         // C++0x [over.load]p2:
1036         //   - Member function declarations with the same name and the same
1037         //     parameter-type-list as well as member function template
1038         //     declarations with the same name, the same parameter-type-list, and
1039         //     the same template parameter lists cannot be overloaded if any of
1040         //     them, but not all, have a ref-qualifier (8.3.5).
1041         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1042           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1043         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1044       }
1045       return true;
1046     }
1047 
1048     // We may not have applied the implicit const for a constexpr member
1049     // function yet (because we haven't yet resolved whether this is a static
1050     // or non-static member function). Add it now, on the assumption that this
1051     // is a redeclaration of OldMethod.
1052     unsigned OldQuals = OldMethod->getTypeQualifiers();
1053     unsigned NewQuals = NewMethod->getTypeQualifiers();
1054     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1055         !isa<CXXConstructorDecl>(NewMethod))
1056       NewQuals |= Qualifiers::Const;
1057 
1058     // We do not allow overloading based off of '__restrict'.
1059     OldQuals &= ~Qualifiers::Restrict;
1060     NewQuals &= ~Qualifiers::Restrict;
1061     if (OldQuals != NewQuals)
1062       return true;
1063   }
1064 
1065   // enable_if attributes are an order-sensitive part of the signature.
1066   for (specific_attr_iterator<EnableIfAttr>
1067          NewI = New->specific_attr_begin<EnableIfAttr>(),
1068          NewE = New->specific_attr_end<EnableIfAttr>(),
1069          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1070          OldE = Old->specific_attr_end<EnableIfAttr>();
1071        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1072     if (NewI == NewE || OldI == OldE)
1073       return true;
1074     llvm::FoldingSetNodeID NewID, OldID;
1075     NewI->getCond()->Profile(NewID, Context, true);
1076     OldI->getCond()->Profile(OldID, Context, true);
1077     if (NewID != OldID)
1078       return true;
1079   }
1080 
1081   if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1082     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1083                        OldTarget = IdentifyCUDATarget(Old);
1084     if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1085       return false;
1086 
1087     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1088 
1089     // Don't allow mixing of HD with other kinds. This guarantees that
1090     // we have only one viable function with this signature on any
1091     // side of CUDA compilation .
1092     if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1093       return false;
1094 
1095     // Allow overloading of functions with same signature, but
1096     // different CUDA target attributes.
1097     return NewTarget != OldTarget;
1098   }
1099 
1100   // The signatures match; this is not an overload.
1101   return false;
1102 }
1103 
1104 /// \brief Checks availability of the function depending on the current
1105 /// function context. Inside an unavailable function, unavailability is ignored.
1106 ///
1107 /// \returns true if \arg FD is unavailable and current context is inside
1108 /// an available function, false otherwise.
1109 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1110   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1111 }
1112 
1113 /// \brief Tries a user-defined conversion from From to ToType.
1114 ///
1115 /// Produces an implicit conversion sequence for when a standard conversion
1116 /// is not an option. See TryImplicitConversion for more information.
1117 static ImplicitConversionSequence
1118 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1119                          bool SuppressUserConversions,
1120                          bool AllowExplicit,
1121                          bool InOverloadResolution,
1122                          bool CStyle,
1123                          bool AllowObjCWritebackConversion,
1124                          bool AllowObjCConversionOnExplicit) {
1125   ImplicitConversionSequence ICS;
1126 
1127   if (SuppressUserConversions) {
1128     // We're not in the case above, so there is no conversion that
1129     // we can perform.
1130     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1131     return ICS;
1132   }
1133 
1134   // Attempt user-defined conversion.
1135   OverloadCandidateSet Conversions(From->getExprLoc(),
1136                                    OverloadCandidateSet::CSK_Normal);
1137   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1138                                   Conversions, AllowExplicit,
1139                                   AllowObjCConversionOnExplicit)) {
1140   case OR_Success:
1141   case OR_Deleted:
1142     ICS.setUserDefined();
1143     ICS.UserDefined.Before.setAsIdentityConversion();
1144     // C++ [over.ics.user]p4:
1145     //   A conversion of an expression of class type to the same class
1146     //   type is given Exact Match rank, and a conversion of an
1147     //   expression of class type to a base class of that type is
1148     //   given Conversion rank, in spite of the fact that a copy
1149     //   constructor (i.e., a user-defined conversion function) is
1150     //   called for those cases.
1151     if (CXXConstructorDecl *Constructor
1152           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1153       QualType FromCanon
1154         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1155       QualType ToCanon
1156         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1157       if (Constructor->isCopyConstructor() &&
1158           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1159         // Turn this into a "standard" conversion sequence, so that it
1160         // gets ranked with standard conversion sequences.
1161         ICS.setStandard();
1162         ICS.Standard.setAsIdentityConversion();
1163         ICS.Standard.setFromType(From->getType());
1164         ICS.Standard.setAllToTypes(ToType);
1165         ICS.Standard.CopyConstructor = Constructor;
1166         if (ToCanon != FromCanon)
1167           ICS.Standard.Second = ICK_Derived_To_Base;
1168       }
1169     }
1170     break;
1171 
1172   case OR_Ambiguous:
1173     ICS.setAmbiguous();
1174     ICS.Ambiguous.setFromType(From->getType());
1175     ICS.Ambiguous.setToType(ToType);
1176     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1177          Cand != Conversions.end(); ++Cand)
1178       if (Cand->Viable)
1179         ICS.Ambiguous.addConversion(Cand->Function);
1180     break;
1181 
1182     // Fall through.
1183   case OR_No_Viable_Function:
1184     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1185     break;
1186   }
1187 
1188   return ICS;
1189 }
1190 
1191 /// TryImplicitConversion - Attempt to perform an implicit conversion
1192 /// from the given expression (Expr) to the given type (ToType). This
1193 /// function returns an implicit conversion sequence that can be used
1194 /// to perform the initialization. Given
1195 ///
1196 ///   void f(float f);
1197 ///   void g(int i) { f(i); }
1198 ///
1199 /// this routine would produce an implicit conversion sequence to
1200 /// describe the initialization of f from i, which will be a standard
1201 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1202 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1203 //
1204 /// Note that this routine only determines how the conversion can be
1205 /// performed; it does not actually perform the conversion. As such,
1206 /// it will not produce any diagnostics if no conversion is available,
1207 /// but will instead return an implicit conversion sequence of kind
1208 /// "BadConversion".
1209 ///
1210 /// If @p SuppressUserConversions, then user-defined conversions are
1211 /// not permitted.
1212 /// If @p AllowExplicit, then explicit user-defined conversions are
1213 /// permitted.
1214 ///
1215 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1216 /// writeback conversion, which allows __autoreleasing id* parameters to
1217 /// be initialized with __strong id* or __weak id* arguments.
1218 static ImplicitConversionSequence
1219 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1220                       bool SuppressUserConversions,
1221                       bool AllowExplicit,
1222                       bool InOverloadResolution,
1223                       bool CStyle,
1224                       bool AllowObjCWritebackConversion,
1225                       bool AllowObjCConversionOnExplicit) {
1226   ImplicitConversionSequence ICS;
1227   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1228                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1229     ICS.setStandard();
1230     return ICS;
1231   }
1232 
1233   if (!S.getLangOpts().CPlusPlus) {
1234     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1235     return ICS;
1236   }
1237 
1238   // C++ [over.ics.user]p4:
1239   //   A conversion of an expression of class type to the same class
1240   //   type is given Exact Match rank, and a conversion of an
1241   //   expression of class type to a base class of that type is
1242   //   given Conversion rank, in spite of the fact that a copy/move
1243   //   constructor (i.e., a user-defined conversion function) is
1244   //   called for those cases.
1245   QualType FromType = From->getType();
1246   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1247       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1248        S.IsDerivedFrom(FromType, ToType))) {
1249     ICS.setStandard();
1250     ICS.Standard.setAsIdentityConversion();
1251     ICS.Standard.setFromType(FromType);
1252     ICS.Standard.setAllToTypes(ToType);
1253 
1254     // We don't actually check at this point whether there is a valid
1255     // copy/move constructor, since overloading just assumes that it
1256     // exists. When we actually perform initialization, we'll find the
1257     // appropriate constructor to copy the returned object, if needed.
1258     ICS.Standard.CopyConstructor = nullptr;
1259 
1260     // Determine whether this is considered a derived-to-base conversion.
1261     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1262       ICS.Standard.Second = ICK_Derived_To_Base;
1263 
1264     return ICS;
1265   }
1266 
1267   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1268                                   AllowExplicit, InOverloadResolution, CStyle,
1269                                   AllowObjCWritebackConversion,
1270                                   AllowObjCConversionOnExplicit);
1271 }
1272 
1273 ImplicitConversionSequence
1274 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1275                             bool SuppressUserConversions,
1276                             bool AllowExplicit,
1277                             bool InOverloadResolution,
1278                             bool CStyle,
1279                             bool AllowObjCWritebackConversion) {
1280   return ::TryImplicitConversion(*this, From, ToType,
1281                                  SuppressUserConversions, AllowExplicit,
1282                                  InOverloadResolution, CStyle,
1283                                  AllowObjCWritebackConversion,
1284                                  /*AllowObjCConversionOnExplicit=*/false);
1285 }
1286 
1287 /// PerformImplicitConversion - Perform an implicit conversion of the
1288 /// expression From to the type ToType. Returns the
1289 /// converted expression. Flavor is the kind of conversion we're
1290 /// performing, used in the error message. If @p AllowExplicit,
1291 /// explicit user-defined conversions are permitted.
1292 ExprResult
1293 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1294                                 AssignmentAction Action, bool AllowExplicit) {
1295   ImplicitConversionSequence ICS;
1296   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1297 }
1298 
1299 ExprResult
1300 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1301                                 AssignmentAction Action, bool AllowExplicit,
1302                                 ImplicitConversionSequence& ICS) {
1303   if (checkPlaceholderForOverload(*this, From))
1304     return ExprError();
1305 
1306   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1307   bool AllowObjCWritebackConversion
1308     = getLangOpts().ObjCAutoRefCount &&
1309       (Action == AA_Passing || Action == AA_Sending);
1310   if (getLangOpts().ObjC1)
1311     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1312                                       ToType, From->getType(), From);
1313   ICS = ::TryImplicitConversion(*this, From, ToType,
1314                                 /*SuppressUserConversions=*/false,
1315                                 AllowExplicit,
1316                                 /*InOverloadResolution=*/false,
1317                                 /*CStyle=*/false,
1318                                 AllowObjCWritebackConversion,
1319                                 /*AllowObjCConversionOnExplicit=*/false);
1320   return PerformImplicitConversion(From, ToType, ICS, Action);
1321 }
1322 
1323 /// \brief Determine whether the conversion from FromType to ToType is a valid
1324 /// conversion that strips "noreturn" off the nested function type.
1325 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1326                                 QualType &ResultTy) {
1327   if (Context.hasSameUnqualifiedType(FromType, ToType))
1328     return false;
1329 
1330   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1331   // where F adds one of the following at most once:
1332   //   - a pointer
1333   //   - a member pointer
1334   //   - a block pointer
1335   CanQualType CanTo = Context.getCanonicalType(ToType);
1336   CanQualType CanFrom = Context.getCanonicalType(FromType);
1337   Type::TypeClass TyClass = CanTo->getTypeClass();
1338   if (TyClass != CanFrom->getTypeClass()) return false;
1339   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1340     if (TyClass == Type::Pointer) {
1341       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1342       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1343     } else if (TyClass == Type::BlockPointer) {
1344       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1345       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1346     } else if (TyClass == Type::MemberPointer) {
1347       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1348       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1349     } else {
1350       return false;
1351     }
1352 
1353     TyClass = CanTo->getTypeClass();
1354     if (TyClass != CanFrom->getTypeClass()) return false;
1355     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1356       return false;
1357   }
1358 
1359   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1360   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1361   if (!EInfo.getNoReturn()) return false;
1362 
1363   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1364   assert(QualType(FromFn, 0).isCanonical());
1365   if (QualType(FromFn, 0) != CanTo) return false;
1366 
1367   ResultTy = ToType;
1368   return true;
1369 }
1370 
1371 /// \brief Determine whether the conversion from FromType to ToType is a valid
1372 /// vector conversion.
1373 ///
1374 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1375 /// conversion.
1376 static bool IsVectorConversion(Sema &S, QualType FromType,
1377                                QualType ToType, ImplicitConversionKind &ICK) {
1378   // We need at least one of these types to be a vector type to have a vector
1379   // conversion.
1380   if (!ToType->isVectorType() && !FromType->isVectorType())
1381     return false;
1382 
1383   // Identical types require no conversions.
1384   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1385     return false;
1386 
1387   // There are no conversions between extended vector types, only identity.
1388   if (ToType->isExtVectorType()) {
1389     // There are no conversions between extended vector types other than the
1390     // identity conversion.
1391     if (FromType->isExtVectorType())
1392       return false;
1393 
1394     // Vector splat from any arithmetic type to a vector.
1395     if (FromType->isArithmeticType()) {
1396       ICK = ICK_Vector_Splat;
1397       return true;
1398     }
1399   }
1400 
1401   // We can perform the conversion between vector types in the following cases:
1402   // 1)vector types are equivalent AltiVec and GCC vector types
1403   // 2)lax vector conversions are permitted and the vector types are of the
1404   //   same size
1405   if (ToType->isVectorType() && FromType->isVectorType()) {
1406     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1407         S.isLaxVectorConversion(FromType, ToType)) {
1408       ICK = ICK_Vector_Conversion;
1409       return true;
1410     }
1411   }
1412 
1413   return false;
1414 }
1415 
1416 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1417                                 bool InOverloadResolution,
1418                                 StandardConversionSequence &SCS,
1419                                 bool CStyle);
1420 
1421 /// IsStandardConversion - Determines whether there is a standard
1422 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1423 /// expression From to the type ToType. Standard conversion sequences
1424 /// only consider non-class types; for conversions that involve class
1425 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1426 /// contain the standard conversion sequence required to perform this
1427 /// conversion and this routine will return true. Otherwise, this
1428 /// routine will return false and the value of SCS is unspecified.
1429 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1430                                  bool InOverloadResolution,
1431                                  StandardConversionSequence &SCS,
1432                                  bool CStyle,
1433                                  bool AllowObjCWritebackConversion) {
1434   QualType FromType = From->getType();
1435 
1436   // Standard conversions (C++ [conv])
1437   SCS.setAsIdentityConversion();
1438   SCS.IncompatibleObjC = false;
1439   SCS.setFromType(FromType);
1440   SCS.CopyConstructor = nullptr;
1441 
1442   // There are no standard conversions for class types in C++, so
1443   // abort early. When overloading in C, however, we do permit them.
1444   if (S.getLangOpts().CPlusPlus &&
1445       (FromType->isRecordType() || ToType->isRecordType()))
1446     return false;
1447 
1448   // The first conversion can be an lvalue-to-rvalue conversion,
1449   // array-to-pointer conversion, or function-to-pointer conversion
1450   // (C++ 4p1).
1451 
1452   if (FromType == S.Context.OverloadTy) {
1453     DeclAccessPair AccessPair;
1454     if (FunctionDecl *Fn
1455           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1456                                                  AccessPair)) {
1457       // We were able to resolve the address of the overloaded function,
1458       // so we can convert to the type of that function.
1459       FromType = Fn->getType();
1460       SCS.setFromType(FromType);
1461 
1462       // we can sometimes resolve &foo<int> regardless of ToType, so check
1463       // if the type matches (identity) or we are converting to bool
1464       if (!S.Context.hasSameUnqualifiedType(
1465                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1466         QualType resultTy;
1467         // if the function type matches except for [[noreturn]], it's ok
1468         if (!S.IsNoReturnConversion(FromType,
1469               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1470           // otherwise, only a boolean conversion is standard
1471           if (!ToType->isBooleanType())
1472             return false;
1473       }
1474 
1475       // Check if the "from" expression is taking the address of an overloaded
1476       // function and recompute the FromType accordingly. Take advantage of the
1477       // fact that non-static member functions *must* have such an address-of
1478       // expression.
1479       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1480       if (Method && !Method->isStatic()) {
1481         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1482                "Non-unary operator on non-static member address");
1483         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1484                == UO_AddrOf &&
1485                "Non-address-of operator on non-static member address");
1486         const Type *ClassType
1487           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1488         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1489       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1490         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1491                UO_AddrOf &&
1492                "Non-address-of operator for overloaded function expression");
1493         FromType = S.Context.getPointerType(FromType);
1494       }
1495 
1496       // Check that we've computed the proper type after overload resolution.
1497       assert(S.Context.hasSameType(
1498         FromType,
1499         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1500     } else {
1501       return false;
1502     }
1503   }
1504   // Lvalue-to-rvalue conversion (C++11 4.1):
1505   //   A glvalue (3.10) of a non-function, non-array type T can
1506   //   be converted to a prvalue.
1507   bool argIsLValue = From->isGLValue();
1508   if (argIsLValue &&
1509       !FromType->isFunctionType() && !FromType->isArrayType() &&
1510       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1511     SCS.First = ICK_Lvalue_To_Rvalue;
1512 
1513     // C11 6.3.2.1p2:
1514     //   ... if the lvalue has atomic type, the value has the non-atomic version
1515     //   of the type of the lvalue ...
1516     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1517       FromType = Atomic->getValueType();
1518 
1519     // If T is a non-class type, the type of the rvalue is the
1520     // cv-unqualified version of T. Otherwise, the type of the rvalue
1521     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1522     // just strip the qualifiers because they don't matter.
1523     FromType = FromType.getUnqualifiedType();
1524   } else if (FromType->isArrayType()) {
1525     // Array-to-pointer conversion (C++ 4.2)
1526     SCS.First = ICK_Array_To_Pointer;
1527 
1528     // An lvalue or rvalue of type "array of N T" or "array of unknown
1529     // bound of T" can be converted to an rvalue of type "pointer to
1530     // T" (C++ 4.2p1).
1531     FromType = S.Context.getArrayDecayedType(FromType);
1532 
1533     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1534       // This conversion is deprecated in C++03 (D.4)
1535       SCS.DeprecatedStringLiteralToCharPtr = true;
1536 
1537       // For the purpose of ranking in overload resolution
1538       // (13.3.3.1.1), this conversion is considered an
1539       // array-to-pointer conversion followed by a qualification
1540       // conversion (4.4). (C++ 4.2p2)
1541       SCS.Second = ICK_Identity;
1542       SCS.Third = ICK_Qualification;
1543       SCS.QualificationIncludesObjCLifetime = false;
1544       SCS.setAllToTypes(FromType);
1545       return true;
1546     }
1547   } else if (FromType->isFunctionType() && argIsLValue) {
1548     // Function-to-pointer conversion (C++ 4.3).
1549     SCS.First = ICK_Function_To_Pointer;
1550 
1551     // An lvalue of function type T can be converted to an rvalue of
1552     // type "pointer to T." The result is a pointer to the
1553     // function. (C++ 4.3p1).
1554     FromType = S.Context.getPointerType(FromType);
1555   } else {
1556     // We don't require any conversions for the first step.
1557     SCS.First = ICK_Identity;
1558   }
1559   SCS.setToType(0, FromType);
1560 
1561   // The second conversion can be an integral promotion, floating
1562   // point promotion, integral conversion, floating point conversion,
1563   // floating-integral conversion, pointer conversion,
1564   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1565   // For overloading in C, this can also be a "compatible-type"
1566   // conversion.
1567   bool IncompatibleObjC = false;
1568   ImplicitConversionKind SecondICK = ICK_Identity;
1569   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1570     // The unqualified versions of the types are the same: there's no
1571     // conversion to do.
1572     SCS.Second = ICK_Identity;
1573   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1574     // Integral promotion (C++ 4.5).
1575     SCS.Second = ICK_Integral_Promotion;
1576     FromType = ToType.getUnqualifiedType();
1577   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1578     // Floating point promotion (C++ 4.6).
1579     SCS.Second = ICK_Floating_Promotion;
1580     FromType = ToType.getUnqualifiedType();
1581   } else if (S.IsComplexPromotion(FromType, ToType)) {
1582     // Complex promotion (Clang extension)
1583     SCS.Second = ICK_Complex_Promotion;
1584     FromType = ToType.getUnqualifiedType();
1585   } else if (ToType->isBooleanType() &&
1586              (FromType->isArithmeticType() ||
1587               FromType->isAnyPointerType() ||
1588               FromType->isBlockPointerType() ||
1589               FromType->isMemberPointerType() ||
1590               FromType->isNullPtrType())) {
1591     // Boolean conversions (C++ 4.12).
1592     SCS.Second = ICK_Boolean_Conversion;
1593     FromType = S.Context.BoolTy;
1594   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1595              ToType->isIntegralType(S.Context)) {
1596     // Integral conversions (C++ 4.7).
1597     SCS.Second = ICK_Integral_Conversion;
1598     FromType = ToType.getUnqualifiedType();
1599   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1600     // Complex conversions (C99 6.3.1.6)
1601     SCS.Second = ICK_Complex_Conversion;
1602     FromType = ToType.getUnqualifiedType();
1603   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1604              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1605     // Complex-real conversions (C99 6.3.1.7)
1606     SCS.Second = ICK_Complex_Real;
1607     FromType = ToType.getUnqualifiedType();
1608   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1609     // Floating point conversions (C++ 4.8).
1610     SCS.Second = ICK_Floating_Conversion;
1611     FromType = ToType.getUnqualifiedType();
1612   } else if ((FromType->isRealFloatingType() &&
1613               ToType->isIntegralType(S.Context)) ||
1614              (FromType->isIntegralOrUnscopedEnumerationType() &&
1615               ToType->isRealFloatingType())) {
1616     // Floating-integral conversions (C++ 4.9).
1617     SCS.Second = ICK_Floating_Integral;
1618     FromType = ToType.getUnqualifiedType();
1619   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1620     SCS.Second = ICK_Block_Pointer_Conversion;
1621   } else if (AllowObjCWritebackConversion &&
1622              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1623     SCS.Second = ICK_Writeback_Conversion;
1624   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1625                                    FromType, IncompatibleObjC)) {
1626     // Pointer conversions (C++ 4.10).
1627     SCS.Second = ICK_Pointer_Conversion;
1628     SCS.IncompatibleObjC = IncompatibleObjC;
1629     FromType = FromType.getUnqualifiedType();
1630   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1631                                          InOverloadResolution, FromType)) {
1632     // Pointer to member conversions (4.11).
1633     SCS.Second = ICK_Pointer_Member;
1634   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1635     SCS.Second = SecondICK;
1636     FromType = ToType.getUnqualifiedType();
1637   } else if (!S.getLangOpts().CPlusPlus &&
1638              S.Context.typesAreCompatible(ToType, FromType)) {
1639     // Compatible conversions (Clang extension for C function overloading)
1640     SCS.Second = ICK_Compatible_Conversion;
1641     FromType = ToType.getUnqualifiedType();
1642   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1643     // Treat a conversion that strips "noreturn" as an identity conversion.
1644     SCS.Second = ICK_NoReturn_Adjustment;
1645   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1646                                              InOverloadResolution,
1647                                              SCS, CStyle)) {
1648     SCS.Second = ICK_TransparentUnionConversion;
1649     FromType = ToType;
1650   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1651                                  CStyle)) {
1652     // tryAtomicConversion has updated the standard conversion sequence
1653     // appropriately.
1654     return true;
1655   } else if (ToType->isEventT() &&
1656              From->isIntegerConstantExpr(S.getASTContext()) &&
1657              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1658     SCS.Second = ICK_Zero_Event_Conversion;
1659     FromType = ToType;
1660   } else {
1661     // No second conversion required.
1662     SCS.Second = ICK_Identity;
1663   }
1664   SCS.setToType(1, FromType);
1665 
1666   QualType CanonFrom;
1667   QualType CanonTo;
1668   // The third conversion can be a qualification conversion (C++ 4p1).
1669   bool ObjCLifetimeConversion;
1670   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1671                                   ObjCLifetimeConversion)) {
1672     SCS.Third = ICK_Qualification;
1673     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1674     FromType = ToType;
1675     CanonFrom = S.Context.getCanonicalType(FromType);
1676     CanonTo = S.Context.getCanonicalType(ToType);
1677   } else {
1678     // No conversion required
1679     SCS.Third = ICK_Identity;
1680 
1681     // C++ [over.best.ics]p6:
1682     //   [...] Any difference in top-level cv-qualification is
1683     //   subsumed by the initialization itself and does not constitute
1684     //   a conversion. [...]
1685     CanonFrom = S.Context.getCanonicalType(FromType);
1686     CanonTo = S.Context.getCanonicalType(ToType);
1687     if (CanonFrom.getLocalUnqualifiedType()
1688                                        == CanonTo.getLocalUnqualifiedType() &&
1689         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1690       FromType = ToType;
1691       CanonFrom = CanonTo;
1692     }
1693   }
1694   SCS.setToType(2, FromType);
1695 
1696   if (CanonFrom == CanonTo)
1697     return true;
1698 
1699   // If we have not converted the argument type to the parameter type,
1700   // this is a bad conversion sequence, unless we're resolving an overload in C.
1701   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1702     return false;
1703 
1704   ExprResult ER = ExprResult{From};
1705   auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1706                                                  /*Diagnose=*/false,
1707                                                  /*DiagnoseCFAudited=*/false,
1708                                                  /*ConvertRHS=*/false);
1709   if (Conv != Sema::Compatible)
1710     return false;
1711 
1712   SCS.setAllToTypes(ToType);
1713   // We need to set all three because we want this conversion to rank terribly,
1714   // and we don't know what conversions it may overlap with.
1715   SCS.First = ICK_C_Only_Conversion;
1716   SCS.Second = ICK_C_Only_Conversion;
1717   SCS.Third = ICK_C_Only_Conversion;
1718   return true;
1719 }
1720 
1721 static bool
1722 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1723                                      QualType &ToType,
1724                                      bool InOverloadResolution,
1725                                      StandardConversionSequence &SCS,
1726                                      bool CStyle) {
1727 
1728   const RecordType *UT = ToType->getAsUnionType();
1729   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1730     return false;
1731   // The field to initialize within the transparent union.
1732   RecordDecl *UD = UT->getDecl();
1733   // It's compatible if the expression matches any of the fields.
1734   for (const auto *it : UD->fields()) {
1735     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1736                              CStyle, /*ObjCWritebackConversion=*/false)) {
1737       ToType = it->getType();
1738       return true;
1739     }
1740   }
1741   return false;
1742 }
1743 
1744 /// IsIntegralPromotion - Determines whether the conversion from the
1745 /// expression From (whose potentially-adjusted type is FromType) to
1746 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1747 /// sets PromotedType to the promoted type.
1748 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1749   const BuiltinType *To = ToType->getAs<BuiltinType>();
1750   // All integers are built-in.
1751   if (!To) {
1752     return false;
1753   }
1754 
1755   // An rvalue of type char, signed char, unsigned char, short int, or
1756   // unsigned short int can be converted to an rvalue of type int if
1757   // int can represent all the values of the source type; otherwise,
1758   // the source rvalue can be converted to an rvalue of type unsigned
1759   // int (C++ 4.5p1).
1760   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1761       !FromType->isEnumeralType()) {
1762     if (// We can promote any signed, promotable integer type to an int
1763         (FromType->isSignedIntegerType() ||
1764          // We can promote any unsigned integer type whose size is
1765          // less than int to an int.
1766          (!FromType->isSignedIntegerType() &&
1767           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1768       return To->getKind() == BuiltinType::Int;
1769     }
1770 
1771     return To->getKind() == BuiltinType::UInt;
1772   }
1773 
1774   // C++11 [conv.prom]p3:
1775   //   A prvalue of an unscoped enumeration type whose underlying type is not
1776   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1777   //   following types that can represent all the values of the enumeration
1778   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1779   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1780   //   long long int. If none of the types in that list can represent all the
1781   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1782   //   type can be converted to an rvalue a prvalue of the extended integer type
1783   //   with lowest integer conversion rank (4.13) greater than the rank of long
1784   //   long in which all the values of the enumeration can be represented. If
1785   //   there are two such extended types, the signed one is chosen.
1786   // C++11 [conv.prom]p4:
1787   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1788   //   can be converted to a prvalue of its underlying type. Moreover, if
1789   //   integral promotion can be applied to its underlying type, a prvalue of an
1790   //   unscoped enumeration type whose underlying type is fixed can also be
1791   //   converted to a prvalue of the promoted underlying type.
1792   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1793     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1794     // provided for a scoped enumeration.
1795     if (FromEnumType->getDecl()->isScoped())
1796       return false;
1797 
1798     // We can perform an integral promotion to the underlying type of the enum,
1799     // even if that's not the promoted type. Note that the check for promoting
1800     // the underlying type is based on the type alone, and does not consider
1801     // the bitfield-ness of the actual source expression.
1802     if (FromEnumType->getDecl()->isFixed()) {
1803       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1804       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1805              IsIntegralPromotion(nullptr, Underlying, ToType);
1806     }
1807 
1808     // We have already pre-calculated the promotion type, so this is trivial.
1809     if (ToType->isIntegerType() &&
1810         !RequireCompleteType(From->getLocStart(), FromType, 0))
1811       return Context.hasSameUnqualifiedType(
1812           ToType, FromEnumType->getDecl()->getPromotionType());
1813   }
1814 
1815   // C++0x [conv.prom]p2:
1816   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1817   //   to an rvalue a prvalue of the first of the following types that can
1818   //   represent all the values of its underlying type: int, unsigned int,
1819   //   long int, unsigned long int, long long int, or unsigned long long int.
1820   //   If none of the types in that list can represent all the values of its
1821   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1822   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1823   //   type.
1824   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1825       ToType->isIntegerType()) {
1826     // Determine whether the type we're converting from is signed or
1827     // unsigned.
1828     bool FromIsSigned = FromType->isSignedIntegerType();
1829     uint64_t FromSize = Context.getTypeSize(FromType);
1830 
1831     // The types we'll try to promote to, in the appropriate
1832     // order. Try each of these types.
1833     QualType PromoteTypes[6] = {
1834       Context.IntTy, Context.UnsignedIntTy,
1835       Context.LongTy, Context.UnsignedLongTy ,
1836       Context.LongLongTy, Context.UnsignedLongLongTy
1837     };
1838     for (int Idx = 0; Idx < 6; ++Idx) {
1839       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1840       if (FromSize < ToSize ||
1841           (FromSize == ToSize &&
1842            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1843         // We found the type that we can promote to. If this is the
1844         // type we wanted, we have a promotion. Otherwise, no
1845         // promotion.
1846         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1847       }
1848     }
1849   }
1850 
1851   // An rvalue for an integral bit-field (9.6) can be converted to an
1852   // rvalue of type int if int can represent all the values of the
1853   // bit-field; otherwise, it can be converted to unsigned int if
1854   // unsigned int can represent all the values of the bit-field. If
1855   // the bit-field is larger yet, no integral promotion applies to
1856   // it. If the bit-field has an enumerated type, it is treated as any
1857   // other value of that type for promotion purposes (C++ 4.5p3).
1858   // FIXME: We should delay checking of bit-fields until we actually perform the
1859   // conversion.
1860   if (From) {
1861     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1862       llvm::APSInt BitWidth;
1863       if (FromType->isIntegralType(Context) &&
1864           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1865         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1866         ToSize = Context.getTypeSize(ToType);
1867 
1868         // Are we promoting to an int from a bitfield that fits in an int?
1869         if (BitWidth < ToSize ||
1870             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1871           return To->getKind() == BuiltinType::Int;
1872         }
1873 
1874         // Are we promoting to an unsigned int from an unsigned bitfield
1875         // that fits into an unsigned int?
1876         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1877           return To->getKind() == BuiltinType::UInt;
1878         }
1879 
1880         return false;
1881       }
1882     }
1883   }
1884 
1885   // An rvalue of type bool can be converted to an rvalue of type int,
1886   // with false becoming zero and true becoming one (C++ 4.5p4).
1887   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1888     return true;
1889   }
1890 
1891   return false;
1892 }
1893 
1894 /// IsFloatingPointPromotion - Determines whether the conversion from
1895 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1896 /// returns true and sets PromotedType to the promoted type.
1897 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1898   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1899     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1900       /// An rvalue of type float can be converted to an rvalue of type
1901       /// double. (C++ 4.6p1).
1902       if (FromBuiltin->getKind() == BuiltinType::Float &&
1903           ToBuiltin->getKind() == BuiltinType::Double)
1904         return true;
1905 
1906       // C99 6.3.1.5p1:
1907       //   When a float is promoted to double or long double, or a
1908       //   double is promoted to long double [...].
1909       if (!getLangOpts().CPlusPlus &&
1910           (FromBuiltin->getKind() == BuiltinType::Float ||
1911            FromBuiltin->getKind() == BuiltinType::Double) &&
1912           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1913         return true;
1914 
1915       // Half can be promoted to float.
1916       if (!getLangOpts().NativeHalfType &&
1917            FromBuiltin->getKind() == BuiltinType::Half &&
1918           ToBuiltin->getKind() == BuiltinType::Float)
1919         return true;
1920     }
1921 
1922   return false;
1923 }
1924 
1925 /// \brief Determine if a conversion is a complex promotion.
1926 ///
1927 /// A complex promotion is defined as a complex -> complex conversion
1928 /// where the conversion between the underlying real types is a
1929 /// floating-point or integral promotion.
1930 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1931   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1932   if (!FromComplex)
1933     return false;
1934 
1935   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1936   if (!ToComplex)
1937     return false;
1938 
1939   return IsFloatingPointPromotion(FromComplex->getElementType(),
1940                                   ToComplex->getElementType()) ||
1941     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1942                         ToComplex->getElementType());
1943 }
1944 
1945 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1946 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1947 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1948 /// if non-empty, will be a pointer to ToType that may or may not have
1949 /// the right set of qualifiers on its pointee.
1950 ///
1951 static QualType
1952 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1953                                    QualType ToPointee, QualType ToType,
1954                                    ASTContext &Context,
1955                                    bool StripObjCLifetime = false) {
1956   assert((FromPtr->getTypeClass() == Type::Pointer ||
1957           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1958          "Invalid similarly-qualified pointer type");
1959 
1960   /// Conversions to 'id' subsume cv-qualifier conversions.
1961   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1962     return ToType.getUnqualifiedType();
1963 
1964   QualType CanonFromPointee
1965     = Context.getCanonicalType(FromPtr->getPointeeType());
1966   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1967   Qualifiers Quals = CanonFromPointee.getQualifiers();
1968 
1969   if (StripObjCLifetime)
1970     Quals.removeObjCLifetime();
1971 
1972   // Exact qualifier match -> return the pointer type we're converting to.
1973   if (CanonToPointee.getLocalQualifiers() == Quals) {
1974     // ToType is exactly what we need. Return it.
1975     if (!ToType.isNull())
1976       return ToType.getUnqualifiedType();
1977 
1978     // Build a pointer to ToPointee. It has the right qualifiers
1979     // already.
1980     if (isa<ObjCObjectPointerType>(ToType))
1981       return Context.getObjCObjectPointerType(ToPointee);
1982     return Context.getPointerType(ToPointee);
1983   }
1984 
1985   // Just build a canonical type that has the right qualifiers.
1986   QualType QualifiedCanonToPointee
1987     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1988 
1989   if (isa<ObjCObjectPointerType>(ToType))
1990     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1991   return Context.getPointerType(QualifiedCanonToPointee);
1992 }
1993 
1994 static bool isNullPointerConstantForConversion(Expr *Expr,
1995                                                bool InOverloadResolution,
1996                                                ASTContext &Context) {
1997   // Handle value-dependent integral null pointer constants correctly.
1998   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1999   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2000       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2001     return !InOverloadResolution;
2002 
2003   return Expr->isNullPointerConstant(Context,
2004                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2005                                         : Expr::NPC_ValueDependentIsNull);
2006 }
2007 
2008 /// IsPointerConversion - Determines whether the conversion of the
2009 /// expression From, which has the (possibly adjusted) type FromType,
2010 /// can be converted to the type ToType via a pointer conversion (C++
2011 /// 4.10). If so, returns true and places the converted type (that
2012 /// might differ from ToType in its cv-qualifiers at some level) into
2013 /// ConvertedType.
2014 ///
2015 /// This routine also supports conversions to and from block pointers
2016 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2017 /// pointers to interfaces. FIXME: Once we've determined the
2018 /// appropriate overloading rules for Objective-C, we may want to
2019 /// split the Objective-C checks into a different routine; however,
2020 /// GCC seems to consider all of these conversions to be pointer
2021 /// conversions, so for now they live here. IncompatibleObjC will be
2022 /// set if the conversion is an allowed Objective-C conversion that
2023 /// should result in a warning.
2024 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2025                                bool InOverloadResolution,
2026                                QualType& ConvertedType,
2027                                bool &IncompatibleObjC) {
2028   IncompatibleObjC = false;
2029   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2030                               IncompatibleObjC))
2031     return true;
2032 
2033   // Conversion from a null pointer constant to any Objective-C pointer type.
2034   if (ToType->isObjCObjectPointerType() &&
2035       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2036     ConvertedType = ToType;
2037     return true;
2038   }
2039 
2040   // Blocks: Block pointers can be converted to void*.
2041   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2042       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2043     ConvertedType = ToType;
2044     return true;
2045   }
2046   // Blocks: A null pointer constant can be converted to a block
2047   // pointer type.
2048   if (ToType->isBlockPointerType() &&
2049       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2050     ConvertedType = ToType;
2051     return true;
2052   }
2053 
2054   // If the left-hand-side is nullptr_t, the right side can be a null
2055   // pointer constant.
2056   if (ToType->isNullPtrType() &&
2057       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2058     ConvertedType = ToType;
2059     return true;
2060   }
2061 
2062   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2063   if (!ToTypePtr)
2064     return false;
2065 
2066   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2067   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2068     ConvertedType = ToType;
2069     return true;
2070   }
2071 
2072   // Beyond this point, both types need to be pointers
2073   // , including objective-c pointers.
2074   QualType ToPointeeType = ToTypePtr->getPointeeType();
2075   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2076       !getLangOpts().ObjCAutoRefCount) {
2077     ConvertedType = BuildSimilarlyQualifiedPointerType(
2078                                       FromType->getAs<ObjCObjectPointerType>(),
2079                                                        ToPointeeType,
2080                                                        ToType, Context);
2081     return true;
2082   }
2083   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2084   if (!FromTypePtr)
2085     return false;
2086 
2087   QualType FromPointeeType = FromTypePtr->getPointeeType();
2088 
2089   // If the unqualified pointee types are the same, this can't be a
2090   // pointer conversion, so don't do all of the work below.
2091   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2092     return false;
2093 
2094   // An rvalue of type "pointer to cv T," where T is an object type,
2095   // can be converted to an rvalue of type "pointer to cv void" (C++
2096   // 4.10p2).
2097   if (FromPointeeType->isIncompleteOrObjectType() &&
2098       ToPointeeType->isVoidType()) {
2099     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2100                                                        ToPointeeType,
2101                                                        ToType, Context,
2102                                                    /*StripObjCLifetime=*/true);
2103     return true;
2104   }
2105 
2106   // MSVC allows implicit function to void* type conversion.
2107   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2108       ToPointeeType->isVoidType()) {
2109     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2110                                                        ToPointeeType,
2111                                                        ToType, Context);
2112     return true;
2113   }
2114 
2115   // When we're overloading in C, we allow a special kind of pointer
2116   // conversion for compatible-but-not-identical pointee types.
2117   if (!getLangOpts().CPlusPlus &&
2118       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2119     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2120                                                        ToPointeeType,
2121                                                        ToType, Context);
2122     return true;
2123   }
2124 
2125   // C++ [conv.ptr]p3:
2126   //
2127   //   An rvalue of type "pointer to cv D," where D is a class type,
2128   //   can be converted to an rvalue of type "pointer to cv B," where
2129   //   B is a base class (clause 10) of D. If B is an inaccessible
2130   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2131   //   necessitates this conversion is ill-formed. The result of the
2132   //   conversion is a pointer to the base class sub-object of the
2133   //   derived class object. The null pointer value is converted to
2134   //   the null pointer value of the destination type.
2135   //
2136   // Note that we do not check for ambiguity or inaccessibility
2137   // here. That is handled by CheckPointerConversion.
2138   if (getLangOpts().CPlusPlus &&
2139       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2140       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2141       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2142       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2143     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2144                                                        ToPointeeType,
2145                                                        ToType, Context);
2146     return true;
2147   }
2148 
2149   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2150       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2151     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2152                                                        ToPointeeType,
2153                                                        ToType, Context);
2154     return true;
2155   }
2156 
2157   return false;
2158 }
2159 
2160 /// \brief Adopt the given qualifiers for the given type.
2161 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2162   Qualifiers TQs = T.getQualifiers();
2163 
2164   // Check whether qualifiers already match.
2165   if (TQs == Qs)
2166     return T;
2167 
2168   if (Qs.compatiblyIncludes(TQs))
2169     return Context.getQualifiedType(T, Qs);
2170 
2171   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2172 }
2173 
2174 /// isObjCPointerConversion - Determines whether this is an
2175 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2176 /// with the same arguments and return values.
2177 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2178                                    QualType& ConvertedType,
2179                                    bool &IncompatibleObjC) {
2180   if (!getLangOpts().ObjC1)
2181     return false;
2182 
2183   // The set of qualifiers on the type we're converting from.
2184   Qualifiers FromQualifiers = FromType.getQualifiers();
2185 
2186   // First, we handle all conversions on ObjC object pointer types.
2187   const ObjCObjectPointerType* ToObjCPtr =
2188     ToType->getAs<ObjCObjectPointerType>();
2189   const ObjCObjectPointerType *FromObjCPtr =
2190     FromType->getAs<ObjCObjectPointerType>();
2191 
2192   if (ToObjCPtr && FromObjCPtr) {
2193     // If the pointee types are the same (ignoring qualifications),
2194     // then this is not a pointer conversion.
2195     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2196                                        FromObjCPtr->getPointeeType()))
2197       return false;
2198 
2199     // Conversion between Objective-C pointers.
2200     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2201       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2202       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2203       if (getLangOpts().CPlusPlus && LHS && RHS &&
2204           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2205                                                 FromObjCPtr->getPointeeType()))
2206         return false;
2207       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2208                                                    ToObjCPtr->getPointeeType(),
2209                                                          ToType, Context);
2210       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2211       return true;
2212     }
2213 
2214     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2215       // Okay: this is some kind of implicit downcast of Objective-C
2216       // interfaces, which is permitted. However, we're going to
2217       // complain about it.
2218       IncompatibleObjC = true;
2219       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2220                                                    ToObjCPtr->getPointeeType(),
2221                                                          ToType, Context);
2222       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2223       return true;
2224     }
2225   }
2226   // Beyond this point, both types need to be C pointers or block pointers.
2227   QualType ToPointeeType;
2228   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2229     ToPointeeType = ToCPtr->getPointeeType();
2230   else if (const BlockPointerType *ToBlockPtr =
2231             ToType->getAs<BlockPointerType>()) {
2232     // Objective C++: We're able to convert from a pointer to any object
2233     // to a block pointer type.
2234     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2235       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2236       return true;
2237     }
2238     ToPointeeType = ToBlockPtr->getPointeeType();
2239   }
2240   else if (FromType->getAs<BlockPointerType>() &&
2241            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2242     // Objective C++: We're able to convert from a block pointer type to a
2243     // pointer to any object.
2244     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2245     return true;
2246   }
2247   else
2248     return false;
2249 
2250   QualType FromPointeeType;
2251   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2252     FromPointeeType = FromCPtr->getPointeeType();
2253   else if (const BlockPointerType *FromBlockPtr =
2254            FromType->getAs<BlockPointerType>())
2255     FromPointeeType = FromBlockPtr->getPointeeType();
2256   else
2257     return false;
2258 
2259   // If we have pointers to pointers, recursively check whether this
2260   // is an Objective-C conversion.
2261   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2262       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2263                               IncompatibleObjC)) {
2264     // We always complain about this conversion.
2265     IncompatibleObjC = true;
2266     ConvertedType = Context.getPointerType(ConvertedType);
2267     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2268     return true;
2269   }
2270   // Allow conversion of pointee being objective-c pointer to another one;
2271   // as in I* to id.
2272   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2273       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2274       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2275                               IncompatibleObjC)) {
2276 
2277     ConvertedType = Context.getPointerType(ConvertedType);
2278     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2279     return true;
2280   }
2281 
2282   // If we have pointers to functions or blocks, check whether the only
2283   // differences in the argument and result types are in Objective-C
2284   // pointer conversions. If so, we permit the conversion (but
2285   // complain about it).
2286   const FunctionProtoType *FromFunctionType
2287     = FromPointeeType->getAs<FunctionProtoType>();
2288   const FunctionProtoType *ToFunctionType
2289     = ToPointeeType->getAs<FunctionProtoType>();
2290   if (FromFunctionType && ToFunctionType) {
2291     // If the function types are exactly the same, this isn't an
2292     // Objective-C pointer conversion.
2293     if (Context.getCanonicalType(FromPointeeType)
2294           == Context.getCanonicalType(ToPointeeType))
2295       return false;
2296 
2297     // Perform the quick checks that will tell us whether these
2298     // function types are obviously different.
2299     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2300         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2301         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2302       return false;
2303 
2304     bool HasObjCConversion = false;
2305     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2306         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2307       // Okay, the types match exactly. Nothing to do.
2308     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2309                                        ToFunctionType->getReturnType(),
2310                                        ConvertedType, IncompatibleObjC)) {
2311       // Okay, we have an Objective-C pointer conversion.
2312       HasObjCConversion = true;
2313     } else {
2314       // Function types are too different. Abort.
2315       return false;
2316     }
2317 
2318     // Check argument types.
2319     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2320          ArgIdx != NumArgs; ++ArgIdx) {
2321       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2322       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2323       if (Context.getCanonicalType(FromArgType)
2324             == Context.getCanonicalType(ToArgType)) {
2325         // Okay, the types match exactly. Nothing to do.
2326       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2327                                          ConvertedType, IncompatibleObjC)) {
2328         // Okay, we have an Objective-C pointer conversion.
2329         HasObjCConversion = true;
2330       } else {
2331         // Argument types are too different. Abort.
2332         return false;
2333       }
2334     }
2335 
2336     if (HasObjCConversion) {
2337       // We had an Objective-C conversion. Allow this pointer
2338       // conversion, but complain about it.
2339       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2340       IncompatibleObjC = true;
2341       return true;
2342     }
2343   }
2344 
2345   return false;
2346 }
2347 
2348 /// \brief Determine whether this is an Objective-C writeback conversion,
2349 /// used for parameter passing when performing automatic reference counting.
2350 ///
2351 /// \param FromType The type we're converting form.
2352 ///
2353 /// \param ToType The type we're converting to.
2354 ///
2355 /// \param ConvertedType The type that will be produced after applying
2356 /// this conversion.
2357 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2358                                      QualType &ConvertedType) {
2359   if (!getLangOpts().ObjCAutoRefCount ||
2360       Context.hasSameUnqualifiedType(FromType, ToType))
2361     return false;
2362 
2363   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2364   QualType ToPointee;
2365   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2366     ToPointee = ToPointer->getPointeeType();
2367   else
2368     return false;
2369 
2370   Qualifiers ToQuals = ToPointee.getQualifiers();
2371   if (!ToPointee->isObjCLifetimeType() ||
2372       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2373       !ToQuals.withoutObjCLifetime().empty())
2374     return false;
2375 
2376   // Argument must be a pointer to __strong to __weak.
2377   QualType FromPointee;
2378   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2379     FromPointee = FromPointer->getPointeeType();
2380   else
2381     return false;
2382 
2383   Qualifiers FromQuals = FromPointee.getQualifiers();
2384   if (!FromPointee->isObjCLifetimeType() ||
2385       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2386        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2387     return false;
2388 
2389   // Make sure that we have compatible qualifiers.
2390   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2391   if (!ToQuals.compatiblyIncludes(FromQuals))
2392     return false;
2393 
2394   // Remove qualifiers from the pointee type we're converting from; they
2395   // aren't used in the compatibility check belong, and we'll be adding back
2396   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2397   FromPointee = FromPointee.getUnqualifiedType();
2398 
2399   // The unqualified form of the pointee types must be compatible.
2400   ToPointee = ToPointee.getUnqualifiedType();
2401   bool IncompatibleObjC;
2402   if (Context.typesAreCompatible(FromPointee, ToPointee))
2403     FromPointee = ToPointee;
2404   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2405                                     IncompatibleObjC))
2406     return false;
2407 
2408   /// \brief Construct the type we're converting to, which is a pointer to
2409   /// __autoreleasing pointee.
2410   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2411   ConvertedType = Context.getPointerType(FromPointee);
2412   return true;
2413 }
2414 
2415 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2416                                     QualType& ConvertedType) {
2417   QualType ToPointeeType;
2418   if (const BlockPointerType *ToBlockPtr =
2419         ToType->getAs<BlockPointerType>())
2420     ToPointeeType = ToBlockPtr->getPointeeType();
2421   else
2422     return false;
2423 
2424   QualType FromPointeeType;
2425   if (const BlockPointerType *FromBlockPtr =
2426       FromType->getAs<BlockPointerType>())
2427     FromPointeeType = FromBlockPtr->getPointeeType();
2428   else
2429     return false;
2430   // We have pointer to blocks, check whether the only
2431   // differences in the argument and result types are in Objective-C
2432   // pointer conversions. If so, we permit the conversion.
2433 
2434   const FunctionProtoType *FromFunctionType
2435     = FromPointeeType->getAs<FunctionProtoType>();
2436   const FunctionProtoType *ToFunctionType
2437     = ToPointeeType->getAs<FunctionProtoType>();
2438 
2439   if (!FromFunctionType || !ToFunctionType)
2440     return false;
2441 
2442   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2443     return true;
2444 
2445   // Perform the quick checks that will tell us whether these
2446   // function types are obviously different.
2447   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2448       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2449     return false;
2450 
2451   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2452   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2453   if (FromEInfo != ToEInfo)
2454     return false;
2455 
2456   bool IncompatibleObjC = false;
2457   if (Context.hasSameType(FromFunctionType->getReturnType(),
2458                           ToFunctionType->getReturnType())) {
2459     // Okay, the types match exactly. Nothing to do.
2460   } else {
2461     QualType RHS = FromFunctionType->getReturnType();
2462     QualType LHS = ToFunctionType->getReturnType();
2463     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2464         !RHS.hasQualifiers() && LHS.hasQualifiers())
2465        LHS = LHS.getUnqualifiedType();
2466 
2467      if (Context.hasSameType(RHS,LHS)) {
2468        // OK exact match.
2469      } else if (isObjCPointerConversion(RHS, LHS,
2470                                         ConvertedType, IncompatibleObjC)) {
2471      if (IncompatibleObjC)
2472        return false;
2473      // Okay, we have an Objective-C pointer conversion.
2474      }
2475      else
2476        return false;
2477    }
2478 
2479    // Check argument types.
2480    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2481         ArgIdx != NumArgs; ++ArgIdx) {
2482      IncompatibleObjC = false;
2483      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2484      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2485      if (Context.hasSameType(FromArgType, ToArgType)) {
2486        // Okay, the types match exactly. Nothing to do.
2487      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2488                                         ConvertedType, IncompatibleObjC)) {
2489        if (IncompatibleObjC)
2490          return false;
2491        // Okay, we have an Objective-C pointer conversion.
2492      } else
2493        // Argument types are too different. Abort.
2494        return false;
2495    }
2496    if (LangOpts.ObjCAutoRefCount &&
2497        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2498                                                     ToFunctionType))
2499      return false;
2500 
2501    ConvertedType = ToType;
2502    return true;
2503 }
2504 
2505 enum {
2506   ft_default,
2507   ft_different_class,
2508   ft_parameter_arity,
2509   ft_parameter_mismatch,
2510   ft_return_type,
2511   ft_qualifer_mismatch,
2512   ft_addr_enable_if
2513 };
2514 
2515 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2516 /// function types.  Catches different number of parameter, mismatch in
2517 /// parameter types, and different return types.
2518 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2519                                       QualType FromType, QualType ToType) {
2520   // If either type is not valid, include no extra info.
2521   if (FromType.isNull() || ToType.isNull()) {
2522     PDiag << ft_default;
2523     return;
2524   }
2525 
2526   // Get the function type from the pointers.
2527   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2528     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2529                             *ToMember = ToType->getAs<MemberPointerType>();
2530     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2531       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2532             << QualType(FromMember->getClass(), 0);
2533       return;
2534     }
2535     FromType = FromMember->getPointeeType();
2536     ToType = ToMember->getPointeeType();
2537   }
2538 
2539   if (FromType->isPointerType())
2540     FromType = FromType->getPointeeType();
2541   if (ToType->isPointerType())
2542     ToType = ToType->getPointeeType();
2543 
2544   // Remove references.
2545   FromType = FromType.getNonReferenceType();
2546   ToType = ToType.getNonReferenceType();
2547 
2548   // Don't print extra info for non-specialized template functions.
2549   if (FromType->isInstantiationDependentType() &&
2550       !FromType->getAs<TemplateSpecializationType>()) {
2551     PDiag << ft_default;
2552     return;
2553   }
2554 
2555   // No extra info for same types.
2556   if (Context.hasSameType(FromType, ToType)) {
2557     PDiag << ft_default;
2558     return;
2559   }
2560 
2561   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2562                           *ToFunction = ToType->getAs<FunctionProtoType>();
2563 
2564   // Both types need to be function types.
2565   if (!FromFunction || !ToFunction) {
2566     PDiag << ft_default;
2567     return;
2568   }
2569 
2570   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2571     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2572           << FromFunction->getNumParams();
2573     return;
2574   }
2575 
2576   // Handle different parameter types.
2577   unsigned ArgPos;
2578   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2579     PDiag << ft_parameter_mismatch << ArgPos + 1
2580           << ToFunction->getParamType(ArgPos)
2581           << FromFunction->getParamType(ArgPos);
2582     return;
2583   }
2584 
2585   // Handle different return type.
2586   if (!Context.hasSameType(FromFunction->getReturnType(),
2587                            ToFunction->getReturnType())) {
2588     PDiag << ft_return_type << ToFunction->getReturnType()
2589           << FromFunction->getReturnType();
2590     return;
2591   }
2592 
2593   unsigned FromQuals = FromFunction->getTypeQuals(),
2594            ToQuals = ToFunction->getTypeQuals();
2595   if (FromQuals != ToQuals) {
2596     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2597     return;
2598   }
2599 
2600   // Unable to find a difference, so add no extra info.
2601   PDiag << ft_default;
2602 }
2603 
2604 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2605 /// for equality of their argument types. Caller has already checked that
2606 /// they have same number of arguments.  If the parameters are different,
2607 /// ArgPos will have the parameter index of the first different parameter.
2608 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2609                                       const FunctionProtoType *NewType,
2610                                       unsigned *ArgPos) {
2611   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2612                                               N = NewType->param_type_begin(),
2613                                               E = OldType->param_type_end();
2614        O && (O != E); ++O, ++N) {
2615     if (!Context.hasSameType(O->getUnqualifiedType(),
2616                              N->getUnqualifiedType())) {
2617       if (ArgPos)
2618         *ArgPos = O - OldType->param_type_begin();
2619       return false;
2620     }
2621   }
2622   return true;
2623 }
2624 
2625 /// CheckPointerConversion - Check the pointer conversion from the
2626 /// expression From to the type ToType. This routine checks for
2627 /// ambiguous or inaccessible derived-to-base pointer
2628 /// conversions for which IsPointerConversion has already returned
2629 /// true. It returns true and produces a diagnostic if there was an
2630 /// error, or returns false otherwise.
2631 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2632                                   CastKind &Kind,
2633                                   CXXCastPath& BasePath,
2634                                   bool IgnoreBaseAccess) {
2635   QualType FromType = From->getType();
2636   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2637 
2638   Kind = CK_BitCast;
2639 
2640   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2641       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2642       Expr::NPCK_ZeroExpression) {
2643     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2644       DiagRuntimeBehavior(From->getExprLoc(), From,
2645                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2646                             << ToType << From->getSourceRange());
2647     else if (!isUnevaluatedContext())
2648       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2649         << ToType << From->getSourceRange();
2650   }
2651   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2652     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2653       QualType FromPointeeType = FromPtrType->getPointeeType(),
2654                ToPointeeType   = ToPtrType->getPointeeType();
2655 
2656       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2657           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2658         // We must have a derived-to-base conversion. Check an
2659         // ambiguous or inaccessible conversion.
2660         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2661                                          From->getExprLoc(),
2662                                          From->getSourceRange(), &BasePath,
2663                                          IgnoreBaseAccess))
2664           return true;
2665 
2666         // The conversion was successful.
2667         Kind = CK_DerivedToBase;
2668       }
2669     }
2670   } else if (const ObjCObjectPointerType *ToPtrType =
2671                ToType->getAs<ObjCObjectPointerType>()) {
2672     if (const ObjCObjectPointerType *FromPtrType =
2673           FromType->getAs<ObjCObjectPointerType>()) {
2674       // Objective-C++ conversions are always okay.
2675       // FIXME: We should have a different class of conversions for the
2676       // Objective-C++ implicit conversions.
2677       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2678         return false;
2679     } else if (FromType->isBlockPointerType()) {
2680       Kind = CK_BlockPointerToObjCPointerCast;
2681     } else {
2682       Kind = CK_CPointerToObjCPointerCast;
2683     }
2684   } else if (ToType->isBlockPointerType()) {
2685     if (!FromType->isBlockPointerType())
2686       Kind = CK_AnyPointerToBlockPointerCast;
2687   }
2688 
2689   // We shouldn't fall into this case unless it's valid for other
2690   // reasons.
2691   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2692     Kind = CK_NullToPointer;
2693 
2694   return false;
2695 }
2696 
2697 /// IsMemberPointerConversion - Determines whether the conversion of the
2698 /// expression From, which has the (possibly adjusted) type FromType, can be
2699 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2700 /// If so, returns true and places the converted type (that might differ from
2701 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2702 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2703                                      QualType ToType,
2704                                      bool InOverloadResolution,
2705                                      QualType &ConvertedType) {
2706   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2707   if (!ToTypePtr)
2708     return false;
2709 
2710   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2711   if (From->isNullPointerConstant(Context,
2712                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2713                                         : Expr::NPC_ValueDependentIsNull)) {
2714     ConvertedType = ToType;
2715     return true;
2716   }
2717 
2718   // Otherwise, both types have to be member pointers.
2719   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2720   if (!FromTypePtr)
2721     return false;
2722 
2723   // A pointer to member of B can be converted to a pointer to member of D,
2724   // where D is derived from B (C++ 4.11p2).
2725   QualType FromClass(FromTypePtr->getClass(), 0);
2726   QualType ToClass(ToTypePtr->getClass(), 0);
2727 
2728   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2729       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2730       IsDerivedFrom(ToClass, FromClass)) {
2731     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2732                                                  ToClass.getTypePtr());
2733     return true;
2734   }
2735 
2736   return false;
2737 }
2738 
2739 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2740 /// expression From to the type ToType. This routine checks for ambiguous or
2741 /// virtual or inaccessible base-to-derived member pointer conversions
2742 /// for which IsMemberPointerConversion has already returned true. It returns
2743 /// true and produces a diagnostic if there was an error, or returns false
2744 /// otherwise.
2745 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2746                                         CastKind &Kind,
2747                                         CXXCastPath &BasePath,
2748                                         bool IgnoreBaseAccess) {
2749   QualType FromType = From->getType();
2750   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2751   if (!FromPtrType) {
2752     // This must be a null pointer to member pointer conversion
2753     assert(From->isNullPointerConstant(Context,
2754                                        Expr::NPC_ValueDependentIsNull) &&
2755            "Expr must be null pointer constant!");
2756     Kind = CK_NullToMemberPointer;
2757     return false;
2758   }
2759 
2760   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2761   assert(ToPtrType && "No member pointer cast has a target type "
2762                       "that is not a member pointer.");
2763 
2764   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2765   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2766 
2767   // FIXME: What about dependent types?
2768   assert(FromClass->isRecordType() && "Pointer into non-class.");
2769   assert(ToClass->isRecordType() && "Pointer into non-class.");
2770 
2771   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2772                      /*DetectVirtual=*/true);
2773   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2774   assert(DerivationOkay &&
2775          "Should not have been called if derivation isn't OK.");
2776   (void)DerivationOkay;
2777 
2778   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2779                                   getUnqualifiedType())) {
2780     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2781     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2782       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2783     return true;
2784   }
2785 
2786   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2787     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2788       << FromClass << ToClass << QualType(VBase, 0)
2789       << From->getSourceRange();
2790     return true;
2791   }
2792 
2793   if (!IgnoreBaseAccess)
2794     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2795                          Paths.front(),
2796                          diag::err_downcast_from_inaccessible_base);
2797 
2798   // Must be a base to derived member conversion.
2799   BuildBasePathArray(Paths, BasePath);
2800   Kind = CK_BaseToDerivedMemberPointer;
2801   return false;
2802 }
2803 
2804 /// Determine whether the lifetime conversion between the two given
2805 /// qualifiers sets is nontrivial.
2806 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2807                                                Qualifiers ToQuals) {
2808   // Converting anything to const __unsafe_unretained is trivial.
2809   if (ToQuals.hasConst() &&
2810       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2811     return false;
2812 
2813   return true;
2814 }
2815 
2816 /// IsQualificationConversion - Determines whether the conversion from
2817 /// an rvalue of type FromType to ToType is a qualification conversion
2818 /// (C++ 4.4).
2819 ///
2820 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2821 /// when the qualification conversion involves a change in the Objective-C
2822 /// object lifetime.
2823 bool
2824 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2825                                 bool CStyle, bool &ObjCLifetimeConversion) {
2826   FromType = Context.getCanonicalType(FromType);
2827   ToType = Context.getCanonicalType(ToType);
2828   ObjCLifetimeConversion = false;
2829 
2830   // If FromType and ToType are the same type, this is not a
2831   // qualification conversion.
2832   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2833     return false;
2834 
2835   // (C++ 4.4p4):
2836   //   A conversion can add cv-qualifiers at levels other than the first
2837   //   in multi-level pointers, subject to the following rules: [...]
2838   bool PreviousToQualsIncludeConst = true;
2839   bool UnwrappedAnyPointer = false;
2840   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2841     // Within each iteration of the loop, we check the qualifiers to
2842     // determine if this still looks like a qualification
2843     // conversion. Then, if all is well, we unwrap one more level of
2844     // pointers or pointers-to-members and do it all again
2845     // until there are no more pointers or pointers-to-members left to
2846     // unwrap.
2847     UnwrappedAnyPointer = true;
2848 
2849     Qualifiers FromQuals = FromType.getQualifiers();
2850     Qualifiers ToQuals = ToType.getQualifiers();
2851 
2852     // Objective-C ARC:
2853     //   Check Objective-C lifetime conversions.
2854     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2855         UnwrappedAnyPointer) {
2856       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2857         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2858           ObjCLifetimeConversion = true;
2859         FromQuals.removeObjCLifetime();
2860         ToQuals.removeObjCLifetime();
2861       } else {
2862         // Qualification conversions cannot cast between different
2863         // Objective-C lifetime qualifiers.
2864         return false;
2865       }
2866     }
2867 
2868     // Allow addition/removal of GC attributes but not changing GC attributes.
2869     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2870         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2871       FromQuals.removeObjCGCAttr();
2872       ToQuals.removeObjCGCAttr();
2873     }
2874 
2875     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2876     //      2,j, and similarly for volatile.
2877     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2878       return false;
2879 
2880     //   -- if the cv 1,j and cv 2,j are different, then const is in
2881     //      every cv for 0 < k < j.
2882     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2883         && !PreviousToQualsIncludeConst)
2884       return false;
2885 
2886     // Keep track of whether all prior cv-qualifiers in the "to" type
2887     // include const.
2888     PreviousToQualsIncludeConst
2889       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2890   }
2891 
2892   // We are left with FromType and ToType being the pointee types
2893   // after unwrapping the original FromType and ToType the same number
2894   // of types. If we unwrapped any pointers, and if FromType and
2895   // ToType have the same unqualified type (since we checked
2896   // qualifiers above), then this is a qualification conversion.
2897   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2898 }
2899 
2900 /// \brief - Determine whether this is a conversion from a scalar type to an
2901 /// atomic type.
2902 ///
2903 /// If successful, updates \c SCS's second and third steps in the conversion
2904 /// sequence to finish the conversion.
2905 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2906                                 bool InOverloadResolution,
2907                                 StandardConversionSequence &SCS,
2908                                 bool CStyle) {
2909   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2910   if (!ToAtomic)
2911     return false;
2912 
2913   StandardConversionSequence InnerSCS;
2914   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2915                             InOverloadResolution, InnerSCS,
2916                             CStyle, /*AllowObjCWritebackConversion=*/false))
2917     return false;
2918 
2919   SCS.Second = InnerSCS.Second;
2920   SCS.setToType(1, InnerSCS.getToType(1));
2921   SCS.Third = InnerSCS.Third;
2922   SCS.QualificationIncludesObjCLifetime
2923     = InnerSCS.QualificationIncludesObjCLifetime;
2924   SCS.setToType(2, InnerSCS.getToType(2));
2925   return true;
2926 }
2927 
2928 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2929                                               CXXConstructorDecl *Constructor,
2930                                               QualType Type) {
2931   const FunctionProtoType *CtorType =
2932       Constructor->getType()->getAs<FunctionProtoType>();
2933   if (CtorType->getNumParams() > 0) {
2934     QualType FirstArg = CtorType->getParamType(0);
2935     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2936       return true;
2937   }
2938   return false;
2939 }
2940 
2941 static OverloadingResult
2942 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2943                                        CXXRecordDecl *To,
2944                                        UserDefinedConversionSequence &User,
2945                                        OverloadCandidateSet &CandidateSet,
2946                                        bool AllowExplicit) {
2947   DeclContext::lookup_result R = S.LookupConstructors(To);
2948   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2949        Con != ConEnd; ++Con) {
2950     NamedDecl *D = *Con;
2951     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2952 
2953     // Find the constructor (which may be a template).
2954     CXXConstructorDecl *Constructor = nullptr;
2955     FunctionTemplateDecl *ConstructorTmpl
2956       = dyn_cast<FunctionTemplateDecl>(D);
2957     if (ConstructorTmpl)
2958       Constructor
2959         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2960     else
2961       Constructor = cast<CXXConstructorDecl>(D);
2962 
2963     bool Usable = !Constructor->isInvalidDecl() &&
2964                   S.isInitListConstructor(Constructor) &&
2965                   (AllowExplicit || !Constructor->isExplicit());
2966     if (Usable) {
2967       // If the first argument is (a reference to) the target type,
2968       // suppress conversions.
2969       bool SuppressUserConversions =
2970           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2971       if (ConstructorTmpl)
2972         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2973                                        /*ExplicitArgs*/ nullptr,
2974                                        From, CandidateSet,
2975                                        SuppressUserConversions);
2976       else
2977         S.AddOverloadCandidate(Constructor, FoundDecl,
2978                                From, CandidateSet,
2979                                SuppressUserConversions);
2980     }
2981   }
2982 
2983   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2984 
2985   OverloadCandidateSet::iterator Best;
2986   switch (auto Result =
2987             CandidateSet.BestViableFunction(S, From->getLocStart(),
2988                                             Best, true)) {
2989   case OR_Deleted:
2990   case OR_Success: {
2991     // Record the standard conversion we used and the conversion function.
2992     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2993     QualType ThisType = Constructor->getThisType(S.Context);
2994     // Initializer lists don't have conversions as such.
2995     User.Before.setAsIdentityConversion();
2996     User.HadMultipleCandidates = HadMultipleCandidates;
2997     User.ConversionFunction = Constructor;
2998     User.FoundConversionFunction = Best->FoundDecl;
2999     User.After.setAsIdentityConversion();
3000     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3001     User.After.setAllToTypes(ToType);
3002     return Result;
3003   }
3004 
3005   case OR_No_Viable_Function:
3006     return OR_No_Viable_Function;
3007   case OR_Ambiguous:
3008     return OR_Ambiguous;
3009   }
3010 
3011   llvm_unreachable("Invalid OverloadResult!");
3012 }
3013 
3014 /// Determines whether there is a user-defined conversion sequence
3015 /// (C++ [over.ics.user]) that converts expression From to the type
3016 /// ToType. If such a conversion exists, User will contain the
3017 /// user-defined conversion sequence that performs such a conversion
3018 /// and this routine will return true. Otherwise, this routine returns
3019 /// false and User is unspecified.
3020 ///
3021 /// \param AllowExplicit  true if the conversion should consider C++0x
3022 /// "explicit" conversion functions as well as non-explicit conversion
3023 /// functions (C++0x [class.conv.fct]p2).
3024 ///
3025 /// \param AllowObjCConversionOnExplicit true if the conversion should
3026 /// allow an extra Objective-C pointer conversion on uses of explicit
3027 /// constructors. Requires \c AllowExplicit to also be set.
3028 static OverloadingResult
3029 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3030                         UserDefinedConversionSequence &User,
3031                         OverloadCandidateSet &CandidateSet,
3032                         bool AllowExplicit,
3033                         bool AllowObjCConversionOnExplicit) {
3034   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3035 
3036   // Whether we will only visit constructors.
3037   bool ConstructorsOnly = false;
3038 
3039   // If the type we are conversion to is a class type, enumerate its
3040   // constructors.
3041   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3042     // C++ [over.match.ctor]p1:
3043     //   When objects of class type are direct-initialized (8.5), or
3044     //   copy-initialized from an expression of the same or a
3045     //   derived class type (8.5), overload resolution selects the
3046     //   constructor. [...] For copy-initialization, the candidate
3047     //   functions are all the converting constructors (12.3.1) of
3048     //   that class. The argument list is the expression-list within
3049     //   the parentheses of the initializer.
3050     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3051         (From->getType()->getAs<RecordType>() &&
3052          S.IsDerivedFrom(From->getType(), ToType)))
3053       ConstructorsOnly = true;
3054 
3055     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3056     // RequireCompleteType may have returned true due to some invalid decl
3057     // during template instantiation, but ToType may be complete enough now
3058     // to try to recover.
3059     if (ToType->isIncompleteType()) {
3060       // We're not going to find any constructors.
3061     } else if (CXXRecordDecl *ToRecordDecl
3062                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3063 
3064       Expr **Args = &From;
3065       unsigned NumArgs = 1;
3066       bool ListInitializing = false;
3067       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3068         // But first, see if there is an init-list-constructor that will work.
3069         OverloadingResult Result = IsInitializerListConstructorConversion(
3070             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3071         if (Result != OR_No_Viable_Function)
3072           return Result;
3073         // Never mind.
3074         CandidateSet.clear();
3075 
3076         // If we're list-initializing, we pass the individual elements as
3077         // arguments, not the entire list.
3078         Args = InitList->getInits();
3079         NumArgs = InitList->getNumInits();
3080         ListInitializing = true;
3081       }
3082 
3083       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3084       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3085            Con != ConEnd; ++Con) {
3086         NamedDecl *D = *Con;
3087         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3088 
3089         // Find the constructor (which may be a template).
3090         CXXConstructorDecl *Constructor = nullptr;
3091         FunctionTemplateDecl *ConstructorTmpl
3092           = dyn_cast<FunctionTemplateDecl>(D);
3093         if (ConstructorTmpl)
3094           Constructor
3095             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3096         else
3097           Constructor = cast<CXXConstructorDecl>(D);
3098 
3099         bool Usable = !Constructor->isInvalidDecl();
3100         if (ListInitializing)
3101           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3102         else
3103           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3104         if (Usable) {
3105           bool SuppressUserConversions = !ConstructorsOnly;
3106           if (SuppressUserConversions && ListInitializing) {
3107             SuppressUserConversions = false;
3108             if (NumArgs == 1) {
3109               // If the first argument is (a reference to) the target type,
3110               // suppress conversions.
3111               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3112                                                 S.Context, Constructor, ToType);
3113             }
3114           }
3115           if (ConstructorTmpl)
3116             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3117                                            /*ExplicitArgs*/ nullptr,
3118                                            llvm::makeArrayRef(Args, NumArgs),
3119                                            CandidateSet, SuppressUserConversions);
3120           else
3121             // Allow one user-defined conversion when user specifies a
3122             // From->ToType conversion via an static cast (c-style, etc).
3123             S.AddOverloadCandidate(Constructor, FoundDecl,
3124                                    llvm::makeArrayRef(Args, NumArgs),
3125                                    CandidateSet, SuppressUserConversions);
3126         }
3127       }
3128     }
3129   }
3130 
3131   // Enumerate conversion functions, if we're allowed to.
3132   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3133   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3134     // No conversion functions from incomplete types.
3135   } else if (const RecordType *FromRecordType
3136                                    = From->getType()->getAs<RecordType>()) {
3137     if (CXXRecordDecl *FromRecordDecl
3138          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3139       // Add all of the conversion functions as candidates.
3140       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3141       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3142         DeclAccessPair FoundDecl = I.getPair();
3143         NamedDecl *D = FoundDecl.getDecl();
3144         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3145         if (isa<UsingShadowDecl>(D))
3146           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3147 
3148         CXXConversionDecl *Conv;
3149         FunctionTemplateDecl *ConvTemplate;
3150         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3151           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3152         else
3153           Conv = cast<CXXConversionDecl>(D);
3154 
3155         if (AllowExplicit || !Conv->isExplicit()) {
3156           if (ConvTemplate)
3157             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3158                                              ActingContext, From, ToType,
3159                                              CandidateSet,
3160                                              AllowObjCConversionOnExplicit);
3161           else
3162             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3163                                      From, ToType, CandidateSet,
3164                                      AllowObjCConversionOnExplicit);
3165         }
3166       }
3167     }
3168   }
3169 
3170   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3171 
3172   OverloadCandidateSet::iterator Best;
3173   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3174                                                         Best, true)) {
3175   case OR_Success:
3176   case OR_Deleted:
3177     // Record the standard conversion we used and the conversion function.
3178     if (CXXConstructorDecl *Constructor
3179           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3180       // C++ [over.ics.user]p1:
3181       //   If the user-defined conversion is specified by a
3182       //   constructor (12.3.1), the initial standard conversion
3183       //   sequence converts the source type to the type required by
3184       //   the argument of the constructor.
3185       //
3186       QualType ThisType = Constructor->getThisType(S.Context);
3187       if (isa<InitListExpr>(From)) {
3188         // Initializer lists don't have conversions as such.
3189         User.Before.setAsIdentityConversion();
3190       } else {
3191         if (Best->Conversions[0].isEllipsis())
3192           User.EllipsisConversion = true;
3193         else {
3194           User.Before = Best->Conversions[0].Standard;
3195           User.EllipsisConversion = false;
3196         }
3197       }
3198       User.HadMultipleCandidates = HadMultipleCandidates;
3199       User.ConversionFunction = Constructor;
3200       User.FoundConversionFunction = Best->FoundDecl;
3201       User.After.setAsIdentityConversion();
3202       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3203       User.After.setAllToTypes(ToType);
3204       return Result;
3205     }
3206     if (CXXConversionDecl *Conversion
3207                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3208       // C++ [over.ics.user]p1:
3209       //
3210       //   [...] If the user-defined conversion is specified by a
3211       //   conversion function (12.3.2), the initial standard
3212       //   conversion sequence converts the source type to the
3213       //   implicit object parameter of the conversion function.
3214       User.Before = Best->Conversions[0].Standard;
3215       User.HadMultipleCandidates = HadMultipleCandidates;
3216       User.ConversionFunction = Conversion;
3217       User.FoundConversionFunction = Best->FoundDecl;
3218       User.EllipsisConversion = false;
3219 
3220       // C++ [over.ics.user]p2:
3221       //   The second standard conversion sequence converts the
3222       //   result of the user-defined conversion to the target type
3223       //   for the sequence. Since an implicit conversion sequence
3224       //   is an initialization, the special rules for
3225       //   initialization by user-defined conversion apply when
3226       //   selecting the best user-defined conversion for a
3227       //   user-defined conversion sequence (see 13.3.3 and
3228       //   13.3.3.1).
3229       User.After = Best->FinalConversion;
3230       return Result;
3231     }
3232     llvm_unreachable("Not a constructor or conversion function?");
3233 
3234   case OR_No_Viable_Function:
3235     return OR_No_Viable_Function;
3236 
3237   case OR_Ambiguous:
3238     return OR_Ambiguous;
3239   }
3240 
3241   llvm_unreachable("Invalid OverloadResult!");
3242 }
3243 
3244 bool
3245 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3246   ImplicitConversionSequence ICS;
3247   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3248                                     OverloadCandidateSet::CSK_Normal);
3249   OverloadingResult OvResult =
3250     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3251                             CandidateSet, false, false);
3252   if (OvResult == OR_Ambiguous)
3253     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3254         << From->getType() << ToType << From->getSourceRange();
3255   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3256     if (!RequireCompleteType(From->getLocStart(), ToType,
3257                              diag::err_typecheck_nonviable_condition_incomplete,
3258                              From->getType(), From->getSourceRange()))
3259       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3260           << false << From->getType() << From->getSourceRange() << ToType;
3261   } else
3262     return false;
3263   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3264   return true;
3265 }
3266 
3267 /// \brief Compare the user-defined conversion functions or constructors
3268 /// of two user-defined conversion sequences to determine whether any ordering
3269 /// is possible.
3270 static ImplicitConversionSequence::CompareKind
3271 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3272                            FunctionDecl *Function2) {
3273   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3274     return ImplicitConversionSequence::Indistinguishable;
3275 
3276   // Objective-C++:
3277   //   If both conversion functions are implicitly-declared conversions from
3278   //   a lambda closure type to a function pointer and a block pointer,
3279   //   respectively, always prefer the conversion to a function pointer,
3280   //   because the function pointer is more lightweight and is more likely
3281   //   to keep code working.
3282   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3283   if (!Conv1)
3284     return ImplicitConversionSequence::Indistinguishable;
3285 
3286   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3287   if (!Conv2)
3288     return ImplicitConversionSequence::Indistinguishable;
3289 
3290   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3291     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3292     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3293     if (Block1 != Block2)
3294       return Block1 ? ImplicitConversionSequence::Worse
3295                     : ImplicitConversionSequence::Better;
3296   }
3297 
3298   return ImplicitConversionSequence::Indistinguishable;
3299 }
3300 
3301 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3302     const ImplicitConversionSequence &ICS) {
3303   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3304          (ICS.isUserDefined() &&
3305           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3306 }
3307 
3308 /// CompareImplicitConversionSequences - Compare two implicit
3309 /// conversion sequences to determine whether one is better than the
3310 /// other or if they are indistinguishable (C++ 13.3.3.2).
3311 static ImplicitConversionSequence::CompareKind
3312 CompareImplicitConversionSequences(Sema &S,
3313                                    const ImplicitConversionSequence& ICS1,
3314                                    const ImplicitConversionSequence& ICS2)
3315 {
3316   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3317   // conversion sequences (as defined in 13.3.3.1)
3318   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3319   //      conversion sequence than a user-defined conversion sequence or
3320   //      an ellipsis conversion sequence, and
3321   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3322   //      conversion sequence than an ellipsis conversion sequence
3323   //      (13.3.3.1.3).
3324   //
3325   // C++0x [over.best.ics]p10:
3326   //   For the purpose of ranking implicit conversion sequences as
3327   //   described in 13.3.3.2, the ambiguous conversion sequence is
3328   //   treated as a user-defined sequence that is indistinguishable
3329   //   from any other user-defined conversion sequence.
3330 
3331   // String literal to 'char *' conversion has been deprecated in C++03. It has
3332   // been removed from C++11. We still accept this conversion, if it happens at
3333   // the best viable function. Otherwise, this conversion is considered worse
3334   // than ellipsis conversion. Consider this as an extension; this is not in the
3335   // standard. For example:
3336   //
3337   // int &f(...);    // #1
3338   // void f(char*);  // #2
3339   // void g() { int &r = f("foo"); }
3340   //
3341   // In C++03, we pick #2 as the best viable function.
3342   // In C++11, we pick #1 as the best viable function, because ellipsis
3343   // conversion is better than string-literal to char* conversion (since there
3344   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3345   // convert arguments, #2 would be the best viable function in C++11.
3346   // If the best viable function has this conversion, a warning will be issued
3347   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3348 
3349   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3350       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3351       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3352     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3353                ? ImplicitConversionSequence::Worse
3354                : ImplicitConversionSequence::Better;
3355 
3356   if (ICS1.getKindRank() < ICS2.getKindRank())
3357     return ImplicitConversionSequence::Better;
3358   if (ICS2.getKindRank() < ICS1.getKindRank())
3359     return ImplicitConversionSequence::Worse;
3360 
3361   // The following checks require both conversion sequences to be of
3362   // the same kind.
3363   if (ICS1.getKind() != ICS2.getKind())
3364     return ImplicitConversionSequence::Indistinguishable;
3365 
3366   ImplicitConversionSequence::CompareKind Result =
3367       ImplicitConversionSequence::Indistinguishable;
3368 
3369   // Two implicit conversion sequences of the same form are
3370   // indistinguishable conversion sequences unless one of the
3371   // following rules apply: (C++ 13.3.3.2p3):
3372 
3373   // List-initialization sequence L1 is a better conversion sequence than
3374   // list-initialization sequence L2 if:
3375   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3376   //   if not that,
3377   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3378   //   and N1 is smaller than N2.,
3379   // even if one of the other rules in this paragraph would otherwise apply.
3380   if (!ICS1.isBad()) {
3381     if (ICS1.isStdInitializerListElement() &&
3382         !ICS2.isStdInitializerListElement())
3383       return ImplicitConversionSequence::Better;
3384     if (!ICS1.isStdInitializerListElement() &&
3385         ICS2.isStdInitializerListElement())
3386       return ImplicitConversionSequence::Worse;
3387   }
3388 
3389   if (ICS1.isStandard())
3390     // Standard conversion sequence S1 is a better conversion sequence than
3391     // standard conversion sequence S2 if [...]
3392     Result = CompareStandardConversionSequences(S,
3393                                                 ICS1.Standard, ICS2.Standard);
3394   else if (ICS1.isUserDefined()) {
3395     // User-defined conversion sequence U1 is a better conversion
3396     // sequence than another user-defined conversion sequence U2 if
3397     // they contain the same user-defined conversion function or
3398     // constructor and if the second standard conversion sequence of
3399     // U1 is better than the second standard conversion sequence of
3400     // U2 (C++ 13.3.3.2p3).
3401     if (ICS1.UserDefined.ConversionFunction ==
3402           ICS2.UserDefined.ConversionFunction)
3403       Result = CompareStandardConversionSequences(S,
3404                                                   ICS1.UserDefined.After,
3405                                                   ICS2.UserDefined.After);
3406     else
3407       Result = compareConversionFunctions(S,
3408                                           ICS1.UserDefined.ConversionFunction,
3409                                           ICS2.UserDefined.ConversionFunction);
3410   }
3411 
3412   return Result;
3413 }
3414 
3415 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3416   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3417     Qualifiers Quals;
3418     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3419     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3420   }
3421 
3422   return Context.hasSameUnqualifiedType(T1, T2);
3423 }
3424 
3425 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3426 // determine if one is a proper subset of the other.
3427 static ImplicitConversionSequence::CompareKind
3428 compareStandardConversionSubsets(ASTContext &Context,
3429                                  const StandardConversionSequence& SCS1,
3430                                  const StandardConversionSequence& SCS2) {
3431   ImplicitConversionSequence::CompareKind Result
3432     = ImplicitConversionSequence::Indistinguishable;
3433 
3434   // the identity conversion sequence is considered to be a subsequence of
3435   // any non-identity conversion sequence
3436   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3437     return ImplicitConversionSequence::Better;
3438   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3439     return ImplicitConversionSequence::Worse;
3440 
3441   if (SCS1.Second != SCS2.Second) {
3442     if (SCS1.Second == ICK_Identity)
3443       Result = ImplicitConversionSequence::Better;
3444     else if (SCS2.Second == ICK_Identity)
3445       Result = ImplicitConversionSequence::Worse;
3446     else
3447       return ImplicitConversionSequence::Indistinguishable;
3448   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3449     return ImplicitConversionSequence::Indistinguishable;
3450 
3451   if (SCS1.Third == SCS2.Third) {
3452     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3453                              : ImplicitConversionSequence::Indistinguishable;
3454   }
3455 
3456   if (SCS1.Third == ICK_Identity)
3457     return Result == ImplicitConversionSequence::Worse
3458              ? ImplicitConversionSequence::Indistinguishable
3459              : ImplicitConversionSequence::Better;
3460 
3461   if (SCS2.Third == ICK_Identity)
3462     return Result == ImplicitConversionSequence::Better
3463              ? ImplicitConversionSequence::Indistinguishable
3464              : ImplicitConversionSequence::Worse;
3465 
3466   return ImplicitConversionSequence::Indistinguishable;
3467 }
3468 
3469 /// \brief Determine whether one of the given reference bindings is better
3470 /// than the other based on what kind of bindings they are.
3471 static bool
3472 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3473                              const StandardConversionSequence &SCS2) {
3474   // C++0x [over.ics.rank]p3b4:
3475   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3476   //      implicit object parameter of a non-static member function declared
3477   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3478   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3479   //      lvalue reference to a function lvalue and S2 binds an rvalue
3480   //      reference*.
3481   //
3482   // FIXME: Rvalue references. We're going rogue with the above edits,
3483   // because the semantics in the current C++0x working paper (N3225 at the
3484   // time of this writing) break the standard definition of std::forward
3485   // and std::reference_wrapper when dealing with references to functions.
3486   // Proposed wording changes submitted to CWG for consideration.
3487   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3488       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3489     return false;
3490 
3491   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3492           SCS2.IsLvalueReference) ||
3493          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3494           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3495 }
3496 
3497 /// CompareStandardConversionSequences - Compare two standard
3498 /// conversion sequences to determine whether one is better than the
3499 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3500 static ImplicitConversionSequence::CompareKind
3501 CompareStandardConversionSequences(Sema &S,
3502                                    const StandardConversionSequence& SCS1,
3503                                    const StandardConversionSequence& SCS2)
3504 {
3505   // Standard conversion sequence S1 is a better conversion sequence
3506   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3507 
3508   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3509   //     sequences in the canonical form defined by 13.3.3.1.1,
3510   //     excluding any Lvalue Transformation; the identity conversion
3511   //     sequence is considered to be a subsequence of any
3512   //     non-identity conversion sequence) or, if not that,
3513   if (ImplicitConversionSequence::CompareKind CK
3514         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3515     return CK;
3516 
3517   //  -- the rank of S1 is better than the rank of S2 (by the rules
3518   //     defined below), or, if not that,
3519   ImplicitConversionRank Rank1 = SCS1.getRank();
3520   ImplicitConversionRank Rank2 = SCS2.getRank();
3521   if (Rank1 < Rank2)
3522     return ImplicitConversionSequence::Better;
3523   else if (Rank2 < Rank1)
3524     return ImplicitConversionSequence::Worse;
3525 
3526   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3527   // are indistinguishable unless one of the following rules
3528   // applies:
3529 
3530   //   A conversion that is not a conversion of a pointer, or
3531   //   pointer to member, to bool is better than another conversion
3532   //   that is such a conversion.
3533   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3534     return SCS2.isPointerConversionToBool()
3535              ? ImplicitConversionSequence::Better
3536              : ImplicitConversionSequence::Worse;
3537 
3538   // C++ [over.ics.rank]p4b2:
3539   //
3540   //   If class B is derived directly or indirectly from class A,
3541   //   conversion of B* to A* is better than conversion of B* to
3542   //   void*, and conversion of A* to void* is better than conversion
3543   //   of B* to void*.
3544   bool SCS1ConvertsToVoid
3545     = SCS1.isPointerConversionToVoidPointer(S.Context);
3546   bool SCS2ConvertsToVoid
3547     = SCS2.isPointerConversionToVoidPointer(S.Context);
3548   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3549     // Exactly one of the conversion sequences is a conversion to
3550     // a void pointer; it's the worse conversion.
3551     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3552                               : ImplicitConversionSequence::Worse;
3553   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3554     // Neither conversion sequence converts to a void pointer; compare
3555     // their derived-to-base conversions.
3556     if (ImplicitConversionSequence::CompareKind DerivedCK
3557           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3558       return DerivedCK;
3559   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3560              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3561     // Both conversion sequences are conversions to void
3562     // pointers. Compare the source types to determine if there's an
3563     // inheritance relationship in their sources.
3564     QualType FromType1 = SCS1.getFromType();
3565     QualType FromType2 = SCS2.getFromType();
3566 
3567     // Adjust the types we're converting from via the array-to-pointer
3568     // conversion, if we need to.
3569     if (SCS1.First == ICK_Array_To_Pointer)
3570       FromType1 = S.Context.getArrayDecayedType(FromType1);
3571     if (SCS2.First == ICK_Array_To_Pointer)
3572       FromType2 = S.Context.getArrayDecayedType(FromType2);
3573 
3574     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3575     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3576 
3577     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3578       return ImplicitConversionSequence::Better;
3579     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3580       return ImplicitConversionSequence::Worse;
3581 
3582     // Objective-C++: If one interface is more specific than the
3583     // other, it is the better one.
3584     const ObjCObjectPointerType* FromObjCPtr1
3585       = FromType1->getAs<ObjCObjectPointerType>();
3586     const ObjCObjectPointerType* FromObjCPtr2
3587       = FromType2->getAs<ObjCObjectPointerType>();
3588     if (FromObjCPtr1 && FromObjCPtr2) {
3589       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3590                                                           FromObjCPtr2);
3591       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3592                                                            FromObjCPtr1);
3593       if (AssignLeft != AssignRight) {
3594         return AssignLeft? ImplicitConversionSequence::Better
3595                          : ImplicitConversionSequence::Worse;
3596       }
3597     }
3598   }
3599 
3600   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3601   // bullet 3).
3602   if (ImplicitConversionSequence::CompareKind QualCK
3603         = CompareQualificationConversions(S, SCS1, SCS2))
3604     return QualCK;
3605 
3606   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3607     // Check for a better reference binding based on the kind of bindings.
3608     if (isBetterReferenceBindingKind(SCS1, SCS2))
3609       return ImplicitConversionSequence::Better;
3610     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3611       return ImplicitConversionSequence::Worse;
3612 
3613     // C++ [over.ics.rank]p3b4:
3614     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3615     //      which the references refer are the same type except for
3616     //      top-level cv-qualifiers, and the type to which the reference
3617     //      initialized by S2 refers is more cv-qualified than the type
3618     //      to which the reference initialized by S1 refers.
3619     QualType T1 = SCS1.getToType(2);
3620     QualType T2 = SCS2.getToType(2);
3621     T1 = S.Context.getCanonicalType(T1);
3622     T2 = S.Context.getCanonicalType(T2);
3623     Qualifiers T1Quals, T2Quals;
3624     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3625     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3626     if (UnqualT1 == UnqualT2) {
3627       // Objective-C++ ARC: If the references refer to objects with different
3628       // lifetimes, prefer bindings that don't change lifetime.
3629       if (SCS1.ObjCLifetimeConversionBinding !=
3630                                           SCS2.ObjCLifetimeConversionBinding) {
3631         return SCS1.ObjCLifetimeConversionBinding
3632                                            ? ImplicitConversionSequence::Worse
3633                                            : ImplicitConversionSequence::Better;
3634       }
3635 
3636       // If the type is an array type, promote the element qualifiers to the
3637       // type for comparison.
3638       if (isa<ArrayType>(T1) && T1Quals)
3639         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3640       if (isa<ArrayType>(T2) && T2Quals)
3641         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3642       if (T2.isMoreQualifiedThan(T1))
3643         return ImplicitConversionSequence::Better;
3644       else if (T1.isMoreQualifiedThan(T2))
3645         return ImplicitConversionSequence::Worse;
3646     }
3647   }
3648 
3649   // In Microsoft mode, prefer an integral conversion to a
3650   // floating-to-integral conversion if the integral conversion
3651   // is between types of the same size.
3652   // For example:
3653   // void f(float);
3654   // void f(int);
3655   // int main {
3656   //    long a;
3657   //    f(a);
3658   // }
3659   // Here, MSVC will call f(int) instead of generating a compile error
3660   // as clang will do in standard mode.
3661   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3662       SCS2.Second == ICK_Floating_Integral &&
3663       S.Context.getTypeSize(SCS1.getFromType()) ==
3664           S.Context.getTypeSize(SCS1.getToType(2)))
3665     return ImplicitConversionSequence::Better;
3666 
3667   return ImplicitConversionSequence::Indistinguishable;
3668 }
3669 
3670 /// CompareQualificationConversions - Compares two standard conversion
3671 /// sequences to determine whether they can be ranked based on their
3672 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3673 static ImplicitConversionSequence::CompareKind
3674 CompareQualificationConversions(Sema &S,
3675                                 const StandardConversionSequence& SCS1,
3676                                 const StandardConversionSequence& SCS2) {
3677   // C++ 13.3.3.2p3:
3678   //  -- S1 and S2 differ only in their qualification conversion and
3679   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3680   //     cv-qualification signature of type T1 is a proper subset of
3681   //     the cv-qualification signature of type T2, and S1 is not the
3682   //     deprecated string literal array-to-pointer conversion (4.2).
3683   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3684       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3685     return ImplicitConversionSequence::Indistinguishable;
3686 
3687   // FIXME: the example in the standard doesn't use a qualification
3688   // conversion (!)
3689   QualType T1 = SCS1.getToType(2);
3690   QualType T2 = SCS2.getToType(2);
3691   T1 = S.Context.getCanonicalType(T1);
3692   T2 = S.Context.getCanonicalType(T2);
3693   Qualifiers T1Quals, T2Quals;
3694   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3695   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3696 
3697   // If the types are the same, we won't learn anything by unwrapped
3698   // them.
3699   if (UnqualT1 == UnqualT2)
3700     return ImplicitConversionSequence::Indistinguishable;
3701 
3702   // If the type is an array type, promote the element qualifiers to the type
3703   // for comparison.
3704   if (isa<ArrayType>(T1) && T1Quals)
3705     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3706   if (isa<ArrayType>(T2) && T2Quals)
3707     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3708 
3709   ImplicitConversionSequence::CompareKind Result
3710     = ImplicitConversionSequence::Indistinguishable;
3711 
3712   // Objective-C++ ARC:
3713   //   Prefer qualification conversions not involving a change in lifetime
3714   //   to qualification conversions that do not change lifetime.
3715   if (SCS1.QualificationIncludesObjCLifetime !=
3716                                       SCS2.QualificationIncludesObjCLifetime) {
3717     Result = SCS1.QualificationIncludesObjCLifetime
3718                ? ImplicitConversionSequence::Worse
3719                : ImplicitConversionSequence::Better;
3720   }
3721 
3722   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3723     // Within each iteration of the loop, we check the qualifiers to
3724     // determine if this still looks like a qualification
3725     // conversion. Then, if all is well, we unwrap one more level of
3726     // pointers or pointers-to-members and do it all again
3727     // until there are no more pointers or pointers-to-members left
3728     // to unwrap. This essentially mimics what
3729     // IsQualificationConversion does, but here we're checking for a
3730     // strict subset of qualifiers.
3731     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3732       // The qualifiers are the same, so this doesn't tell us anything
3733       // about how the sequences rank.
3734       ;
3735     else if (T2.isMoreQualifiedThan(T1)) {
3736       // T1 has fewer qualifiers, so it could be the better sequence.
3737       if (Result == ImplicitConversionSequence::Worse)
3738         // Neither has qualifiers that are a subset of the other's
3739         // qualifiers.
3740         return ImplicitConversionSequence::Indistinguishable;
3741 
3742       Result = ImplicitConversionSequence::Better;
3743     } else if (T1.isMoreQualifiedThan(T2)) {
3744       // T2 has fewer qualifiers, so it could be the better sequence.
3745       if (Result == ImplicitConversionSequence::Better)
3746         // Neither has qualifiers that are a subset of the other's
3747         // qualifiers.
3748         return ImplicitConversionSequence::Indistinguishable;
3749 
3750       Result = ImplicitConversionSequence::Worse;
3751     } else {
3752       // Qualifiers are disjoint.
3753       return ImplicitConversionSequence::Indistinguishable;
3754     }
3755 
3756     // If the types after this point are equivalent, we're done.
3757     if (S.Context.hasSameUnqualifiedType(T1, T2))
3758       break;
3759   }
3760 
3761   // Check that the winning standard conversion sequence isn't using
3762   // the deprecated string literal array to pointer conversion.
3763   switch (Result) {
3764   case ImplicitConversionSequence::Better:
3765     if (SCS1.DeprecatedStringLiteralToCharPtr)
3766       Result = ImplicitConversionSequence::Indistinguishable;
3767     break;
3768 
3769   case ImplicitConversionSequence::Indistinguishable:
3770     break;
3771 
3772   case ImplicitConversionSequence::Worse:
3773     if (SCS2.DeprecatedStringLiteralToCharPtr)
3774       Result = ImplicitConversionSequence::Indistinguishable;
3775     break;
3776   }
3777 
3778   return Result;
3779 }
3780 
3781 /// CompareDerivedToBaseConversions - Compares two standard conversion
3782 /// sequences to determine whether they can be ranked based on their
3783 /// various kinds of derived-to-base conversions (C++
3784 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3785 /// conversions between Objective-C interface types.
3786 static ImplicitConversionSequence::CompareKind
3787 CompareDerivedToBaseConversions(Sema &S,
3788                                 const StandardConversionSequence& SCS1,
3789                                 const StandardConversionSequence& SCS2) {
3790   QualType FromType1 = SCS1.getFromType();
3791   QualType ToType1 = SCS1.getToType(1);
3792   QualType FromType2 = SCS2.getFromType();
3793   QualType ToType2 = SCS2.getToType(1);
3794 
3795   // Adjust the types we're converting from via the array-to-pointer
3796   // conversion, if we need to.
3797   if (SCS1.First == ICK_Array_To_Pointer)
3798     FromType1 = S.Context.getArrayDecayedType(FromType1);
3799   if (SCS2.First == ICK_Array_To_Pointer)
3800     FromType2 = S.Context.getArrayDecayedType(FromType2);
3801 
3802   // Canonicalize all of the types.
3803   FromType1 = S.Context.getCanonicalType(FromType1);
3804   ToType1 = S.Context.getCanonicalType(ToType1);
3805   FromType2 = S.Context.getCanonicalType(FromType2);
3806   ToType2 = S.Context.getCanonicalType(ToType2);
3807 
3808   // C++ [over.ics.rank]p4b3:
3809   //
3810   //   If class B is derived directly or indirectly from class A and
3811   //   class C is derived directly or indirectly from B,
3812   //
3813   // Compare based on pointer conversions.
3814   if (SCS1.Second == ICK_Pointer_Conversion &&
3815       SCS2.Second == ICK_Pointer_Conversion &&
3816       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3817       FromType1->isPointerType() && FromType2->isPointerType() &&
3818       ToType1->isPointerType() && ToType2->isPointerType()) {
3819     QualType FromPointee1
3820       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3821     QualType ToPointee1
3822       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3823     QualType FromPointee2
3824       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3825     QualType ToPointee2
3826       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3827 
3828     //   -- conversion of C* to B* is better than conversion of C* to A*,
3829     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3830       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3831         return ImplicitConversionSequence::Better;
3832       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3833         return ImplicitConversionSequence::Worse;
3834     }
3835 
3836     //   -- conversion of B* to A* is better than conversion of C* to A*,
3837     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3838       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3839         return ImplicitConversionSequence::Better;
3840       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3841         return ImplicitConversionSequence::Worse;
3842     }
3843   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3844              SCS2.Second == ICK_Pointer_Conversion) {
3845     const ObjCObjectPointerType *FromPtr1
3846       = FromType1->getAs<ObjCObjectPointerType>();
3847     const ObjCObjectPointerType *FromPtr2
3848       = FromType2->getAs<ObjCObjectPointerType>();
3849     const ObjCObjectPointerType *ToPtr1
3850       = ToType1->getAs<ObjCObjectPointerType>();
3851     const ObjCObjectPointerType *ToPtr2
3852       = ToType2->getAs<ObjCObjectPointerType>();
3853 
3854     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3855       // Apply the same conversion ranking rules for Objective-C pointer types
3856       // that we do for C++ pointers to class types. However, we employ the
3857       // Objective-C pseudo-subtyping relationship used for assignment of
3858       // Objective-C pointer types.
3859       bool FromAssignLeft
3860         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3861       bool FromAssignRight
3862         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3863       bool ToAssignLeft
3864         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3865       bool ToAssignRight
3866         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3867 
3868       // A conversion to an a non-id object pointer type or qualified 'id'
3869       // type is better than a conversion to 'id'.
3870       if (ToPtr1->isObjCIdType() &&
3871           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3872         return ImplicitConversionSequence::Worse;
3873       if (ToPtr2->isObjCIdType() &&
3874           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3875         return ImplicitConversionSequence::Better;
3876 
3877       // A conversion to a non-id object pointer type is better than a
3878       // conversion to a qualified 'id' type
3879       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3880         return ImplicitConversionSequence::Worse;
3881       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3882         return ImplicitConversionSequence::Better;
3883 
3884       // A conversion to an a non-Class object pointer type or qualified 'Class'
3885       // type is better than a conversion to 'Class'.
3886       if (ToPtr1->isObjCClassType() &&
3887           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3888         return ImplicitConversionSequence::Worse;
3889       if (ToPtr2->isObjCClassType() &&
3890           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3891         return ImplicitConversionSequence::Better;
3892 
3893       // A conversion to a non-Class object pointer type is better than a
3894       // conversion to a qualified 'Class' type.
3895       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3896         return ImplicitConversionSequence::Worse;
3897       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3898         return ImplicitConversionSequence::Better;
3899 
3900       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3901       if (S.Context.hasSameType(FromType1, FromType2) &&
3902           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3903           (ToAssignLeft != ToAssignRight))
3904         return ToAssignLeft? ImplicitConversionSequence::Worse
3905                            : ImplicitConversionSequence::Better;
3906 
3907       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3908       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3909           (FromAssignLeft != FromAssignRight))
3910         return FromAssignLeft? ImplicitConversionSequence::Better
3911         : ImplicitConversionSequence::Worse;
3912     }
3913   }
3914 
3915   // Ranking of member-pointer types.
3916   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3917       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3918       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3919     const MemberPointerType * FromMemPointer1 =
3920                                         FromType1->getAs<MemberPointerType>();
3921     const MemberPointerType * ToMemPointer1 =
3922                                           ToType1->getAs<MemberPointerType>();
3923     const MemberPointerType * FromMemPointer2 =
3924                                           FromType2->getAs<MemberPointerType>();
3925     const MemberPointerType * ToMemPointer2 =
3926                                           ToType2->getAs<MemberPointerType>();
3927     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3928     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3929     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3930     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3931     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3932     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3933     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3934     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3935     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3936     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3937       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3938         return ImplicitConversionSequence::Worse;
3939       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3940         return ImplicitConversionSequence::Better;
3941     }
3942     // conversion of B::* to C::* is better than conversion of A::* to C::*
3943     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3944       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3945         return ImplicitConversionSequence::Better;
3946       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3947         return ImplicitConversionSequence::Worse;
3948     }
3949   }
3950 
3951   if (SCS1.Second == ICK_Derived_To_Base) {
3952     //   -- conversion of C to B is better than conversion of C to A,
3953     //   -- binding of an expression of type C to a reference of type
3954     //      B& is better than binding an expression of type C to a
3955     //      reference of type A&,
3956     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3957         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3958       if (S.IsDerivedFrom(ToType1, ToType2))
3959         return ImplicitConversionSequence::Better;
3960       else if (S.IsDerivedFrom(ToType2, ToType1))
3961         return ImplicitConversionSequence::Worse;
3962     }
3963 
3964     //   -- conversion of B to A is better than conversion of C to A.
3965     //   -- binding of an expression of type B to a reference of type
3966     //      A& is better than binding an expression of type C to a
3967     //      reference of type A&,
3968     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3969         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3970       if (S.IsDerivedFrom(FromType2, FromType1))
3971         return ImplicitConversionSequence::Better;
3972       else if (S.IsDerivedFrom(FromType1, FromType2))
3973         return ImplicitConversionSequence::Worse;
3974     }
3975   }
3976 
3977   return ImplicitConversionSequence::Indistinguishable;
3978 }
3979 
3980 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3981 /// C++ class.
3982 static bool isTypeValid(QualType T) {
3983   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3984     return !Record->isInvalidDecl();
3985 
3986   return true;
3987 }
3988 
3989 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3990 /// determine whether they are reference-related,
3991 /// reference-compatible, reference-compatible with added
3992 /// qualification, or incompatible, for use in C++ initialization by
3993 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3994 /// type, and the first type (T1) is the pointee type of the reference
3995 /// type being initialized.
3996 Sema::ReferenceCompareResult
3997 Sema::CompareReferenceRelationship(SourceLocation Loc,
3998                                    QualType OrigT1, QualType OrigT2,
3999                                    bool &DerivedToBase,
4000                                    bool &ObjCConversion,
4001                                    bool &ObjCLifetimeConversion) {
4002   assert(!OrigT1->isReferenceType() &&
4003     "T1 must be the pointee type of the reference type");
4004   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4005 
4006   QualType T1 = Context.getCanonicalType(OrigT1);
4007   QualType T2 = Context.getCanonicalType(OrigT2);
4008   Qualifiers T1Quals, T2Quals;
4009   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4010   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4011 
4012   // C++ [dcl.init.ref]p4:
4013   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4014   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4015   //   T1 is a base class of T2.
4016   DerivedToBase = false;
4017   ObjCConversion = false;
4018   ObjCLifetimeConversion = false;
4019   if (UnqualT1 == UnqualT2) {
4020     // Nothing to do.
4021   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
4022              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4023              IsDerivedFrom(UnqualT2, UnqualT1))
4024     DerivedToBase = true;
4025   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4026            UnqualT2->isObjCObjectOrInterfaceType() &&
4027            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4028     ObjCConversion = true;
4029   else
4030     return Ref_Incompatible;
4031 
4032   // At this point, we know that T1 and T2 are reference-related (at
4033   // least).
4034 
4035   // If the type is an array type, promote the element qualifiers to the type
4036   // for comparison.
4037   if (isa<ArrayType>(T1) && T1Quals)
4038     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4039   if (isa<ArrayType>(T2) && T2Quals)
4040     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4041 
4042   // C++ [dcl.init.ref]p4:
4043   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4044   //   reference-related to T2 and cv1 is the same cv-qualification
4045   //   as, or greater cv-qualification than, cv2. For purposes of
4046   //   overload resolution, cases for which cv1 is greater
4047   //   cv-qualification than cv2 are identified as
4048   //   reference-compatible with added qualification (see 13.3.3.2).
4049   //
4050   // Note that we also require equivalence of Objective-C GC and address-space
4051   // qualifiers when performing these computations, so that e.g., an int in
4052   // address space 1 is not reference-compatible with an int in address
4053   // space 2.
4054   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4055       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4056     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4057       ObjCLifetimeConversion = true;
4058 
4059     T1Quals.removeObjCLifetime();
4060     T2Quals.removeObjCLifetime();
4061   }
4062 
4063   if (T1Quals == T2Quals)
4064     return Ref_Compatible;
4065   else if (T1Quals.compatiblyIncludes(T2Quals))
4066     return Ref_Compatible_With_Added_Qualification;
4067   else
4068     return Ref_Related;
4069 }
4070 
4071 /// \brief Look for a user-defined conversion to an value reference-compatible
4072 ///        with DeclType. Return true if something definite is found.
4073 static bool
4074 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4075                          QualType DeclType, SourceLocation DeclLoc,
4076                          Expr *Init, QualType T2, bool AllowRvalues,
4077                          bool AllowExplicit) {
4078   assert(T2->isRecordType() && "Can only find conversions of record types.");
4079   CXXRecordDecl *T2RecordDecl
4080     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4081 
4082   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4083   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4084   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4085     NamedDecl *D = *I;
4086     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4087     if (isa<UsingShadowDecl>(D))
4088       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4089 
4090     FunctionTemplateDecl *ConvTemplate
4091       = dyn_cast<FunctionTemplateDecl>(D);
4092     CXXConversionDecl *Conv;
4093     if (ConvTemplate)
4094       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4095     else
4096       Conv = cast<CXXConversionDecl>(D);
4097 
4098     // If this is an explicit conversion, and we're not allowed to consider
4099     // explicit conversions, skip it.
4100     if (!AllowExplicit && Conv->isExplicit())
4101       continue;
4102 
4103     if (AllowRvalues) {
4104       bool DerivedToBase = false;
4105       bool ObjCConversion = false;
4106       bool ObjCLifetimeConversion = false;
4107 
4108       // If we are initializing an rvalue reference, don't permit conversion
4109       // functions that return lvalues.
4110       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4111         const ReferenceType *RefType
4112           = Conv->getConversionType()->getAs<LValueReferenceType>();
4113         if (RefType && !RefType->getPointeeType()->isFunctionType())
4114           continue;
4115       }
4116 
4117       if (!ConvTemplate &&
4118           S.CompareReferenceRelationship(
4119             DeclLoc,
4120             Conv->getConversionType().getNonReferenceType()
4121               .getUnqualifiedType(),
4122             DeclType.getNonReferenceType().getUnqualifiedType(),
4123             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4124           Sema::Ref_Incompatible)
4125         continue;
4126     } else {
4127       // If the conversion function doesn't return a reference type,
4128       // it can't be considered for this conversion. An rvalue reference
4129       // is only acceptable if its referencee is a function type.
4130 
4131       const ReferenceType *RefType =
4132         Conv->getConversionType()->getAs<ReferenceType>();
4133       if (!RefType ||
4134           (!RefType->isLValueReferenceType() &&
4135            !RefType->getPointeeType()->isFunctionType()))
4136         continue;
4137     }
4138 
4139     if (ConvTemplate)
4140       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4141                                        Init, DeclType, CandidateSet,
4142                                        /*AllowObjCConversionOnExplicit=*/false);
4143     else
4144       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4145                                DeclType, CandidateSet,
4146                                /*AllowObjCConversionOnExplicit=*/false);
4147   }
4148 
4149   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4150 
4151   OverloadCandidateSet::iterator Best;
4152   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4153   case OR_Success:
4154     // C++ [over.ics.ref]p1:
4155     //
4156     //   [...] If the parameter binds directly to the result of
4157     //   applying a conversion function to the argument
4158     //   expression, the implicit conversion sequence is a
4159     //   user-defined conversion sequence (13.3.3.1.2), with the
4160     //   second standard conversion sequence either an identity
4161     //   conversion or, if the conversion function returns an
4162     //   entity of a type that is a derived class of the parameter
4163     //   type, a derived-to-base Conversion.
4164     if (!Best->FinalConversion.DirectBinding)
4165       return false;
4166 
4167     ICS.setUserDefined();
4168     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4169     ICS.UserDefined.After = Best->FinalConversion;
4170     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4171     ICS.UserDefined.ConversionFunction = Best->Function;
4172     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4173     ICS.UserDefined.EllipsisConversion = false;
4174     assert(ICS.UserDefined.After.ReferenceBinding &&
4175            ICS.UserDefined.After.DirectBinding &&
4176            "Expected a direct reference binding!");
4177     return true;
4178 
4179   case OR_Ambiguous:
4180     ICS.setAmbiguous();
4181     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4182          Cand != CandidateSet.end(); ++Cand)
4183       if (Cand->Viable)
4184         ICS.Ambiguous.addConversion(Cand->Function);
4185     return true;
4186 
4187   case OR_No_Viable_Function:
4188   case OR_Deleted:
4189     // There was no suitable conversion, or we found a deleted
4190     // conversion; continue with other checks.
4191     return false;
4192   }
4193 
4194   llvm_unreachable("Invalid OverloadResult!");
4195 }
4196 
4197 /// \brief Compute an implicit conversion sequence for reference
4198 /// initialization.
4199 static ImplicitConversionSequence
4200 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4201                  SourceLocation DeclLoc,
4202                  bool SuppressUserConversions,
4203                  bool AllowExplicit) {
4204   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4205 
4206   // Most paths end in a failed conversion.
4207   ImplicitConversionSequence ICS;
4208   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4209 
4210   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4211   QualType T2 = Init->getType();
4212 
4213   // If the initializer is the address of an overloaded function, try
4214   // to resolve the overloaded function. If all goes well, T2 is the
4215   // type of the resulting function.
4216   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4217     DeclAccessPair Found;
4218     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4219                                                                 false, Found))
4220       T2 = Fn->getType();
4221   }
4222 
4223   // Compute some basic properties of the types and the initializer.
4224   bool isRValRef = DeclType->isRValueReferenceType();
4225   bool DerivedToBase = false;
4226   bool ObjCConversion = false;
4227   bool ObjCLifetimeConversion = false;
4228   Expr::Classification InitCategory = Init->Classify(S.Context);
4229   Sema::ReferenceCompareResult RefRelationship
4230     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4231                                      ObjCConversion, ObjCLifetimeConversion);
4232 
4233 
4234   // C++0x [dcl.init.ref]p5:
4235   //   A reference to type "cv1 T1" is initialized by an expression
4236   //   of type "cv2 T2" as follows:
4237 
4238   //     -- If reference is an lvalue reference and the initializer expression
4239   if (!isRValRef) {
4240     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4241     //        reference-compatible with "cv2 T2," or
4242     //
4243     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4244     if (InitCategory.isLValue() &&
4245         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4246       // C++ [over.ics.ref]p1:
4247       //   When a parameter of reference type binds directly (8.5.3)
4248       //   to an argument expression, the implicit conversion sequence
4249       //   is the identity conversion, unless the argument expression
4250       //   has a type that is a derived class of the parameter type,
4251       //   in which case the implicit conversion sequence is a
4252       //   derived-to-base Conversion (13.3.3.1).
4253       ICS.setStandard();
4254       ICS.Standard.First = ICK_Identity;
4255       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4256                          : ObjCConversion? ICK_Compatible_Conversion
4257                          : ICK_Identity;
4258       ICS.Standard.Third = ICK_Identity;
4259       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4260       ICS.Standard.setToType(0, T2);
4261       ICS.Standard.setToType(1, T1);
4262       ICS.Standard.setToType(2, T1);
4263       ICS.Standard.ReferenceBinding = true;
4264       ICS.Standard.DirectBinding = true;
4265       ICS.Standard.IsLvalueReference = !isRValRef;
4266       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4267       ICS.Standard.BindsToRvalue = false;
4268       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4269       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4270       ICS.Standard.CopyConstructor = nullptr;
4271       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4272 
4273       // Nothing more to do: the inaccessibility/ambiguity check for
4274       // derived-to-base conversions is suppressed when we're
4275       // computing the implicit conversion sequence (C++
4276       // [over.best.ics]p2).
4277       return ICS;
4278     }
4279 
4280     //       -- has a class type (i.e., T2 is a class type), where T1 is
4281     //          not reference-related to T2, and can be implicitly
4282     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4283     //          is reference-compatible with "cv3 T3" 92) (this
4284     //          conversion is selected by enumerating the applicable
4285     //          conversion functions (13.3.1.6) and choosing the best
4286     //          one through overload resolution (13.3)),
4287     if (!SuppressUserConversions && T2->isRecordType() &&
4288         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4289         RefRelationship == Sema::Ref_Incompatible) {
4290       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4291                                    Init, T2, /*AllowRvalues=*/false,
4292                                    AllowExplicit))
4293         return ICS;
4294     }
4295   }
4296 
4297   //     -- Otherwise, the reference shall be an lvalue reference to a
4298   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4299   //        shall be an rvalue reference.
4300   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4301     return ICS;
4302 
4303   //       -- If the initializer expression
4304   //
4305   //            -- is an xvalue, class prvalue, array prvalue or function
4306   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4307   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4308       (InitCategory.isXValue() ||
4309       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4310       (InitCategory.isLValue() && T2->isFunctionType()))) {
4311     ICS.setStandard();
4312     ICS.Standard.First = ICK_Identity;
4313     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4314                       : ObjCConversion? ICK_Compatible_Conversion
4315                       : ICK_Identity;
4316     ICS.Standard.Third = ICK_Identity;
4317     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4318     ICS.Standard.setToType(0, T2);
4319     ICS.Standard.setToType(1, T1);
4320     ICS.Standard.setToType(2, T1);
4321     ICS.Standard.ReferenceBinding = true;
4322     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4323     // binding unless we're binding to a class prvalue.
4324     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4325     // allow the use of rvalue references in C++98/03 for the benefit of
4326     // standard library implementors; therefore, we need the xvalue check here.
4327     ICS.Standard.DirectBinding =
4328       S.getLangOpts().CPlusPlus11 ||
4329       !(InitCategory.isPRValue() || T2->isRecordType());
4330     ICS.Standard.IsLvalueReference = !isRValRef;
4331     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4332     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4333     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4334     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4335     ICS.Standard.CopyConstructor = nullptr;
4336     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4337     return ICS;
4338   }
4339 
4340   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4341   //               reference-related to T2, and can be implicitly converted to
4342   //               an xvalue, class prvalue, or function lvalue of type
4343   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4344   //               "cv3 T3",
4345   //
4346   //          then the reference is bound to the value of the initializer
4347   //          expression in the first case and to the result of the conversion
4348   //          in the second case (or, in either case, to an appropriate base
4349   //          class subobject).
4350   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4351       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4352       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4353                                Init, T2, /*AllowRvalues=*/true,
4354                                AllowExplicit)) {
4355     // In the second case, if the reference is an rvalue reference
4356     // and the second standard conversion sequence of the
4357     // user-defined conversion sequence includes an lvalue-to-rvalue
4358     // conversion, the program is ill-formed.
4359     if (ICS.isUserDefined() && isRValRef &&
4360         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4361       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4362 
4363     return ICS;
4364   }
4365 
4366   // A temporary of function type cannot be created; don't even try.
4367   if (T1->isFunctionType())
4368     return ICS;
4369 
4370   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4371   //          initialized from the initializer expression using the
4372   //          rules for a non-reference copy initialization (8.5). The
4373   //          reference is then bound to the temporary. If T1 is
4374   //          reference-related to T2, cv1 must be the same
4375   //          cv-qualification as, or greater cv-qualification than,
4376   //          cv2; otherwise, the program is ill-formed.
4377   if (RefRelationship == Sema::Ref_Related) {
4378     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4379     // we would be reference-compatible or reference-compatible with
4380     // added qualification. But that wasn't the case, so the reference
4381     // initialization fails.
4382     //
4383     // Note that we only want to check address spaces and cvr-qualifiers here.
4384     // ObjC GC and lifetime qualifiers aren't important.
4385     Qualifiers T1Quals = T1.getQualifiers();
4386     Qualifiers T2Quals = T2.getQualifiers();
4387     T1Quals.removeObjCGCAttr();
4388     T1Quals.removeObjCLifetime();
4389     T2Quals.removeObjCGCAttr();
4390     T2Quals.removeObjCLifetime();
4391     if (!T1Quals.compatiblyIncludes(T2Quals))
4392       return ICS;
4393   }
4394 
4395   // If at least one of the types is a class type, the types are not
4396   // related, and we aren't allowed any user conversions, the
4397   // reference binding fails. This case is important for breaking
4398   // recursion, since TryImplicitConversion below will attempt to
4399   // create a temporary through the use of a copy constructor.
4400   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4401       (T1->isRecordType() || T2->isRecordType()))
4402     return ICS;
4403 
4404   // If T1 is reference-related to T2 and the reference is an rvalue
4405   // reference, the initializer expression shall not be an lvalue.
4406   if (RefRelationship >= Sema::Ref_Related &&
4407       isRValRef && Init->Classify(S.Context).isLValue())
4408     return ICS;
4409 
4410   // C++ [over.ics.ref]p2:
4411   //   When a parameter of reference type is not bound directly to
4412   //   an argument expression, the conversion sequence is the one
4413   //   required to convert the argument expression to the
4414   //   underlying type of the reference according to
4415   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4416   //   to copy-initializing a temporary of the underlying type with
4417   //   the argument expression. Any difference in top-level
4418   //   cv-qualification is subsumed by the initialization itself
4419   //   and does not constitute a conversion.
4420   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4421                               /*AllowExplicit=*/false,
4422                               /*InOverloadResolution=*/false,
4423                               /*CStyle=*/false,
4424                               /*AllowObjCWritebackConversion=*/false,
4425                               /*AllowObjCConversionOnExplicit=*/false);
4426 
4427   // Of course, that's still a reference binding.
4428   if (ICS.isStandard()) {
4429     ICS.Standard.ReferenceBinding = true;
4430     ICS.Standard.IsLvalueReference = !isRValRef;
4431     ICS.Standard.BindsToFunctionLvalue = false;
4432     ICS.Standard.BindsToRvalue = true;
4433     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4434     ICS.Standard.ObjCLifetimeConversionBinding = false;
4435   } else if (ICS.isUserDefined()) {
4436     const ReferenceType *LValRefType =
4437         ICS.UserDefined.ConversionFunction->getReturnType()
4438             ->getAs<LValueReferenceType>();
4439 
4440     // C++ [over.ics.ref]p3:
4441     //   Except for an implicit object parameter, for which see 13.3.1, a
4442     //   standard conversion sequence cannot be formed if it requires [...]
4443     //   binding an rvalue reference to an lvalue other than a function
4444     //   lvalue.
4445     // Note that the function case is not possible here.
4446     if (DeclType->isRValueReferenceType() && LValRefType) {
4447       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4448       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4449       // reference to an rvalue!
4450       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4451       return ICS;
4452     }
4453 
4454     ICS.UserDefined.Before.setAsIdentityConversion();
4455     ICS.UserDefined.After.ReferenceBinding = true;
4456     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4457     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4458     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4459     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4460     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4461   }
4462 
4463   return ICS;
4464 }
4465 
4466 static ImplicitConversionSequence
4467 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4468                       bool SuppressUserConversions,
4469                       bool InOverloadResolution,
4470                       bool AllowObjCWritebackConversion,
4471                       bool AllowExplicit = false);
4472 
4473 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4474 /// initializer list From.
4475 static ImplicitConversionSequence
4476 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4477                   bool SuppressUserConversions,
4478                   bool InOverloadResolution,
4479                   bool AllowObjCWritebackConversion) {
4480   // C++11 [over.ics.list]p1:
4481   //   When an argument is an initializer list, it is not an expression and
4482   //   special rules apply for converting it to a parameter type.
4483 
4484   ImplicitConversionSequence Result;
4485   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4486 
4487   // We need a complete type for what follows. Incomplete types can never be
4488   // initialized from init lists.
4489   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4490     return Result;
4491 
4492   // Per DR1467:
4493   //   If the parameter type is a class X and the initializer list has a single
4494   //   element of type cv U, where U is X or a class derived from X, the
4495   //   implicit conversion sequence is the one required to convert the element
4496   //   to the parameter type.
4497   //
4498   //   Otherwise, if the parameter type is a character array [... ]
4499   //   and the initializer list has a single element that is an
4500   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4501   //   implicit conversion sequence is the identity conversion.
4502   if (From->getNumInits() == 1) {
4503     if (ToType->isRecordType()) {
4504       QualType InitType = From->getInit(0)->getType();
4505       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4506           S.IsDerivedFrom(InitType, ToType))
4507         return TryCopyInitialization(S, From->getInit(0), ToType,
4508                                      SuppressUserConversions,
4509                                      InOverloadResolution,
4510                                      AllowObjCWritebackConversion);
4511     }
4512     // FIXME: Check the other conditions here: array of character type,
4513     // initializer is a string literal.
4514     if (ToType->isArrayType()) {
4515       InitializedEntity Entity =
4516         InitializedEntity::InitializeParameter(S.Context, ToType,
4517                                                /*Consumed=*/false);
4518       if (S.CanPerformCopyInitialization(Entity, From)) {
4519         Result.setStandard();
4520         Result.Standard.setAsIdentityConversion();
4521         Result.Standard.setFromType(ToType);
4522         Result.Standard.setAllToTypes(ToType);
4523         return Result;
4524       }
4525     }
4526   }
4527 
4528   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4529   // C++11 [over.ics.list]p2:
4530   //   If the parameter type is std::initializer_list<X> or "array of X" and
4531   //   all the elements can be implicitly converted to X, the implicit
4532   //   conversion sequence is the worst conversion necessary to convert an
4533   //   element of the list to X.
4534   //
4535   // C++14 [over.ics.list]p3:
4536   //   Otherwise, if the parameter type is "array of N X", if the initializer
4537   //   list has exactly N elements or if it has fewer than N elements and X is
4538   //   default-constructible, and if all the elements of the initializer list
4539   //   can be implicitly converted to X, the implicit conversion sequence is
4540   //   the worst conversion necessary to convert an element of the list to X.
4541   //
4542   // FIXME: We're missing a lot of these checks.
4543   bool toStdInitializerList = false;
4544   QualType X;
4545   if (ToType->isArrayType())
4546     X = S.Context.getAsArrayType(ToType)->getElementType();
4547   else
4548     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4549   if (!X.isNull()) {
4550     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4551       Expr *Init = From->getInit(i);
4552       ImplicitConversionSequence ICS =
4553           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4554                                 InOverloadResolution,
4555                                 AllowObjCWritebackConversion);
4556       // If a single element isn't convertible, fail.
4557       if (ICS.isBad()) {
4558         Result = ICS;
4559         break;
4560       }
4561       // Otherwise, look for the worst conversion.
4562       if (Result.isBad() ||
4563           CompareImplicitConversionSequences(S, ICS, Result) ==
4564               ImplicitConversionSequence::Worse)
4565         Result = ICS;
4566     }
4567 
4568     // For an empty list, we won't have computed any conversion sequence.
4569     // Introduce the identity conversion sequence.
4570     if (From->getNumInits() == 0) {
4571       Result.setStandard();
4572       Result.Standard.setAsIdentityConversion();
4573       Result.Standard.setFromType(ToType);
4574       Result.Standard.setAllToTypes(ToType);
4575     }
4576 
4577     Result.setStdInitializerListElement(toStdInitializerList);
4578     return Result;
4579   }
4580 
4581   // C++14 [over.ics.list]p4:
4582   // C++11 [over.ics.list]p3:
4583   //   Otherwise, if the parameter is a non-aggregate class X and overload
4584   //   resolution chooses a single best constructor [...] the implicit
4585   //   conversion sequence is a user-defined conversion sequence. If multiple
4586   //   constructors are viable but none is better than the others, the
4587   //   implicit conversion sequence is a user-defined conversion sequence.
4588   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4589     // This function can deal with initializer lists.
4590     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4591                                     /*AllowExplicit=*/false,
4592                                     InOverloadResolution, /*CStyle=*/false,
4593                                     AllowObjCWritebackConversion,
4594                                     /*AllowObjCConversionOnExplicit=*/false);
4595   }
4596 
4597   // C++14 [over.ics.list]p5:
4598   // C++11 [over.ics.list]p4:
4599   //   Otherwise, if the parameter has an aggregate type which can be
4600   //   initialized from the initializer list [...] the implicit conversion
4601   //   sequence is a user-defined conversion sequence.
4602   if (ToType->isAggregateType()) {
4603     // Type is an aggregate, argument is an init list. At this point it comes
4604     // down to checking whether the initialization works.
4605     // FIXME: Find out whether this parameter is consumed or not.
4606     InitializedEntity Entity =
4607         InitializedEntity::InitializeParameter(S.Context, ToType,
4608                                                /*Consumed=*/false);
4609     if (S.CanPerformCopyInitialization(Entity, From)) {
4610       Result.setUserDefined();
4611       Result.UserDefined.Before.setAsIdentityConversion();
4612       // Initializer lists don't have a type.
4613       Result.UserDefined.Before.setFromType(QualType());
4614       Result.UserDefined.Before.setAllToTypes(QualType());
4615 
4616       Result.UserDefined.After.setAsIdentityConversion();
4617       Result.UserDefined.After.setFromType(ToType);
4618       Result.UserDefined.After.setAllToTypes(ToType);
4619       Result.UserDefined.ConversionFunction = nullptr;
4620     }
4621     return Result;
4622   }
4623 
4624   // C++14 [over.ics.list]p6:
4625   // C++11 [over.ics.list]p5:
4626   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4627   if (ToType->isReferenceType()) {
4628     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4629     // mention initializer lists in any way. So we go by what list-
4630     // initialization would do and try to extrapolate from that.
4631 
4632     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4633 
4634     // If the initializer list has a single element that is reference-related
4635     // to the parameter type, we initialize the reference from that.
4636     if (From->getNumInits() == 1) {
4637       Expr *Init = From->getInit(0);
4638 
4639       QualType T2 = Init->getType();
4640 
4641       // If the initializer is the address of an overloaded function, try
4642       // to resolve the overloaded function. If all goes well, T2 is the
4643       // type of the resulting function.
4644       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4645         DeclAccessPair Found;
4646         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4647                                    Init, ToType, false, Found))
4648           T2 = Fn->getType();
4649       }
4650 
4651       // Compute some basic properties of the types and the initializer.
4652       bool dummy1 = false;
4653       bool dummy2 = false;
4654       bool dummy3 = false;
4655       Sema::ReferenceCompareResult RefRelationship
4656         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4657                                          dummy2, dummy3);
4658 
4659       if (RefRelationship >= Sema::Ref_Related) {
4660         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4661                                 SuppressUserConversions,
4662                                 /*AllowExplicit=*/false);
4663       }
4664     }
4665 
4666     // Otherwise, we bind the reference to a temporary created from the
4667     // initializer list.
4668     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4669                                InOverloadResolution,
4670                                AllowObjCWritebackConversion);
4671     if (Result.isFailure())
4672       return Result;
4673     assert(!Result.isEllipsis() &&
4674            "Sub-initialization cannot result in ellipsis conversion.");
4675 
4676     // Can we even bind to a temporary?
4677     if (ToType->isRValueReferenceType() ||
4678         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4679       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4680                                             Result.UserDefined.After;
4681       SCS.ReferenceBinding = true;
4682       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4683       SCS.BindsToRvalue = true;
4684       SCS.BindsToFunctionLvalue = false;
4685       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4686       SCS.ObjCLifetimeConversionBinding = false;
4687     } else
4688       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4689                     From, ToType);
4690     return Result;
4691   }
4692 
4693   // C++14 [over.ics.list]p7:
4694   // C++11 [over.ics.list]p6:
4695   //   Otherwise, if the parameter type is not a class:
4696   if (!ToType->isRecordType()) {
4697     //    - if the initializer list has one element that is not itself an
4698     //      initializer list, the implicit conversion sequence is the one
4699     //      required to convert the element to the parameter type.
4700     unsigned NumInits = From->getNumInits();
4701     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4702       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4703                                      SuppressUserConversions,
4704                                      InOverloadResolution,
4705                                      AllowObjCWritebackConversion);
4706     //    - if the initializer list has no elements, the implicit conversion
4707     //      sequence is the identity conversion.
4708     else if (NumInits == 0) {
4709       Result.setStandard();
4710       Result.Standard.setAsIdentityConversion();
4711       Result.Standard.setFromType(ToType);
4712       Result.Standard.setAllToTypes(ToType);
4713     }
4714     return Result;
4715   }
4716 
4717   // C++14 [over.ics.list]p8:
4718   // C++11 [over.ics.list]p7:
4719   //   In all cases other than those enumerated above, no conversion is possible
4720   return Result;
4721 }
4722 
4723 /// TryCopyInitialization - Try to copy-initialize a value of type
4724 /// ToType from the expression From. Return the implicit conversion
4725 /// sequence required to pass this argument, which may be a bad
4726 /// conversion sequence (meaning that the argument cannot be passed to
4727 /// a parameter of this type). If @p SuppressUserConversions, then we
4728 /// do not permit any user-defined conversion sequences.
4729 static ImplicitConversionSequence
4730 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4731                       bool SuppressUserConversions,
4732                       bool InOverloadResolution,
4733                       bool AllowObjCWritebackConversion,
4734                       bool AllowExplicit) {
4735   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4736     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4737                              InOverloadResolution,AllowObjCWritebackConversion);
4738 
4739   if (ToType->isReferenceType())
4740     return TryReferenceInit(S, From, ToType,
4741                             /*FIXME:*/From->getLocStart(),
4742                             SuppressUserConversions,
4743                             AllowExplicit);
4744 
4745   return TryImplicitConversion(S, From, ToType,
4746                                SuppressUserConversions,
4747                                /*AllowExplicit=*/false,
4748                                InOverloadResolution,
4749                                /*CStyle=*/false,
4750                                AllowObjCWritebackConversion,
4751                                /*AllowObjCConversionOnExplicit=*/false);
4752 }
4753 
4754 static bool TryCopyInitialization(const CanQualType FromQTy,
4755                                   const CanQualType ToQTy,
4756                                   Sema &S,
4757                                   SourceLocation Loc,
4758                                   ExprValueKind FromVK) {
4759   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4760   ImplicitConversionSequence ICS =
4761     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4762 
4763   return !ICS.isBad();
4764 }
4765 
4766 /// TryObjectArgumentInitialization - Try to initialize the object
4767 /// parameter of the given member function (@c Method) from the
4768 /// expression @p From.
4769 static ImplicitConversionSequence
4770 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4771                                 Expr::Classification FromClassification,
4772                                 CXXMethodDecl *Method,
4773                                 CXXRecordDecl *ActingContext) {
4774   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4775   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4776   //                 const volatile object.
4777   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4778     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4779   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4780 
4781   // Set up the conversion sequence as a "bad" conversion, to allow us
4782   // to exit early.
4783   ImplicitConversionSequence ICS;
4784 
4785   // We need to have an object of class type.
4786   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4787     FromType = PT->getPointeeType();
4788 
4789     // When we had a pointer, it's implicitly dereferenced, so we
4790     // better have an lvalue.
4791     assert(FromClassification.isLValue());
4792   }
4793 
4794   assert(FromType->isRecordType());
4795 
4796   // C++0x [over.match.funcs]p4:
4797   //   For non-static member functions, the type of the implicit object
4798   //   parameter is
4799   //
4800   //     - "lvalue reference to cv X" for functions declared without a
4801   //        ref-qualifier or with the & ref-qualifier
4802   //     - "rvalue reference to cv X" for functions declared with the &&
4803   //        ref-qualifier
4804   //
4805   // where X is the class of which the function is a member and cv is the
4806   // cv-qualification on the member function declaration.
4807   //
4808   // However, when finding an implicit conversion sequence for the argument, we
4809   // are not allowed to create temporaries or perform user-defined conversions
4810   // (C++ [over.match.funcs]p5). We perform a simplified version of
4811   // reference binding here, that allows class rvalues to bind to
4812   // non-constant references.
4813 
4814   // First check the qualifiers.
4815   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4816   if (ImplicitParamType.getCVRQualifiers()
4817                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4818       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4819     ICS.setBad(BadConversionSequence::bad_qualifiers,
4820                FromType, ImplicitParamType);
4821     return ICS;
4822   }
4823 
4824   // Check that we have either the same type or a derived type. It
4825   // affects the conversion rank.
4826   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4827   ImplicitConversionKind SecondKind;
4828   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4829     SecondKind = ICK_Identity;
4830   } else if (S.IsDerivedFrom(FromType, ClassType))
4831     SecondKind = ICK_Derived_To_Base;
4832   else {
4833     ICS.setBad(BadConversionSequence::unrelated_class,
4834                FromType, ImplicitParamType);
4835     return ICS;
4836   }
4837 
4838   // Check the ref-qualifier.
4839   switch (Method->getRefQualifier()) {
4840   case RQ_None:
4841     // Do nothing; we don't care about lvalueness or rvalueness.
4842     break;
4843 
4844   case RQ_LValue:
4845     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4846       // non-const lvalue reference cannot bind to an rvalue
4847       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4848                  ImplicitParamType);
4849       return ICS;
4850     }
4851     break;
4852 
4853   case RQ_RValue:
4854     if (!FromClassification.isRValue()) {
4855       // rvalue reference cannot bind to an lvalue
4856       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4857                  ImplicitParamType);
4858       return ICS;
4859     }
4860     break;
4861   }
4862 
4863   // Success. Mark this as a reference binding.
4864   ICS.setStandard();
4865   ICS.Standard.setAsIdentityConversion();
4866   ICS.Standard.Second = SecondKind;
4867   ICS.Standard.setFromType(FromType);
4868   ICS.Standard.setAllToTypes(ImplicitParamType);
4869   ICS.Standard.ReferenceBinding = true;
4870   ICS.Standard.DirectBinding = true;
4871   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4872   ICS.Standard.BindsToFunctionLvalue = false;
4873   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4874   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4875     = (Method->getRefQualifier() == RQ_None);
4876   return ICS;
4877 }
4878 
4879 /// PerformObjectArgumentInitialization - Perform initialization of
4880 /// the implicit object parameter for the given Method with the given
4881 /// expression.
4882 ExprResult
4883 Sema::PerformObjectArgumentInitialization(Expr *From,
4884                                           NestedNameSpecifier *Qualifier,
4885                                           NamedDecl *FoundDecl,
4886                                           CXXMethodDecl *Method) {
4887   QualType FromRecordType, DestType;
4888   QualType ImplicitParamRecordType  =
4889     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4890 
4891   Expr::Classification FromClassification;
4892   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4893     FromRecordType = PT->getPointeeType();
4894     DestType = Method->getThisType(Context);
4895     FromClassification = Expr::Classification::makeSimpleLValue();
4896   } else {
4897     FromRecordType = From->getType();
4898     DestType = ImplicitParamRecordType;
4899     FromClassification = From->Classify(Context);
4900   }
4901 
4902   // Note that we always use the true parent context when performing
4903   // the actual argument initialization.
4904   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4905       *this, From->getType(), FromClassification, Method, Method->getParent());
4906   if (ICS.isBad()) {
4907     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4908       Qualifiers FromQs = FromRecordType.getQualifiers();
4909       Qualifiers ToQs = DestType.getQualifiers();
4910       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4911       if (CVR) {
4912         Diag(From->getLocStart(),
4913              diag::err_member_function_call_bad_cvr)
4914           << Method->getDeclName() << FromRecordType << (CVR - 1)
4915           << From->getSourceRange();
4916         Diag(Method->getLocation(), diag::note_previous_decl)
4917           << Method->getDeclName();
4918         return ExprError();
4919       }
4920     }
4921 
4922     return Diag(From->getLocStart(),
4923                 diag::err_implicit_object_parameter_init)
4924        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4925   }
4926 
4927   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4928     ExprResult FromRes =
4929       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4930     if (FromRes.isInvalid())
4931       return ExprError();
4932     From = FromRes.get();
4933   }
4934 
4935   if (!Context.hasSameType(From->getType(), DestType))
4936     From = ImpCastExprToType(From, DestType, CK_NoOp,
4937                              From->getValueKind()).get();
4938   return From;
4939 }
4940 
4941 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4942 /// expression From to bool (C++0x [conv]p3).
4943 static ImplicitConversionSequence
4944 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4945   return TryImplicitConversion(S, From, S.Context.BoolTy,
4946                                /*SuppressUserConversions=*/false,
4947                                /*AllowExplicit=*/true,
4948                                /*InOverloadResolution=*/false,
4949                                /*CStyle=*/false,
4950                                /*AllowObjCWritebackConversion=*/false,
4951                                /*AllowObjCConversionOnExplicit=*/false);
4952 }
4953 
4954 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4955 /// of the expression From to bool (C++0x [conv]p3).
4956 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4957   if (checkPlaceholderForOverload(*this, From))
4958     return ExprError();
4959 
4960   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4961   if (!ICS.isBad())
4962     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4963 
4964   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4965     return Diag(From->getLocStart(),
4966                 diag::err_typecheck_bool_condition)
4967                   << From->getType() << From->getSourceRange();
4968   return ExprError();
4969 }
4970 
4971 /// Check that the specified conversion is permitted in a converted constant
4972 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4973 /// is acceptable.
4974 static bool CheckConvertedConstantConversions(Sema &S,
4975                                               StandardConversionSequence &SCS) {
4976   // Since we know that the target type is an integral or unscoped enumeration
4977   // type, most conversion kinds are impossible. All possible First and Third
4978   // conversions are fine.
4979   switch (SCS.Second) {
4980   case ICK_Identity:
4981   case ICK_NoReturn_Adjustment:
4982   case ICK_Integral_Promotion:
4983   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
4984     return true;
4985 
4986   case ICK_Boolean_Conversion:
4987     // Conversion from an integral or unscoped enumeration type to bool is
4988     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4989     // conversion, so we allow it in a converted constant expression.
4990     //
4991     // FIXME: Per core issue 1407, we should not allow this, but that breaks
4992     // a lot of popular code. We should at least add a warning for this
4993     // (non-conforming) extension.
4994     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4995            SCS.getToType(2)->isBooleanType();
4996 
4997   case ICK_Pointer_Conversion:
4998   case ICK_Pointer_Member:
4999     // C++1z: null pointer conversions and null member pointer conversions are
5000     // only permitted if the source type is std::nullptr_t.
5001     return SCS.getFromType()->isNullPtrType();
5002 
5003   case ICK_Floating_Promotion:
5004   case ICK_Complex_Promotion:
5005   case ICK_Floating_Conversion:
5006   case ICK_Complex_Conversion:
5007   case ICK_Floating_Integral:
5008   case ICK_Compatible_Conversion:
5009   case ICK_Derived_To_Base:
5010   case ICK_Vector_Conversion:
5011   case ICK_Vector_Splat:
5012   case ICK_Complex_Real:
5013   case ICK_Block_Pointer_Conversion:
5014   case ICK_TransparentUnionConversion:
5015   case ICK_Writeback_Conversion:
5016   case ICK_Zero_Event_Conversion:
5017   case ICK_C_Only_Conversion:
5018     return false;
5019 
5020   case ICK_Lvalue_To_Rvalue:
5021   case ICK_Array_To_Pointer:
5022   case ICK_Function_To_Pointer:
5023     llvm_unreachable("found a first conversion kind in Second");
5024 
5025   case ICK_Qualification:
5026     llvm_unreachable("found a third conversion kind in Second");
5027 
5028   case ICK_Num_Conversion_Kinds:
5029     break;
5030   }
5031 
5032   llvm_unreachable("unknown conversion kind");
5033 }
5034 
5035 /// CheckConvertedConstantExpression - Check that the expression From is a
5036 /// converted constant expression of type T, perform the conversion and produce
5037 /// the converted expression, per C++11 [expr.const]p3.
5038 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5039                                                    QualType T, APValue &Value,
5040                                                    Sema::CCEKind CCE,
5041                                                    bool RequireInt) {
5042   assert(S.getLangOpts().CPlusPlus11 &&
5043          "converted constant expression outside C++11");
5044 
5045   if (checkPlaceholderForOverload(S, From))
5046     return ExprError();
5047 
5048   // C++1z [expr.const]p3:
5049   //  A converted constant expression of type T is an expression,
5050   //  implicitly converted to type T, where the converted
5051   //  expression is a constant expression and the implicit conversion
5052   //  sequence contains only [... list of conversions ...].
5053   ImplicitConversionSequence ICS =
5054     TryCopyInitialization(S, From, T,
5055                           /*SuppressUserConversions=*/false,
5056                           /*InOverloadResolution=*/false,
5057                           /*AllowObjcWritebackConversion=*/false,
5058                           /*AllowExplicit=*/false);
5059   StandardConversionSequence *SCS = nullptr;
5060   switch (ICS.getKind()) {
5061   case ImplicitConversionSequence::StandardConversion:
5062     SCS = &ICS.Standard;
5063     break;
5064   case ImplicitConversionSequence::UserDefinedConversion:
5065     // We are converting to a non-class type, so the Before sequence
5066     // must be trivial.
5067     SCS = &ICS.UserDefined.After;
5068     break;
5069   case ImplicitConversionSequence::AmbiguousConversion:
5070   case ImplicitConversionSequence::BadConversion:
5071     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5072       return S.Diag(From->getLocStart(),
5073                     diag::err_typecheck_converted_constant_expression)
5074                 << From->getType() << From->getSourceRange() << T;
5075     return ExprError();
5076 
5077   case ImplicitConversionSequence::EllipsisConversion:
5078     llvm_unreachable("ellipsis conversion in converted constant expression");
5079   }
5080 
5081   // Check that we would only use permitted conversions.
5082   if (!CheckConvertedConstantConversions(S, *SCS)) {
5083     return S.Diag(From->getLocStart(),
5084                   diag::err_typecheck_converted_constant_expression_disallowed)
5085              << From->getType() << From->getSourceRange() << T;
5086   }
5087   // [...] and where the reference binding (if any) binds directly.
5088   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5089     return S.Diag(From->getLocStart(),
5090                   diag::err_typecheck_converted_constant_expression_indirect)
5091              << From->getType() << From->getSourceRange() << T;
5092   }
5093 
5094   ExprResult Result =
5095       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5096   if (Result.isInvalid())
5097     return Result;
5098 
5099   // Check for a narrowing implicit conversion.
5100   APValue PreNarrowingValue;
5101   QualType PreNarrowingType;
5102   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5103                                 PreNarrowingType)) {
5104   case NK_Variable_Narrowing:
5105     // Implicit conversion to a narrower type, and the value is not a constant
5106     // expression. We'll diagnose this in a moment.
5107   case NK_Not_Narrowing:
5108     break;
5109 
5110   case NK_Constant_Narrowing:
5111     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5112       << CCE << /*Constant*/1
5113       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5114     break;
5115 
5116   case NK_Type_Narrowing:
5117     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5118       << CCE << /*Constant*/0 << From->getType() << T;
5119     break;
5120   }
5121 
5122   // Check the expression is a constant expression.
5123   SmallVector<PartialDiagnosticAt, 8> Notes;
5124   Expr::EvalResult Eval;
5125   Eval.Diag = &Notes;
5126 
5127   if ((T->isReferenceType()
5128            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5129            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5130       (RequireInt && !Eval.Val.isInt())) {
5131     // The expression can't be folded, so we can't keep it at this position in
5132     // the AST.
5133     Result = ExprError();
5134   } else {
5135     Value = Eval.Val;
5136 
5137     if (Notes.empty()) {
5138       // It's a constant expression.
5139       return Result;
5140     }
5141   }
5142 
5143   // It's not a constant expression. Produce an appropriate diagnostic.
5144   if (Notes.size() == 1 &&
5145       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5146     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5147   else {
5148     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5149       << CCE << From->getSourceRange();
5150     for (unsigned I = 0; I < Notes.size(); ++I)
5151       S.Diag(Notes[I].first, Notes[I].second);
5152   }
5153   return ExprError();
5154 }
5155 
5156 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5157                                                   APValue &Value, CCEKind CCE) {
5158   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5159 }
5160 
5161 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5162                                                   llvm::APSInt &Value,
5163                                                   CCEKind CCE) {
5164   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5165 
5166   APValue V;
5167   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5168   if (!R.isInvalid())
5169     Value = V.getInt();
5170   return R;
5171 }
5172 
5173 
5174 /// dropPointerConversions - If the given standard conversion sequence
5175 /// involves any pointer conversions, remove them.  This may change
5176 /// the result type of the conversion sequence.
5177 static void dropPointerConversion(StandardConversionSequence &SCS) {
5178   if (SCS.Second == ICK_Pointer_Conversion) {
5179     SCS.Second = ICK_Identity;
5180     SCS.Third = ICK_Identity;
5181     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5182   }
5183 }
5184 
5185 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5186 /// convert the expression From to an Objective-C pointer type.
5187 static ImplicitConversionSequence
5188 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5189   // Do an implicit conversion to 'id'.
5190   QualType Ty = S.Context.getObjCIdType();
5191   ImplicitConversionSequence ICS
5192     = TryImplicitConversion(S, From, Ty,
5193                             // FIXME: Are these flags correct?
5194                             /*SuppressUserConversions=*/false,
5195                             /*AllowExplicit=*/true,
5196                             /*InOverloadResolution=*/false,
5197                             /*CStyle=*/false,
5198                             /*AllowObjCWritebackConversion=*/false,
5199                             /*AllowObjCConversionOnExplicit=*/true);
5200 
5201   // Strip off any final conversions to 'id'.
5202   switch (ICS.getKind()) {
5203   case ImplicitConversionSequence::BadConversion:
5204   case ImplicitConversionSequence::AmbiguousConversion:
5205   case ImplicitConversionSequence::EllipsisConversion:
5206     break;
5207 
5208   case ImplicitConversionSequence::UserDefinedConversion:
5209     dropPointerConversion(ICS.UserDefined.After);
5210     break;
5211 
5212   case ImplicitConversionSequence::StandardConversion:
5213     dropPointerConversion(ICS.Standard);
5214     break;
5215   }
5216 
5217   return ICS;
5218 }
5219 
5220 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5221 /// conversion of the expression From to an Objective-C pointer type.
5222 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5223   if (checkPlaceholderForOverload(*this, From))
5224     return ExprError();
5225 
5226   QualType Ty = Context.getObjCIdType();
5227   ImplicitConversionSequence ICS =
5228     TryContextuallyConvertToObjCPointer(*this, From);
5229   if (!ICS.isBad())
5230     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5231   return ExprError();
5232 }
5233 
5234 /// Determine whether the provided type is an integral type, or an enumeration
5235 /// type of a permitted flavor.
5236 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5237   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5238                                  : T->isIntegralOrUnscopedEnumerationType();
5239 }
5240 
5241 static ExprResult
5242 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5243                             Sema::ContextualImplicitConverter &Converter,
5244                             QualType T, UnresolvedSetImpl &ViableConversions) {
5245 
5246   if (Converter.Suppress)
5247     return ExprError();
5248 
5249   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5250   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5251     CXXConversionDecl *Conv =
5252         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5253     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5254     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5255   }
5256   return From;
5257 }
5258 
5259 static bool
5260 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5261                            Sema::ContextualImplicitConverter &Converter,
5262                            QualType T, bool HadMultipleCandidates,
5263                            UnresolvedSetImpl &ExplicitConversions) {
5264   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5265     DeclAccessPair Found = ExplicitConversions[0];
5266     CXXConversionDecl *Conversion =
5267         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5268 
5269     // The user probably meant to invoke the given explicit
5270     // conversion; use it.
5271     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5272     std::string TypeStr;
5273     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5274 
5275     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5276         << FixItHint::CreateInsertion(From->getLocStart(),
5277                                       "static_cast<" + TypeStr + ">(")
5278         << FixItHint::CreateInsertion(
5279                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5280     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5281 
5282     // If we aren't in a SFINAE context, build a call to the
5283     // explicit conversion function.
5284     if (SemaRef.isSFINAEContext())
5285       return true;
5286 
5287     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5288     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5289                                                        HadMultipleCandidates);
5290     if (Result.isInvalid())
5291       return true;
5292     // Record usage of conversion in an implicit cast.
5293     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5294                                     CK_UserDefinedConversion, Result.get(),
5295                                     nullptr, Result.get()->getValueKind());
5296   }
5297   return false;
5298 }
5299 
5300 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5301                              Sema::ContextualImplicitConverter &Converter,
5302                              QualType T, bool HadMultipleCandidates,
5303                              DeclAccessPair &Found) {
5304   CXXConversionDecl *Conversion =
5305       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5306   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5307 
5308   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5309   if (!Converter.SuppressConversion) {
5310     if (SemaRef.isSFINAEContext())
5311       return true;
5312 
5313     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5314         << From->getSourceRange();
5315   }
5316 
5317   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5318                                                      HadMultipleCandidates);
5319   if (Result.isInvalid())
5320     return true;
5321   // Record usage of conversion in an implicit cast.
5322   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5323                                   CK_UserDefinedConversion, Result.get(),
5324                                   nullptr, Result.get()->getValueKind());
5325   return false;
5326 }
5327 
5328 static ExprResult finishContextualImplicitConversion(
5329     Sema &SemaRef, SourceLocation Loc, Expr *From,
5330     Sema::ContextualImplicitConverter &Converter) {
5331   if (!Converter.match(From->getType()) && !Converter.Suppress)
5332     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5333         << From->getSourceRange();
5334 
5335   return SemaRef.DefaultLvalueConversion(From);
5336 }
5337 
5338 static void
5339 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5340                                   UnresolvedSetImpl &ViableConversions,
5341                                   OverloadCandidateSet &CandidateSet) {
5342   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5343     DeclAccessPair FoundDecl = ViableConversions[I];
5344     NamedDecl *D = FoundDecl.getDecl();
5345     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5346     if (isa<UsingShadowDecl>(D))
5347       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5348 
5349     CXXConversionDecl *Conv;
5350     FunctionTemplateDecl *ConvTemplate;
5351     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5352       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5353     else
5354       Conv = cast<CXXConversionDecl>(D);
5355 
5356     if (ConvTemplate)
5357       SemaRef.AddTemplateConversionCandidate(
5358         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5359         /*AllowObjCConversionOnExplicit=*/false);
5360     else
5361       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5362                                      ToType, CandidateSet,
5363                                      /*AllowObjCConversionOnExplicit=*/false);
5364   }
5365 }
5366 
5367 /// \brief Attempt to convert the given expression to a type which is accepted
5368 /// by the given converter.
5369 ///
5370 /// This routine will attempt to convert an expression of class type to a
5371 /// type accepted by the specified converter. In C++11 and before, the class
5372 /// must have a single non-explicit conversion function converting to a matching
5373 /// type. In C++1y, there can be multiple such conversion functions, but only
5374 /// one target type.
5375 ///
5376 /// \param Loc The source location of the construct that requires the
5377 /// conversion.
5378 ///
5379 /// \param From The expression we're converting from.
5380 ///
5381 /// \param Converter Used to control and diagnose the conversion process.
5382 ///
5383 /// \returns The expression, converted to an integral or enumeration type if
5384 /// successful.
5385 ExprResult Sema::PerformContextualImplicitConversion(
5386     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5387   // We can't perform any more checking for type-dependent expressions.
5388   if (From->isTypeDependent())
5389     return From;
5390 
5391   // Process placeholders immediately.
5392   if (From->hasPlaceholderType()) {
5393     ExprResult result = CheckPlaceholderExpr(From);
5394     if (result.isInvalid())
5395       return result;
5396     From = result.get();
5397   }
5398 
5399   // If the expression already has a matching type, we're golden.
5400   QualType T = From->getType();
5401   if (Converter.match(T))
5402     return DefaultLvalueConversion(From);
5403 
5404   // FIXME: Check for missing '()' if T is a function type?
5405 
5406   // We can only perform contextual implicit conversions on objects of class
5407   // type.
5408   const RecordType *RecordTy = T->getAs<RecordType>();
5409   if (!RecordTy || !getLangOpts().CPlusPlus) {
5410     if (!Converter.Suppress)
5411       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5412     return From;
5413   }
5414 
5415   // We must have a complete class type.
5416   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5417     ContextualImplicitConverter &Converter;
5418     Expr *From;
5419 
5420     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5421         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5422 
5423     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5424       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5425     }
5426   } IncompleteDiagnoser(Converter, From);
5427 
5428   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5429     return From;
5430 
5431   // Look for a conversion to an integral or enumeration type.
5432   UnresolvedSet<4>
5433       ViableConversions; // These are *potentially* viable in C++1y.
5434   UnresolvedSet<4> ExplicitConversions;
5435   const auto &Conversions =
5436       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5437 
5438   bool HadMultipleCandidates =
5439       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5440 
5441   // To check that there is only one target type, in C++1y:
5442   QualType ToType;
5443   bool HasUniqueTargetType = true;
5444 
5445   // Collect explicit or viable (potentially in C++1y) conversions.
5446   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5447     NamedDecl *D = (*I)->getUnderlyingDecl();
5448     CXXConversionDecl *Conversion;
5449     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5450     if (ConvTemplate) {
5451       if (getLangOpts().CPlusPlus14)
5452         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5453       else
5454         continue; // C++11 does not consider conversion operator templates(?).
5455     } else
5456       Conversion = cast<CXXConversionDecl>(D);
5457 
5458     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5459            "Conversion operator templates are considered potentially "
5460            "viable in C++1y");
5461 
5462     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5463     if (Converter.match(CurToType) || ConvTemplate) {
5464 
5465       if (Conversion->isExplicit()) {
5466         // FIXME: For C++1y, do we need this restriction?
5467         // cf. diagnoseNoViableConversion()
5468         if (!ConvTemplate)
5469           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5470       } else {
5471         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5472           if (ToType.isNull())
5473             ToType = CurToType.getUnqualifiedType();
5474           else if (HasUniqueTargetType &&
5475                    (CurToType.getUnqualifiedType() != ToType))
5476             HasUniqueTargetType = false;
5477         }
5478         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5479       }
5480     }
5481   }
5482 
5483   if (getLangOpts().CPlusPlus14) {
5484     // C++1y [conv]p6:
5485     // ... An expression e of class type E appearing in such a context
5486     // is said to be contextually implicitly converted to a specified
5487     // type T and is well-formed if and only if e can be implicitly
5488     // converted to a type T that is determined as follows: E is searched
5489     // for conversion functions whose return type is cv T or reference to
5490     // cv T such that T is allowed by the context. There shall be
5491     // exactly one such T.
5492 
5493     // If no unique T is found:
5494     if (ToType.isNull()) {
5495       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5496                                      HadMultipleCandidates,
5497                                      ExplicitConversions))
5498         return ExprError();
5499       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5500     }
5501 
5502     // If more than one unique Ts are found:
5503     if (!HasUniqueTargetType)
5504       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5505                                          ViableConversions);
5506 
5507     // If one unique T is found:
5508     // First, build a candidate set from the previously recorded
5509     // potentially viable conversions.
5510     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5511     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5512                                       CandidateSet);
5513 
5514     // Then, perform overload resolution over the candidate set.
5515     OverloadCandidateSet::iterator Best;
5516     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5517     case OR_Success: {
5518       // Apply this conversion.
5519       DeclAccessPair Found =
5520           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5521       if (recordConversion(*this, Loc, From, Converter, T,
5522                            HadMultipleCandidates, Found))
5523         return ExprError();
5524       break;
5525     }
5526     case OR_Ambiguous:
5527       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5528                                          ViableConversions);
5529     case OR_No_Viable_Function:
5530       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5531                                      HadMultipleCandidates,
5532                                      ExplicitConversions))
5533         return ExprError();
5534     // fall through 'OR_Deleted' case.
5535     case OR_Deleted:
5536       // We'll complain below about a non-integral condition type.
5537       break;
5538     }
5539   } else {
5540     switch (ViableConversions.size()) {
5541     case 0: {
5542       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5543                                      HadMultipleCandidates,
5544                                      ExplicitConversions))
5545         return ExprError();
5546 
5547       // We'll complain below about a non-integral condition type.
5548       break;
5549     }
5550     case 1: {
5551       // Apply this conversion.
5552       DeclAccessPair Found = ViableConversions[0];
5553       if (recordConversion(*this, Loc, From, Converter, T,
5554                            HadMultipleCandidates, Found))
5555         return ExprError();
5556       break;
5557     }
5558     default:
5559       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5560                                          ViableConversions);
5561     }
5562   }
5563 
5564   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5565 }
5566 
5567 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5568 /// an acceptable non-member overloaded operator for a call whose
5569 /// arguments have types T1 (and, if non-empty, T2). This routine
5570 /// implements the check in C++ [over.match.oper]p3b2 concerning
5571 /// enumeration types.
5572 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5573                                                    FunctionDecl *Fn,
5574                                                    ArrayRef<Expr *> Args) {
5575   QualType T1 = Args[0]->getType();
5576   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5577 
5578   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5579     return true;
5580 
5581   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5582     return true;
5583 
5584   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5585   if (Proto->getNumParams() < 1)
5586     return false;
5587 
5588   if (T1->isEnumeralType()) {
5589     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5590     if (Context.hasSameUnqualifiedType(T1, ArgType))
5591       return true;
5592   }
5593 
5594   if (Proto->getNumParams() < 2)
5595     return false;
5596 
5597   if (!T2.isNull() && T2->isEnumeralType()) {
5598     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5599     if (Context.hasSameUnqualifiedType(T2, ArgType))
5600       return true;
5601   }
5602 
5603   return false;
5604 }
5605 
5606 /// AddOverloadCandidate - Adds the given function to the set of
5607 /// candidate functions, using the given function call arguments.  If
5608 /// @p SuppressUserConversions, then don't allow user-defined
5609 /// conversions via constructors or conversion operators.
5610 ///
5611 /// \param PartialOverloading true if we are performing "partial" overloading
5612 /// based on an incomplete set of function arguments. This feature is used by
5613 /// code completion.
5614 void
5615 Sema::AddOverloadCandidate(FunctionDecl *Function,
5616                            DeclAccessPair FoundDecl,
5617                            ArrayRef<Expr *> Args,
5618                            OverloadCandidateSet &CandidateSet,
5619                            bool SuppressUserConversions,
5620                            bool PartialOverloading,
5621                            bool AllowExplicit) {
5622   const FunctionProtoType *Proto
5623     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5624   assert(Proto && "Functions without a prototype cannot be overloaded");
5625   assert(!Function->getDescribedFunctionTemplate() &&
5626          "Use AddTemplateOverloadCandidate for function templates");
5627 
5628   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5629     if (!isa<CXXConstructorDecl>(Method)) {
5630       // If we get here, it's because we're calling a member function
5631       // that is named without a member access expression (e.g.,
5632       // "this->f") that was either written explicitly or created
5633       // implicitly. This can happen with a qualified call to a member
5634       // function, e.g., X::f(). We use an empty type for the implied
5635       // object argument (C++ [over.call.func]p3), and the acting context
5636       // is irrelevant.
5637       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5638                          QualType(), Expr::Classification::makeSimpleLValue(),
5639                          Args, CandidateSet, SuppressUserConversions,
5640                          PartialOverloading);
5641       return;
5642     }
5643     // We treat a constructor like a non-member function, since its object
5644     // argument doesn't participate in overload resolution.
5645   }
5646 
5647   if (!CandidateSet.isNewCandidate(Function))
5648     return;
5649 
5650   // C++ [over.match.oper]p3:
5651   //   if no operand has a class type, only those non-member functions in the
5652   //   lookup set that have a first parameter of type T1 or "reference to
5653   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5654   //   is a right operand) a second parameter of type T2 or "reference to
5655   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5656   //   candidate functions.
5657   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5658       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5659     return;
5660 
5661   // C++11 [class.copy]p11: [DR1402]
5662   //   A defaulted move constructor that is defined as deleted is ignored by
5663   //   overload resolution.
5664   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5665   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5666       Constructor->isMoveConstructor())
5667     return;
5668 
5669   // Overload resolution is always an unevaluated context.
5670   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5671 
5672   // Add this candidate
5673   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5674   Candidate.FoundDecl = FoundDecl;
5675   Candidate.Function = Function;
5676   Candidate.Viable = true;
5677   Candidate.IsSurrogate = false;
5678   Candidate.IgnoreObjectArgument = false;
5679   Candidate.ExplicitCallArguments = Args.size();
5680 
5681   if (Constructor) {
5682     // C++ [class.copy]p3:
5683     //   A member function template is never instantiated to perform the copy
5684     //   of a class object to an object of its class type.
5685     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5686     if (Args.size() == 1 &&
5687         Constructor->isSpecializationCopyingObject() &&
5688         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5689          IsDerivedFrom(Args[0]->getType(), ClassType))) {
5690       Candidate.Viable = false;
5691       Candidate.FailureKind = ovl_fail_illegal_constructor;
5692       return;
5693     }
5694   }
5695 
5696   unsigned NumParams = Proto->getNumParams();
5697 
5698   // (C++ 13.3.2p2): A candidate function having fewer than m
5699   // parameters is viable only if it has an ellipsis in its parameter
5700   // list (8.3.5).
5701   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5702       !Proto->isVariadic()) {
5703     Candidate.Viable = false;
5704     Candidate.FailureKind = ovl_fail_too_many_arguments;
5705     return;
5706   }
5707 
5708   // (C++ 13.3.2p2): A candidate function having more than m parameters
5709   // is viable only if the (m+1)st parameter has a default argument
5710   // (8.3.6). For the purposes of overload resolution, the
5711   // parameter list is truncated on the right, so that there are
5712   // exactly m parameters.
5713   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5714   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5715     // Not enough arguments.
5716     Candidate.Viable = false;
5717     Candidate.FailureKind = ovl_fail_too_few_arguments;
5718     return;
5719   }
5720 
5721   // (CUDA B.1): Check for invalid calls between targets.
5722   if (getLangOpts().CUDA)
5723     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5724       // Skip the check for callers that are implicit members, because in this
5725       // case we may not yet know what the member's target is; the target is
5726       // inferred for the member automatically, based on the bases and fields of
5727       // the class.
5728       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5729         Candidate.Viable = false;
5730         Candidate.FailureKind = ovl_fail_bad_target;
5731         return;
5732       }
5733 
5734   // Determine the implicit conversion sequences for each of the
5735   // arguments.
5736   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5737     if (ArgIdx < NumParams) {
5738       // (C++ 13.3.2p3): for F to be a viable function, there shall
5739       // exist for each argument an implicit conversion sequence
5740       // (13.3.3.1) that converts that argument to the corresponding
5741       // parameter of F.
5742       QualType ParamType = Proto->getParamType(ArgIdx);
5743       Candidate.Conversions[ArgIdx]
5744         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5745                                 SuppressUserConversions,
5746                                 /*InOverloadResolution=*/true,
5747                                 /*AllowObjCWritebackConversion=*/
5748                                   getLangOpts().ObjCAutoRefCount,
5749                                 AllowExplicit);
5750       if (Candidate.Conversions[ArgIdx].isBad()) {
5751         Candidate.Viable = false;
5752         Candidate.FailureKind = ovl_fail_bad_conversion;
5753         return;
5754       }
5755     } else {
5756       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5757       // argument for which there is no corresponding parameter is
5758       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5759       Candidate.Conversions[ArgIdx].setEllipsis();
5760     }
5761   }
5762 
5763   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5764     Candidate.Viable = false;
5765     Candidate.FailureKind = ovl_fail_enable_if;
5766     Candidate.DeductionFailure.Data = FailedAttr;
5767     return;
5768   }
5769 }
5770 
5771 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5772                                        bool IsInstance) {
5773   SmallVector<ObjCMethodDecl*, 4> Methods;
5774   if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5775     return nullptr;
5776 
5777   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5778     bool Match = true;
5779     ObjCMethodDecl *Method = Methods[b];
5780     unsigned NumNamedArgs = Sel.getNumArgs();
5781     // Method might have more arguments than selector indicates. This is due
5782     // to addition of c-style arguments in method.
5783     if (Method->param_size() > NumNamedArgs)
5784       NumNamedArgs = Method->param_size();
5785     if (Args.size() < NumNamedArgs)
5786       continue;
5787 
5788     for (unsigned i = 0; i < NumNamedArgs; i++) {
5789       // We can't do any type-checking on a type-dependent argument.
5790       if (Args[i]->isTypeDependent()) {
5791         Match = false;
5792         break;
5793       }
5794 
5795       ParmVarDecl *param = Method->parameters()[i];
5796       Expr *argExpr = Args[i];
5797       assert(argExpr && "SelectBestMethod(): missing expression");
5798 
5799       // Strip the unbridged-cast placeholder expression off unless it's
5800       // a consumed argument.
5801       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5802           !param->hasAttr<CFConsumedAttr>())
5803         argExpr = stripARCUnbridgedCast(argExpr);
5804 
5805       // If the parameter is __unknown_anytype, move on to the next method.
5806       if (param->getType() == Context.UnknownAnyTy) {
5807         Match = false;
5808         break;
5809       }
5810 
5811       ImplicitConversionSequence ConversionState
5812         = TryCopyInitialization(*this, argExpr, param->getType(),
5813                                 /*SuppressUserConversions*/false,
5814                                 /*InOverloadResolution=*/true,
5815                                 /*AllowObjCWritebackConversion=*/
5816                                 getLangOpts().ObjCAutoRefCount,
5817                                 /*AllowExplicit*/false);
5818         if (ConversionState.isBad()) {
5819           Match = false;
5820           break;
5821         }
5822     }
5823     // Promote additional arguments to variadic methods.
5824     if (Match && Method->isVariadic()) {
5825       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5826         if (Args[i]->isTypeDependent()) {
5827           Match = false;
5828           break;
5829         }
5830         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5831                                                           nullptr);
5832         if (Arg.isInvalid()) {
5833           Match = false;
5834           break;
5835         }
5836       }
5837     } else {
5838       // Check for extra arguments to non-variadic methods.
5839       if (Args.size() != NumNamedArgs)
5840         Match = false;
5841       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5842         // Special case when selectors have no argument. In this case, select
5843         // one with the most general result type of 'id'.
5844         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5845           QualType ReturnT = Methods[b]->getReturnType();
5846           if (ReturnT->isObjCIdType())
5847             return Methods[b];
5848         }
5849       }
5850     }
5851 
5852     if (Match)
5853       return Method;
5854   }
5855   return nullptr;
5856 }
5857 
5858 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5859 
5860 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5861                                   bool MissingImplicitThis) {
5862   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5863   // we need to find the first failing one.
5864   if (!Function->hasAttrs())
5865     return nullptr;
5866   AttrVec Attrs = Function->getAttrs();
5867   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5868                                        IsNotEnableIfAttr);
5869   if (Attrs.begin() == E)
5870     return nullptr;
5871   std::reverse(Attrs.begin(), E);
5872 
5873   SFINAETrap Trap(*this);
5874 
5875   SmallVector<Expr *, 16> ConvertedArgs;
5876   bool InitializationFailed = false;
5877   bool ContainsValueDependentExpr = false;
5878 
5879   // Convert the arguments.
5880   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5881     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5882         !cast<CXXMethodDecl>(Function)->isStatic() &&
5883         !isa<CXXConstructorDecl>(Function)) {
5884       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5885       ExprResult R =
5886         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5887                                             Method, Method);
5888       if (R.isInvalid()) {
5889         InitializationFailed = true;
5890         break;
5891       }
5892       ContainsValueDependentExpr |= R.get()->isValueDependent();
5893       ConvertedArgs.push_back(R.get());
5894     } else {
5895       ExprResult R =
5896         PerformCopyInitialization(InitializedEntity::InitializeParameter(
5897                                                 Context,
5898                                                 Function->getParamDecl(i)),
5899                                   SourceLocation(),
5900                                   Args[i]);
5901       if (R.isInvalid()) {
5902         InitializationFailed = true;
5903         break;
5904       }
5905       ContainsValueDependentExpr |= R.get()->isValueDependent();
5906       ConvertedArgs.push_back(R.get());
5907     }
5908   }
5909 
5910   if (InitializationFailed || Trap.hasErrorOccurred())
5911     return cast<EnableIfAttr>(Attrs[0]);
5912 
5913   // Push default arguments if needed.
5914   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5915     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5916       ParmVarDecl *P = Function->getParamDecl(i);
5917       ExprResult R = PerformCopyInitialization(
5918           InitializedEntity::InitializeParameter(Context,
5919                                                  Function->getParamDecl(i)),
5920           SourceLocation(),
5921           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5922                                            : P->getDefaultArg());
5923       if (R.isInvalid()) {
5924         InitializationFailed = true;
5925         break;
5926       }
5927       ContainsValueDependentExpr |= R.get()->isValueDependent();
5928       ConvertedArgs.push_back(R.get());
5929     }
5930 
5931     if (InitializationFailed || Trap.hasErrorOccurred())
5932       return cast<EnableIfAttr>(Attrs[0]);
5933   }
5934 
5935   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5936     APValue Result;
5937     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5938     if (EIA->getCond()->isValueDependent()) {
5939       // Don't even try now, we'll examine it after instantiation.
5940       continue;
5941     }
5942 
5943     if (!EIA->getCond()->EvaluateWithSubstitution(
5944             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5945       if (!ContainsValueDependentExpr)
5946         return EIA;
5947     } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
5948       return EIA;
5949     }
5950   }
5951   return nullptr;
5952 }
5953 
5954 /// \brief Add all of the function declarations in the given function set to
5955 /// the overload candidate set.
5956 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5957                                  ArrayRef<Expr *> Args,
5958                                  OverloadCandidateSet& CandidateSet,
5959                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5960                                  bool SuppressUserConversions,
5961                                  bool PartialOverloading) {
5962   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5963     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5964     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5965       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5966         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5967                            cast<CXXMethodDecl>(FD)->getParent(),
5968                            Args[0]->getType(), Args[0]->Classify(Context),
5969                            Args.slice(1), CandidateSet,
5970                            SuppressUserConversions, PartialOverloading);
5971       else
5972         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5973                              SuppressUserConversions, PartialOverloading);
5974     } else {
5975       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5976       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5977           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5978         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5979                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5980                                    ExplicitTemplateArgs,
5981                                    Args[0]->getType(),
5982                                    Args[0]->Classify(Context), Args.slice(1),
5983                                    CandidateSet, SuppressUserConversions,
5984                                    PartialOverloading);
5985       else
5986         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5987                                      ExplicitTemplateArgs, Args,
5988                                      CandidateSet, SuppressUserConversions,
5989                                      PartialOverloading);
5990     }
5991   }
5992 }
5993 
5994 /// AddMethodCandidate - Adds a named decl (which is some kind of
5995 /// method) as a method candidate to the given overload set.
5996 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5997                               QualType ObjectType,
5998                               Expr::Classification ObjectClassification,
5999                               ArrayRef<Expr *> Args,
6000                               OverloadCandidateSet& CandidateSet,
6001                               bool SuppressUserConversions) {
6002   NamedDecl *Decl = FoundDecl.getDecl();
6003   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6004 
6005   if (isa<UsingShadowDecl>(Decl))
6006     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6007 
6008   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6009     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6010            "Expected a member function template");
6011     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6012                                /*ExplicitArgs*/ nullptr,
6013                                ObjectType, ObjectClassification,
6014                                Args, CandidateSet,
6015                                SuppressUserConversions);
6016   } else {
6017     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6018                        ObjectType, ObjectClassification,
6019                        Args,
6020                        CandidateSet, SuppressUserConversions);
6021   }
6022 }
6023 
6024 /// AddMethodCandidate - Adds the given C++ member function to the set
6025 /// of candidate functions, using the given function call arguments
6026 /// and the object argument (@c Object). For example, in a call
6027 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6028 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6029 /// allow user-defined conversions via constructors or conversion
6030 /// operators.
6031 void
6032 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6033                          CXXRecordDecl *ActingContext, QualType ObjectType,
6034                          Expr::Classification ObjectClassification,
6035                          ArrayRef<Expr *> Args,
6036                          OverloadCandidateSet &CandidateSet,
6037                          bool SuppressUserConversions,
6038                          bool PartialOverloading) {
6039   const FunctionProtoType *Proto
6040     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6041   assert(Proto && "Methods without a prototype cannot be overloaded");
6042   assert(!isa<CXXConstructorDecl>(Method) &&
6043          "Use AddOverloadCandidate for constructors");
6044 
6045   if (!CandidateSet.isNewCandidate(Method))
6046     return;
6047 
6048   // C++11 [class.copy]p23: [DR1402]
6049   //   A defaulted move assignment operator that is defined as deleted is
6050   //   ignored by overload resolution.
6051   if (Method->isDefaulted() && Method->isDeleted() &&
6052       Method->isMoveAssignmentOperator())
6053     return;
6054 
6055   // Overload resolution is always an unevaluated context.
6056   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6057 
6058   // Add this candidate
6059   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6060   Candidate.FoundDecl = FoundDecl;
6061   Candidate.Function = Method;
6062   Candidate.IsSurrogate = false;
6063   Candidate.IgnoreObjectArgument = false;
6064   Candidate.ExplicitCallArguments = Args.size();
6065 
6066   unsigned NumParams = Proto->getNumParams();
6067 
6068   // (C++ 13.3.2p2): A candidate function having fewer than m
6069   // parameters is viable only if it has an ellipsis in its parameter
6070   // list (8.3.5).
6071   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6072       !Proto->isVariadic()) {
6073     Candidate.Viable = false;
6074     Candidate.FailureKind = ovl_fail_too_many_arguments;
6075     return;
6076   }
6077 
6078   // (C++ 13.3.2p2): A candidate function having more than m parameters
6079   // is viable only if the (m+1)st parameter has a default argument
6080   // (8.3.6). For the purposes of overload resolution, the
6081   // parameter list is truncated on the right, so that there are
6082   // exactly m parameters.
6083   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6084   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6085     // Not enough arguments.
6086     Candidate.Viable = false;
6087     Candidate.FailureKind = ovl_fail_too_few_arguments;
6088     return;
6089   }
6090 
6091   Candidate.Viable = true;
6092 
6093   if (Method->isStatic() || ObjectType.isNull())
6094     // The implicit object argument is ignored.
6095     Candidate.IgnoreObjectArgument = true;
6096   else {
6097     // Determine the implicit conversion sequence for the object
6098     // parameter.
6099     Candidate.Conversions[0]
6100       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6101                                         Method, ActingContext);
6102     if (Candidate.Conversions[0].isBad()) {
6103       Candidate.Viable = false;
6104       Candidate.FailureKind = ovl_fail_bad_conversion;
6105       return;
6106     }
6107   }
6108 
6109   // (CUDA B.1): Check for invalid calls between targets.
6110   if (getLangOpts().CUDA)
6111     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6112       if (CheckCUDATarget(Caller, Method)) {
6113         Candidate.Viable = false;
6114         Candidate.FailureKind = ovl_fail_bad_target;
6115         return;
6116       }
6117 
6118   // Determine the implicit conversion sequences for each of the
6119   // arguments.
6120   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6121     if (ArgIdx < NumParams) {
6122       // (C++ 13.3.2p3): for F to be a viable function, there shall
6123       // exist for each argument an implicit conversion sequence
6124       // (13.3.3.1) that converts that argument to the corresponding
6125       // parameter of F.
6126       QualType ParamType = Proto->getParamType(ArgIdx);
6127       Candidate.Conversions[ArgIdx + 1]
6128         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6129                                 SuppressUserConversions,
6130                                 /*InOverloadResolution=*/true,
6131                                 /*AllowObjCWritebackConversion=*/
6132                                   getLangOpts().ObjCAutoRefCount);
6133       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6134         Candidate.Viable = false;
6135         Candidate.FailureKind = ovl_fail_bad_conversion;
6136         return;
6137       }
6138     } else {
6139       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6140       // argument for which there is no corresponding parameter is
6141       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6142       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6143     }
6144   }
6145 
6146   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6147     Candidate.Viable = false;
6148     Candidate.FailureKind = ovl_fail_enable_if;
6149     Candidate.DeductionFailure.Data = FailedAttr;
6150     return;
6151   }
6152 }
6153 
6154 /// \brief Add a C++ member function template as a candidate to the candidate
6155 /// set, using template argument deduction to produce an appropriate member
6156 /// function template specialization.
6157 void
6158 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6159                                  DeclAccessPair FoundDecl,
6160                                  CXXRecordDecl *ActingContext,
6161                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6162                                  QualType ObjectType,
6163                                  Expr::Classification ObjectClassification,
6164                                  ArrayRef<Expr *> Args,
6165                                  OverloadCandidateSet& CandidateSet,
6166                                  bool SuppressUserConversions,
6167                                  bool PartialOverloading) {
6168   if (!CandidateSet.isNewCandidate(MethodTmpl))
6169     return;
6170 
6171   // C++ [over.match.funcs]p7:
6172   //   In each case where a candidate is a function template, candidate
6173   //   function template specializations are generated using template argument
6174   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6175   //   candidate functions in the usual way.113) A given name can refer to one
6176   //   or more function templates and also to a set of overloaded non-template
6177   //   functions. In such a case, the candidate functions generated from each
6178   //   function template are combined with the set of non-template candidate
6179   //   functions.
6180   TemplateDeductionInfo Info(CandidateSet.getLocation());
6181   FunctionDecl *Specialization = nullptr;
6182   if (TemplateDeductionResult Result
6183       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6184                                 Specialization, Info, PartialOverloading)) {
6185     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6186     Candidate.FoundDecl = FoundDecl;
6187     Candidate.Function = MethodTmpl->getTemplatedDecl();
6188     Candidate.Viable = false;
6189     Candidate.FailureKind = ovl_fail_bad_deduction;
6190     Candidate.IsSurrogate = false;
6191     Candidate.IgnoreObjectArgument = false;
6192     Candidate.ExplicitCallArguments = Args.size();
6193     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6194                                                           Info);
6195     return;
6196   }
6197 
6198   // Add the function template specialization produced by template argument
6199   // deduction as a candidate.
6200   assert(Specialization && "Missing member function template specialization?");
6201   assert(isa<CXXMethodDecl>(Specialization) &&
6202          "Specialization is not a member function?");
6203   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6204                      ActingContext, ObjectType, ObjectClassification, Args,
6205                      CandidateSet, SuppressUserConversions, PartialOverloading);
6206 }
6207 
6208 /// \brief Add a C++ function template specialization as a candidate
6209 /// in the candidate set, using template argument deduction to produce
6210 /// an appropriate function template specialization.
6211 void
6212 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6213                                    DeclAccessPair FoundDecl,
6214                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6215                                    ArrayRef<Expr *> Args,
6216                                    OverloadCandidateSet& CandidateSet,
6217                                    bool SuppressUserConversions,
6218                                    bool PartialOverloading) {
6219   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6220     return;
6221 
6222   // C++ [over.match.funcs]p7:
6223   //   In each case where a candidate is a function template, candidate
6224   //   function template specializations are generated using template argument
6225   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6226   //   candidate functions in the usual way.113) A given name can refer to one
6227   //   or more function templates and also to a set of overloaded non-template
6228   //   functions. In such a case, the candidate functions generated from each
6229   //   function template are combined with the set of non-template candidate
6230   //   functions.
6231   TemplateDeductionInfo Info(CandidateSet.getLocation());
6232   FunctionDecl *Specialization = nullptr;
6233   if (TemplateDeductionResult Result
6234         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6235                                   Specialization, Info, PartialOverloading)) {
6236     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6237     Candidate.FoundDecl = FoundDecl;
6238     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6239     Candidate.Viable = false;
6240     Candidate.FailureKind = ovl_fail_bad_deduction;
6241     Candidate.IsSurrogate = false;
6242     Candidate.IgnoreObjectArgument = false;
6243     Candidate.ExplicitCallArguments = Args.size();
6244     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6245                                                           Info);
6246     return;
6247   }
6248 
6249   // Add the function template specialization produced by template argument
6250   // deduction as a candidate.
6251   assert(Specialization && "Missing function template specialization?");
6252   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6253                        SuppressUserConversions, PartialOverloading);
6254 }
6255 
6256 /// Determine whether this is an allowable conversion from the result
6257 /// of an explicit conversion operator to the expected type, per C++
6258 /// [over.match.conv]p1 and [over.match.ref]p1.
6259 ///
6260 /// \param ConvType The return type of the conversion function.
6261 ///
6262 /// \param ToType The type we are converting to.
6263 ///
6264 /// \param AllowObjCPointerConversion Allow a conversion from one
6265 /// Objective-C pointer to another.
6266 ///
6267 /// \returns true if the conversion is allowable, false otherwise.
6268 static bool isAllowableExplicitConversion(Sema &S,
6269                                           QualType ConvType, QualType ToType,
6270                                           bool AllowObjCPointerConversion) {
6271   QualType ToNonRefType = ToType.getNonReferenceType();
6272 
6273   // Easy case: the types are the same.
6274   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6275     return true;
6276 
6277   // Allow qualification conversions.
6278   bool ObjCLifetimeConversion;
6279   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6280                                   ObjCLifetimeConversion))
6281     return true;
6282 
6283   // If we're not allowed to consider Objective-C pointer conversions,
6284   // we're done.
6285   if (!AllowObjCPointerConversion)
6286     return false;
6287 
6288   // Is this an Objective-C pointer conversion?
6289   bool IncompatibleObjC = false;
6290   QualType ConvertedType;
6291   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6292                                    IncompatibleObjC);
6293 }
6294 
6295 /// AddConversionCandidate - Add a C++ conversion function as a
6296 /// candidate in the candidate set (C++ [over.match.conv],
6297 /// C++ [over.match.copy]). From is the expression we're converting from,
6298 /// and ToType is the type that we're eventually trying to convert to
6299 /// (which may or may not be the same type as the type that the
6300 /// conversion function produces).
6301 void
6302 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6303                              DeclAccessPair FoundDecl,
6304                              CXXRecordDecl *ActingContext,
6305                              Expr *From, QualType ToType,
6306                              OverloadCandidateSet& CandidateSet,
6307                              bool AllowObjCConversionOnExplicit) {
6308   assert(!Conversion->getDescribedFunctionTemplate() &&
6309          "Conversion function templates use AddTemplateConversionCandidate");
6310   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6311   if (!CandidateSet.isNewCandidate(Conversion))
6312     return;
6313 
6314   // If the conversion function has an undeduced return type, trigger its
6315   // deduction now.
6316   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6317     if (DeduceReturnType(Conversion, From->getExprLoc()))
6318       return;
6319     ConvType = Conversion->getConversionType().getNonReferenceType();
6320   }
6321 
6322   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6323   // operator is only a candidate if its return type is the target type or
6324   // can be converted to the target type with a qualification conversion.
6325   if (Conversion->isExplicit() &&
6326       !isAllowableExplicitConversion(*this, ConvType, ToType,
6327                                      AllowObjCConversionOnExplicit))
6328     return;
6329 
6330   // Overload resolution is always an unevaluated context.
6331   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6332 
6333   // Add this candidate
6334   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6335   Candidate.FoundDecl = FoundDecl;
6336   Candidate.Function = Conversion;
6337   Candidate.IsSurrogate = false;
6338   Candidate.IgnoreObjectArgument = false;
6339   Candidate.FinalConversion.setAsIdentityConversion();
6340   Candidate.FinalConversion.setFromType(ConvType);
6341   Candidate.FinalConversion.setAllToTypes(ToType);
6342   Candidate.Viable = true;
6343   Candidate.ExplicitCallArguments = 1;
6344 
6345   // C++ [over.match.funcs]p4:
6346   //   For conversion functions, the function is considered to be a member of
6347   //   the class of the implicit implied object argument for the purpose of
6348   //   defining the type of the implicit object parameter.
6349   //
6350   // Determine the implicit conversion sequence for the implicit
6351   // object parameter.
6352   QualType ImplicitParamType = From->getType();
6353   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6354     ImplicitParamType = FromPtrType->getPointeeType();
6355   CXXRecordDecl *ConversionContext
6356     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6357 
6358   Candidate.Conversions[0]
6359     = TryObjectArgumentInitialization(*this, From->getType(),
6360                                       From->Classify(Context),
6361                                       Conversion, ConversionContext);
6362 
6363   if (Candidate.Conversions[0].isBad()) {
6364     Candidate.Viable = false;
6365     Candidate.FailureKind = ovl_fail_bad_conversion;
6366     return;
6367   }
6368 
6369   // We won't go through a user-defined type conversion function to convert a
6370   // derived to base as such conversions are given Conversion Rank. They only
6371   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6372   QualType FromCanon
6373     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6374   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6375   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6376     Candidate.Viable = false;
6377     Candidate.FailureKind = ovl_fail_trivial_conversion;
6378     return;
6379   }
6380 
6381   // To determine what the conversion from the result of calling the
6382   // conversion function to the type we're eventually trying to
6383   // convert to (ToType), we need to synthesize a call to the
6384   // conversion function and attempt copy initialization from it. This
6385   // makes sure that we get the right semantics with respect to
6386   // lvalues/rvalues and the type. Fortunately, we can allocate this
6387   // call on the stack and we don't need its arguments to be
6388   // well-formed.
6389   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6390                             VK_LValue, From->getLocStart());
6391   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6392                                 Context.getPointerType(Conversion->getType()),
6393                                 CK_FunctionToPointerDecay,
6394                                 &ConversionRef, VK_RValue);
6395 
6396   QualType ConversionType = Conversion->getConversionType();
6397   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6398     Candidate.Viable = false;
6399     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6400     return;
6401   }
6402 
6403   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6404 
6405   // Note that it is safe to allocate CallExpr on the stack here because
6406   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6407   // allocator).
6408   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6409   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6410                 From->getLocStart());
6411   ImplicitConversionSequence ICS =
6412     TryCopyInitialization(*this, &Call, ToType,
6413                           /*SuppressUserConversions=*/true,
6414                           /*InOverloadResolution=*/false,
6415                           /*AllowObjCWritebackConversion=*/false);
6416 
6417   switch (ICS.getKind()) {
6418   case ImplicitConversionSequence::StandardConversion:
6419     Candidate.FinalConversion = ICS.Standard;
6420 
6421     // C++ [over.ics.user]p3:
6422     //   If the user-defined conversion is specified by a specialization of a
6423     //   conversion function template, the second standard conversion sequence
6424     //   shall have exact match rank.
6425     if (Conversion->getPrimaryTemplate() &&
6426         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6427       Candidate.Viable = false;
6428       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6429       return;
6430     }
6431 
6432     // C++0x [dcl.init.ref]p5:
6433     //    In the second case, if the reference is an rvalue reference and
6434     //    the second standard conversion sequence of the user-defined
6435     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6436     //    program is ill-formed.
6437     if (ToType->isRValueReferenceType() &&
6438         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6439       Candidate.Viable = false;
6440       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6441       return;
6442     }
6443     break;
6444 
6445   case ImplicitConversionSequence::BadConversion:
6446     Candidate.Viable = false;
6447     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6448     return;
6449 
6450   default:
6451     llvm_unreachable(
6452            "Can only end up with a standard conversion sequence or failure");
6453   }
6454 
6455   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6456     Candidate.Viable = false;
6457     Candidate.FailureKind = ovl_fail_enable_if;
6458     Candidate.DeductionFailure.Data = FailedAttr;
6459     return;
6460   }
6461 }
6462 
6463 /// \brief Adds a conversion function template specialization
6464 /// candidate to the overload set, using template argument deduction
6465 /// to deduce the template arguments of the conversion function
6466 /// template from the type that we are converting to (C++
6467 /// [temp.deduct.conv]).
6468 void
6469 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6470                                      DeclAccessPair FoundDecl,
6471                                      CXXRecordDecl *ActingDC,
6472                                      Expr *From, QualType ToType,
6473                                      OverloadCandidateSet &CandidateSet,
6474                                      bool AllowObjCConversionOnExplicit) {
6475   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6476          "Only conversion function templates permitted here");
6477 
6478   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6479     return;
6480 
6481   TemplateDeductionInfo Info(CandidateSet.getLocation());
6482   CXXConversionDecl *Specialization = nullptr;
6483   if (TemplateDeductionResult Result
6484         = DeduceTemplateArguments(FunctionTemplate, ToType,
6485                                   Specialization, Info)) {
6486     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6487     Candidate.FoundDecl = FoundDecl;
6488     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6489     Candidate.Viable = false;
6490     Candidate.FailureKind = ovl_fail_bad_deduction;
6491     Candidate.IsSurrogate = false;
6492     Candidate.IgnoreObjectArgument = false;
6493     Candidate.ExplicitCallArguments = 1;
6494     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6495                                                           Info);
6496     return;
6497   }
6498 
6499   // Add the conversion function template specialization produced by
6500   // template argument deduction as a candidate.
6501   assert(Specialization && "Missing function template specialization?");
6502   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6503                          CandidateSet, AllowObjCConversionOnExplicit);
6504 }
6505 
6506 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6507 /// converts the given @c Object to a function pointer via the
6508 /// conversion function @c Conversion, and then attempts to call it
6509 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6510 /// the type of function that we'll eventually be calling.
6511 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6512                                  DeclAccessPair FoundDecl,
6513                                  CXXRecordDecl *ActingContext,
6514                                  const FunctionProtoType *Proto,
6515                                  Expr *Object,
6516                                  ArrayRef<Expr *> Args,
6517                                  OverloadCandidateSet& CandidateSet) {
6518   if (!CandidateSet.isNewCandidate(Conversion))
6519     return;
6520 
6521   // Overload resolution is always an unevaluated context.
6522   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6523 
6524   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6525   Candidate.FoundDecl = FoundDecl;
6526   Candidate.Function = nullptr;
6527   Candidate.Surrogate = Conversion;
6528   Candidate.Viable = true;
6529   Candidate.IsSurrogate = true;
6530   Candidate.IgnoreObjectArgument = false;
6531   Candidate.ExplicitCallArguments = Args.size();
6532 
6533   // Determine the implicit conversion sequence for the implicit
6534   // object parameter.
6535   ImplicitConversionSequence ObjectInit
6536     = TryObjectArgumentInitialization(*this, Object->getType(),
6537                                       Object->Classify(Context),
6538                                       Conversion, ActingContext);
6539   if (ObjectInit.isBad()) {
6540     Candidate.Viable = false;
6541     Candidate.FailureKind = ovl_fail_bad_conversion;
6542     Candidate.Conversions[0] = ObjectInit;
6543     return;
6544   }
6545 
6546   // The first conversion is actually a user-defined conversion whose
6547   // first conversion is ObjectInit's standard conversion (which is
6548   // effectively a reference binding). Record it as such.
6549   Candidate.Conversions[0].setUserDefined();
6550   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6551   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6552   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6553   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6554   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6555   Candidate.Conversions[0].UserDefined.After
6556     = Candidate.Conversions[0].UserDefined.Before;
6557   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6558 
6559   // Find the
6560   unsigned NumParams = Proto->getNumParams();
6561 
6562   // (C++ 13.3.2p2): A candidate function having fewer than m
6563   // parameters is viable only if it has an ellipsis in its parameter
6564   // list (8.3.5).
6565   if (Args.size() > NumParams && !Proto->isVariadic()) {
6566     Candidate.Viable = false;
6567     Candidate.FailureKind = ovl_fail_too_many_arguments;
6568     return;
6569   }
6570 
6571   // Function types don't have any default arguments, so just check if
6572   // we have enough arguments.
6573   if (Args.size() < NumParams) {
6574     // Not enough arguments.
6575     Candidate.Viable = false;
6576     Candidate.FailureKind = ovl_fail_too_few_arguments;
6577     return;
6578   }
6579 
6580   // Determine the implicit conversion sequences for each of the
6581   // arguments.
6582   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6583     if (ArgIdx < NumParams) {
6584       // (C++ 13.3.2p3): for F to be a viable function, there shall
6585       // exist for each argument an implicit conversion sequence
6586       // (13.3.3.1) that converts that argument to the corresponding
6587       // parameter of F.
6588       QualType ParamType = Proto->getParamType(ArgIdx);
6589       Candidate.Conversions[ArgIdx + 1]
6590         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6591                                 /*SuppressUserConversions=*/false,
6592                                 /*InOverloadResolution=*/false,
6593                                 /*AllowObjCWritebackConversion=*/
6594                                   getLangOpts().ObjCAutoRefCount);
6595       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6596         Candidate.Viable = false;
6597         Candidate.FailureKind = ovl_fail_bad_conversion;
6598         return;
6599       }
6600     } else {
6601       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6602       // argument for which there is no corresponding parameter is
6603       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6604       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6605     }
6606   }
6607 
6608   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6609     Candidate.Viable = false;
6610     Candidate.FailureKind = ovl_fail_enable_if;
6611     Candidate.DeductionFailure.Data = FailedAttr;
6612     return;
6613   }
6614 }
6615 
6616 /// \brief Add overload candidates for overloaded operators that are
6617 /// member functions.
6618 ///
6619 /// Add the overloaded operator candidates that are member functions
6620 /// for the operator Op that was used in an operator expression such
6621 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6622 /// CandidateSet will store the added overload candidates. (C++
6623 /// [over.match.oper]).
6624 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6625                                        SourceLocation OpLoc,
6626                                        ArrayRef<Expr *> Args,
6627                                        OverloadCandidateSet& CandidateSet,
6628                                        SourceRange OpRange) {
6629   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6630 
6631   // C++ [over.match.oper]p3:
6632   //   For a unary operator @ with an operand of a type whose
6633   //   cv-unqualified version is T1, and for a binary operator @ with
6634   //   a left operand of a type whose cv-unqualified version is T1 and
6635   //   a right operand of a type whose cv-unqualified version is T2,
6636   //   three sets of candidate functions, designated member
6637   //   candidates, non-member candidates and built-in candidates, are
6638   //   constructed as follows:
6639   QualType T1 = Args[0]->getType();
6640 
6641   //     -- If T1 is a complete class type or a class currently being
6642   //        defined, the set of member candidates is the result of the
6643   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6644   //        the set of member candidates is empty.
6645   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6646     // Complete the type if it can be completed.
6647     RequireCompleteType(OpLoc, T1, 0);
6648     // If the type is neither complete nor being defined, bail out now.
6649     if (!T1Rec->getDecl()->getDefinition())
6650       return;
6651 
6652     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6653     LookupQualifiedName(Operators, T1Rec->getDecl());
6654     Operators.suppressDiagnostics();
6655 
6656     for (LookupResult::iterator Oper = Operators.begin(),
6657                              OperEnd = Operators.end();
6658          Oper != OperEnd;
6659          ++Oper)
6660       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6661                          Args[0]->Classify(Context),
6662                          Args.slice(1),
6663                          CandidateSet,
6664                          /* SuppressUserConversions = */ false);
6665   }
6666 }
6667 
6668 /// AddBuiltinCandidate - Add a candidate for a built-in
6669 /// operator. ResultTy and ParamTys are the result and parameter types
6670 /// of the built-in candidate, respectively. Args and NumArgs are the
6671 /// arguments being passed to the candidate. IsAssignmentOperator
6672 /// should be true when this built-in candidate is an assignment
6673 /// operator. NumContextualBoolArguments is the number of arguments
6674 /// (at the beginning of the argument list) that will be contextually
6675 /// converted to bool.
6676 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6677                                ArrayRef<Expr *> Args,
6678                                OverloadCandidateSet& CandidateSet,
6679                                bool IsAssignmentOperator,
6680                                unsigned NumContextualBoolArguments) {
6681   // Overload resolution is always an unevaluated context.
6682   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6683 
6684   // Add this candidate
6685   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6686   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6687   Candidate.Function = nullptr;
6688   Candidate.IsSurrogate = false;
6689   Candidate.IgnoreObjectArgument = false;
6690   Candidate.BuiltinTypes.ResultTy = ResultTy;
6691   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6692     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6693 
6694   // Determine the implicit conversion sequences for each of the
6695   // arguments.
6696   Candidate.Viable = true;
6697   Candidate.ExplicitCallArguments = Args.size();
6698   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6699     // C++ [over.match.oper]p4:
6700     //   For the built-in assignment operators, conversions of the
6701     //   left operand are restricted as follows:
6702     //     -- no temporaries are introduced to hold the left operand, and
6703     //     -- no user-defined conversions are applied to the left
6704     //        operand to achieve a type match with the left-most
6705     //        parameter of a built-in candidate.
6706     //
6707     // We block these conversions by turning off user-defined
6708     // conversions, since that is the only way that initialization of
6709     // a reference to a non-class type can occur from something that
6710     // is not of the same type.
6711     if (ArgIdx < NumContextualBoolArguments) {
6712       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6713              "Contextual conversion to bool requires bool type");
6714       Candidate.Conversions[ArgIdx]
6715         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6716     } else {
6717       Candidate.Conversions[ArgIdx]
6718         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6719                                 ArgIdx == 0 && IsAssignmentOperator,
6720                                 /*InOverloadResolution=*/false,
6721                                 /*AllowObjCWritebackConversion=*/
6722                                   getLangOpts().ObjCAutoRefCount);
6723     }
6724     if (Candidate.Conversions[ArgIdx].isBad()) {
6725       Candidate.Viable = false;
6726       Candidate.FailureKind = ovl_fail_bad_conversion;
6727       break;
6728     }
6729   }
6730 }
6731 
6732 namespace {
6733 
6734 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6735 /// candidate operator functions for built-in operators (C++
6736 /// [over.built]). The types are separated into pointer types and
6737 /// enumeration types.
6738 class BuiltinCandidateTypeSet  {
6739   /// TypeSet - A set of types.
6740   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6741 
6742   /// PointerTypes - The set of pointer types that will be used in the
6743   /// built-in candidates.
6744   TypeSet PointerTypes;
6745 
6746   /// MemberPointerTypes - The set of member pointer types that will be
6747   /// used in the built-in candidates.
6748   TypeSet MemberPointerTypes;
6749 
6750   /// EnumerationTypes - The set of enumeration types that will be
6751   /// used in the built-in candidates.
6752   TypeSet EnumerationTypes;
6753 
6754   /// \brief The set of vector types that will be used in the built-in
6755   /// candidates.
6756   TypeSet VectorTypes;
6757 
6758   /// \brief A flag indicating non-record types are viable candidates
6759   bool HasNonRecordTypes;
6760 
6761   /// \brief A flag indicating whether either arithmetic or enumeration types
6762   /// were present in the candidate set.
6763   bool HasArithmeticOrEnumeralTypes;
6764 
6765   /// \brief A flag indicating whether the nullptr type was present in the
6766   /// candidate set.
6767   bool HasNullPtrType;
6768 
6769   /// Sema - The semantic analysis instance where we are building the
6770   /// candidate type set.
6771   Sema &SemaRef;
6772 
6773   /// Context - The AST context in which we will build the type sets.
6774   ASTContext &Context;
6775 
6776   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6777                                                const Qualifiers &VisibleQuals);
6778   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6779 
6780 public:
6781   /// iterator - Iterates through the types that are part of the set.
6782   typedef TypeSet::iterator iterator;
6783 
6784   BuiltinCandidateTypeSet(Sema &SemaRef)
6785     : HasNonRecordTypes(false),
6786       HasArithmeticOrEnumeralTypes(false),
6787       HasNullPtrType(false),
6788       SemaRef(SemaRef),
6789       Context(SemaRef.Context) { }
6790 
6791   void AddTypesConvertedFrom(QualType Ty,
6792                              SourceLocation Loc,
6793                              bool AllowUserConversions,
6794                              bool AllowExplicitConversions,
6795                              const Qualifiers &VisibleTypeConversionsQuals);
6796 
6797   /// pointer_begin - First pointer type found;
6798   iterator pointer_begin() { return PointerTypes.begin(); }
6799 
6800   /// pointer_end - Past the last pointer type found;
6801   iterator pointer_end() { return PointerTypes.end(); }
6802 
6803   /// member_pointer_begin - First member pointer type found;
6804   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6805 
6806   /// member_pointer_end - Past the last member pointer type found;
6807   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6808 
6809   /// enumeration_begin - First enumeration type found;
6810   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6811 
6812   /// enumeration_end - Past the last enumeration type found;
6813   iterator enumeration_end() { return EnumerationTypes.end(); }
6814 
6815   iterator vector_begin() { return VectorTypes.begin(); }
6816   iterator vector_end() { return VectorTypes.end(); }
6817 
6818   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6819   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6820   bool hasNullPtrType() const { return HasNullPtrType; }
6821 };
6822 
6823 } // end anonymous namespace
6824 
6825 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6826 /// the set of pointer types along with any more-qualified variants of
6827 /// that type. For example, if @p Ty is "int const *", this routine
6828 /// will add "int const *", "int const volatile *", "int const
6829 /// restrict *", and "int const volatile restrict *" to the set of
6830 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6831 /// false otherwise.
6832 ///
6833 /// FIXME: what to do about extended qualifiers?
6834 bool
6835 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6836                                              const Qualifiers &VisibleQuals) {
6837 
6838   // Insert this type.
6839   if (!PointerTypes.insert(Ty).second)
6840     return false;
6841 
6842   QualType PointeeTy;
6843   const PointerType *PointerTy = Ty->getAs<PointerType>();
6844   bool buildObjCPtr = false;
6845   if (!PointerTy) {
6846     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6847     PointeeTy = PTy->getPointeeType();
6848     buildObjCPtr = true;
6849   } else {
6850     PointeeTy = PointerTy->getPointeeType();
6851   }
6852 
6853   // Don't add qualified variants of arrays. For one, they're not allowed
6854   // (the qualifier would sink to the element type), and for another, the
6855   // only overload situation where it matters is subscript or pointer +- int,
6856   // and those shouldn't have qualifier variants anyway.
6857   if (PointeeTy->isArrayType())
6858     return true;
6859 
6860   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6861   bool hasVolatile = VisibleQuals.hasVolatile();
6862   bool hasRestrict = VisibleQuals.hasRestrict();
6863 
6864   // Iterate through all strict supersets of BaseCVR.
6865   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6866     if ((CVR | BaseCVR) != CVR) continue;
6867     // Skip over volatile if no volatile found anywhere in the types.
6868     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6869 
6870     // Skip over restrict if no restrict found anywhere in the types, or if
6871     // the type cannot be restrict-qualified.
6872     if ((CVR & Qualifiers::Restrict) &&
6873         (!hasRestrict ||
6874          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6875       continue;
6876 
6877     // Build qualified pointee type.
6878     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6879 
6880     // Build qualified pointer type.
6881     QualType QPointerTy;
6882     if (!buildObjCPtr)
6883       QPointerTy = Context.getPointerType(QPointeeTy);
6884     else
6885       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6886 
6887     // Insert qualified pointer type.
6888     PointerTypes.insert(QPointerTy);
6889   }
6890 
6891   return true;
6892 }
6893 
6894 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6895 /// to the set of pointer types along with any more-qualified variants of
6896 /// that type. For example, if @p Ty is "int const *", this routine
6897 /// will add "int const *", "int const volatile *", "int const
6898 /// restrict *", and "int const volatile restrict *" to the set of
6899 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6900 /// false otherwise.
6901 ///
6902 /// FIXME: what to do about extended qualifiers?
6903 bool
6904 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6905     QualType Ty) {
6906   // Insert this type.
6907   if (!MemberPointerTypes.insert(Ty).second)
6908     return false;
6909 
6910   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6911   assert(PointerTy && "type was not a member pointer type!");
6912 
6913   QualType PointeeTy = PointerTy->getPointeeType();
6914   // Don't add qualified variants of arrays. For one, they're not allowed
6915   // (the qualifier would sink to the element type), and for another, the
6916   // only overload situation where it matters is subscript or pointer +- int,
6917   // and those shouldn't have qualifier variants anyway.
6918   if (PointeeTy->isArrayType())
6919     return true;
6920   const Type *ClassTy = PointerTy->getClass();
6921 
6922   // Iterate through all strict supersets of the pointee type's CVR
6923   // qualifiers.
6924   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6925   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6926     if ((CVR | BaseCVR) != CVR) continue;
6927 
6928     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6929     MemberPointerTypes.insert(
6930       Context.getMemberPointerType(QPointeeTy, ClassTy));
6931   }
6932 
6933   return true;
6934 }
6935 
6936 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6937 /// Ty can be implicit converted to the given set of @p Types. We're
6938 /// primarily interested in pointer types and enumeration types. We also
6939 /// take member pointer types, for the conditional operator.
6940 /// AllowUserConversions is true if we should look at the conversion
6941 /// functions of a class type, and AllowExplicitConversions if we
6942 /// should also include the explicit conversion functions of a class
6943 /// type.
6944 void
6945 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6946                                                SourceLocation Loc,
6947                                                bool AllowUserConversions,
6948                                                bool AllowExplicitConversions,
6949                                                const Qualifiers &VisibleQuals) {
6950   // Only deal with canonical types.
6951   Ty = Context.getCanonicalType(Ty);
6952 
6953   // Look through reference types; they aren't part of the type of an
6954   // expression for the purposes of conversions.
6955   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6956     Ty = RefTy->getPointeeType();
6957 
6958   // If we're dealing with an array type, decay to the pointer.
6959   if (Ty->isArrayType())
6960     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6961 
6962   // Otherwise, we don't care about qualifiers on the type.
6963   Ty = Ty.getLocalUnqualifiedType();
6964 
6965   // Flag if we ever add a non-record type.
6966   const RecordType *TyRec = Ty->getAs<RecordType>();
6967   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6968 
6969   // Flag if we encounter an arithmetic type.
6970   HasArithmeticOrEnumeralTypes =
6971     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6972 
6973   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6974     PointerTypes.insert(Ty);
6975   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6976     // Insert our type, and its more-qualified variants, into the set
6977     // of types.
6978     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6979       return;
6980   } else if (Ty->isMemberPointerType()) {
6981     // Member pointers are far easier, since the pointee can't be converted.
6982     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6983       return;
6984   } else if (Ty->isEnumeralType()) {
6985     HasArithmeticOrEnumeralTypes = true;
6986     EnumerationTypes.insert(Ty);
6987   } else if (Ty->isVectorType()) {
6988     // We treat vector types as arithmetic types in many contexts as an
6989     // extension.
6990     HasArithmeticOrEnumeralTypes = true;
6991     VectorTypes.insert(Ty);
6992   } else if (Ty->isNullPtrType()) {
6993     HasNullPtrType = true;
6994   } else if (AllowUserConversions && TyRec) {
6995     // No conversion functions in incomplete types.
6996     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6997       return;
6998 
6999     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7000     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7001       if (isa<UsingShadowDecl>(D))
7002         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7003 
7004       // Skip conversion function templates; they don't tell us anything
7005       // about which builtin types we can convert to.
7006       if (isa<FunctionTemplateDecl>(D))
7007         continue;
7008 
7009       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7010       if (AllowExplicitConversions || !Conv->isExplicit()) {
7011         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7012                               VisibleQuals);
7013       }
7014     }
7015   }
7016 }
7017 
7018 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7019 /// the volatile- and non-volatile-qualified assignment operators for the
7020 /// given type to the candidate set.
7021 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7022                                                    QualType T,
7023                                                    ArrayRef<Expr *> Args,
7024                                     OverloadCandidateSet &CandidateSet) {
7025   QualType ParamTypes[2];
7026 
7027   // T& operator=(T&, T)
7028   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7029   ParamTypes[1] = T;
7030   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7031                         /*IsAssignmentOperator=*/true);
7032 
7033   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7034     // volatile T& operator=(volatile T&, T)
7035     ParamTypes[0]
7036       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7037     ParamTypes[1] = T;
7038     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7039                           /*IsAssignmentOperator=*/true);
7040   }
7041 }
7042 
7043 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7044 /// if any, found in visible type conversion functions found in ArgExpr's type.
7045 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7046     Qualifiers VRQuals;
7047     const RecordType *TyRec;
7048     if (const MemberPointerType *RHSMPType =
7049         ArgExpr->getType()->getAs<MemberPointerType>())
7050       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7051     else
7052       TyRec = ArgExpr->getType()->getAs<RecordType>();
7053     if (!TyRec) {
7054       // Just to be safe, assume the worst case.
7055       VRQuals.addVolatile();
7056       VRQuals.addRestrict();
7057       return VRQuals;
7058     }
7059 
7060     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7061     if (!ClassDecl->hasDefinition())
7062       return VRQuals;
7063 
7064     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7065       if (isa<UsingShadowDecl>(D))
7066         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7067       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7068         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7069         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7070           CanTy = ResTypeRef->getPointeeType();
7071         // Need to go down the pointer/mempointer chain and add qualifiers
7072         // as see them.
7073         bool done = false;
7074         while (!done) {
7075           if (CanTy.isRestrictQualified())
7076             VRQuals.addRestrict();
7077           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7078             CanTy = ResTypePtr->getPointeeType();
7079           else if (const MemberPointerType *ResTypeMPtr =
7080                 CanTy->getAs<MemberPointerType>())
7081             CanTy = ResTypeMPtr->getPointeeType();
7082           else
7083             done = true;
7084           if (CanTy.isVolatileQualified())
7085             VRQuals.addVolatile();
7086           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7087             return VRQuals;
7088         }
7089       }
7090     }
7091     return VRQuals;
7092 }
7093 
7094 namespace {
7095 
7096 /// \brief Helper class to manage the addition of builtin operator overload
7097 /// candidates. It provides shared state and utility methods used throughout
7098 /// the process, as well as a helper method to add each group of builtin
7099 /// operator overloads from the standard to a candidate set.
7100 class BuiltinOperatorOverloadBuilder {
7101   // Common instance state available to all overload candidate addition methods.
7102   Sema &S;
7103   ArrayRef<Expr *> Args;
7104   Qualifiers VisibleTypeConversionsQuals;
7105   bool HasArithmeticOrEnumeralCandidateType;
7106   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7107   OverloadCandidateSet &CandidateSet;
7108 
7109   // Define some constants used to index and iterate over the arithemetic types
7110   // provided via the getArithmeticType() method below.
7111   // The "promoted arithmetic types" are the arithmetic
7112   // types are that preserved by promotion (C++ [over.built]p2).
7113   static const unsigned FirstIntegralType = 3;
7114   static const unsigned LastIntegralType = 20;
7115   static const unsigned FirstPromotedIntegralType = 3,
7116                         LastPromotedIntegralType = 11;
7117   static const unsigned FirstPromotedArithmeticType = 0,
7118                         LastPromotedArithmeticType = 11;
7119   static const unsigned NumArithmeticTypes = 20;
7120 
7121   /// \brief Get the canonical type for a given arithmetic type index.
7122   CanQualType getArithmeticType(unsigned index) {
7123     assert(index < NumArithmeticTypes);
7124     static CanQualType ASTContext::* const
7125       ArithmeticTypes[NumArithmeticTypes] = {
7126       // Start of promoted types.
7127       &ASTContext::FloatTy,
7128       &ASTContext::DoubleTy,
7129       &ASTContext::LongDoubleTy,
7130 
7131       // Start of integral types.
7132       &ASTContext::IntTy,
7133       &ASTContext::LongTy,
7134       &ASTContext::LongLongTy,
7135       &ASTContext::Int128Ty,
7136       &ASTContext::UnsignedIntTy,
7137       &ASTContext::UnsignedLongTy,
7138       &ASTContext::UnsignedLongLongTy,
7139       &ASTContext::UnsignedInt128Ty,
7140       // End of promoted types.
7141 
7142       &ASTContext::BoolTy,
7143       &ASTContext::CharTy,
7144       &ASTContext::WCharTy,
7145       &ASTContext::Char16Ty,
7146       &ASTContext::Char32Ty,
7147       &ASTContext::SignedCharTy,
7148       &ASTContext::ShortTy,
7149       &ASTContext::UnsignedCharTy,
7150       &ASTContext::UnsignedShortTy,
7151       // End of integral types.
7152       // FIXME: What about complex? What about half?
7153     };
7154     return S.Context.*ArithmeticTypes[index];
7155   }
7156 
7157   /// \brief Gets the canonical type resulting from the usual arithemetic
7158   /// converions for the given arithmetic types.
7159   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7160     // Accelerator table for performing the usual arithmetic conversions.
7161     // The rules are basically:
7162     //   - if either is floating-point, use the wider floating-point
7163     //   - if same signedness, use the higher rank
7164     //   - if same size, use unsigned of the higher rank
7165     //   - use the larger type
7166     // These rules, together with the axiom that higher ranks are
7167     // never smaller, are sufficient to precompute all of these results
7168     // *except* when dealing with signed types of higher rank.
7169     // (we could precompute SLL x UI for all known platforms, but it's
7170     // better not to make any assumptions).
7171     // We assume that int128 has a higher rank than long long on all platforms.
7172     enum PromotedType {
7173             Dep=-1,
7174             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7175     };
7176     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7177                                         [LastPromotedArithmeticType] = {
7178 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7179 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7180 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7181 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7182 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7183 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7184 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7185 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7186 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7187 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7188 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7189     };
7190 
7191     assert(L < LastPromotedArithmeticType);
7192     assert(R < LastPromotedArithmeticType);
7193     int Idx = ConversionsTable[L][R];
7194 
7195     // Fast path: the table gives us a concrete answer.
7196     if (Idx != Dep) return getArithmeticType(Idx);
7197 
7198     // Slow path: we need to compare widths.
7199     // An invariant is that the signed type has higher rank.
7200     CanQualType LT = getArithmeticType(L),
7201                 RT = getArithmeticType(R);
7202     unsigned LW = S.Context.getIntWidth(LT),
7203              RW = S.Context.getIntWidth(RT);
7204 
7205     // If they're different widths, use the signed type.
7206     if (LW > RW) return LT;
7207     else if (LW < RW) return RT;
7208 
7209     // Otherwise, use the unsigned type of the signed type's rank.
7210     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7211     assert(L == SLL || R == SLL);
7212     return S.Context.UnsignedLongLongTy;
7213   }
7214 
7215   /// \brief Helper method to factor out the common pattern of adding overloads
7216   /// for '++' and '--' builtin operators.
7217   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7218                                            bool HasVolatile,
7219                                            bool HasRestrict) {
7220     QualType ParamTypes[2] = {
7221       S.Context.getLValueReferenceType(CandidateTy),
7222       S.Context.IntTy
7223     };
7224 
7225     // Non-volatile version.
7226     if (Args.size() == 1)
7227       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7228     else
7229       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7230 
7231     // Use a heuristic to reduce number of builtin candidates in the set:
7232     // add volatile version only if there are conversions to a volatile type.
7233     if (HasVolatile) {
7234       ParamTypes[0] =
7235         S.Context.getLValueReferenceType(
7236           S.Context.getVolatileType(CandidateTy));
7237       if (Args.size() == 1)
7238         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7239       else
7240         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7241     }
7242 
7243     // Add restrict version only if there are conversions to a restrict type
7244     // and our candidate type is a non-restrict-qualified pointer.
7245     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7246         !CandidateTy.isRestrictQualified()) {
7247       ParamTypes[0]
7248         = S.Context.getLValueReferenceType(
7249             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7250       if (Args.size() == 1)
7251         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7252       else
7253         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7254 
7255       if (HasVolatile) {
7256         ParamTypes[0]
7257           = S.Context.getLValueReferenceType(
7258               S.Context.getCVRQualifiedType(CandidateTy,
7259                                             (Qualifiers::Volatile |
7260                                              Qualifiers::Restrict)));
7261         if (Args.size() == 1)
7262           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7263         else
7264           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7265       }
7266     }
7267 
7268   }
7269 
7270 public:
7271   BuiltinOperatorOverloadBuilder(
7272     Sema &S, ArrayRef<Expr *> Args,
7273     Qualifiers VisibleTypeConversionsQuals,
7274     bool HasArithmeticOrEnumeralCandidateType,
7275     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7276     OverloadCandidateSet &CandidateSet)
7277     : S(S), Args(Args),
7278       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7279       HasArithmeticOrEnumeralCandidateType(
7280         HasArithmeticOrEnumeralCandidateType),
7281       CandidateTypes(CandidateTypes),
7282       CandidateSet(CandidateSet) {
7283     // Validate some of our static helper constants in debug builds.
7284     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7285            "Invalid first promoted integral type");
7286     assert(getArithmeticType(LastPromotedIntegralType - 1)
7287              == S.Context.UnsignedInt128Ty &&
7288            "Invalid last promoted integral type");
7289     assert(getArithmeticType(FirstPromotedArithmeticType)
7290              == S.Context.FloatTy &&
7291            "Invalid first promoted arithmetic type");
7292     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7293              == S.Context.UnsignedInt128Ty &&
7294            "Invalid last promoted arithmetic type");
7295   }
7296 
7297   // C++ [over.built]p3:
7298   //
7299   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7300   //   is either volatile or empty, there exist candidate operator
7301   //   functions of the form
7302   //
7303   //       VQ T&      operator++(VQ T&);
7304   //       T          operator++(VQ T&, int);
7305   //
7306   // C++ [over.built]p4:
7307   //
7308   //   For every pair (T, VQ), where T is an arithmetic type other
7309   //   than bool, and VQ is either volatile or empty, there exist
7310   //   candidate operator functions of the form
7311   //
7312   //       VQ T&      operator--(VQ T&);
7313   //       T          operator--(VQ T&, int);
7314   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7315     if (!HasArithmeticOrEnumeralCandidateType)
7316       return;
7317 
7318     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7319          Arith < NumArithmeticTypes; ++Arith) {
7320       addPlusPlusMinusMinusStyleOverloads(
7321         getArithmeticType(Arith),
7322         VisibleTypeConversionsQuals.hasVolatile(),
7323         VisibleTypeConversionsQuals.hasRestrict());
7324     }
7325   }
7326 
7327   // C++ [over.built]p5:
7328   //
7329   //   For every pair (T, VQ), where T is a cv-qualified or
7330   //   cv-unqualified object type, and VQ is either volatile or
7331   //   empty, there exist candidate operator functions of the form
7332   //
7333   //       T*VQ&      operator++(T*VQ&);
7334   //       T*VQ&      operator--(T*VQ&);
7335   //       T*         operator++(T*VQ&, int);
7336   //       T*         operator--(T*VQ&, int);
7337   void addPlusPlusMinusMinusPointerOverloads() {
7338     for (BuiltinCandidateTypeSet::iterator
7339               Ptr = CandidateTypes[0].pointer_begin(),
7340            PtrEnd = CandidateTypes[0].pointer_end();
7341          Ptr != PtrEnd; ++Ptr) {
7342       // Skip pointer types that aren't pointers to object types.
7343       if (!(*Ptr)->getPointeeType()->isObjectType())
7344         continue;
7345 
7346       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7347         (!(*Ptr).isVolatileQualified() &&
7348          VisibleTypeConversionsQuals.hasVolatile()),
7349         (!(*Ptr).isRestrictQualified() &&
7350          VisibleTypeConversionsQuals.hasRestrict()));
7351     }
7352   }
7353 
7354   // C++ [over.built]p6:
7355   //   For every cv-qualified or cv-unqualified object type T, there
7356   //   exist candidate operator functions of the form
7357   //
7358   //       T&         operator*(T*);
7359   //
7360   // C++ [over.built]p7:
7361   //   For every function type T that does not have cv-qualifiers or a
7362   //   ref-qualifier, there exist candidate operator functions of the form
7363   //       T&         operator*(T*);
7364   void addUnaryStarPointerOverloads() {
7365     for (BuiltinCandidateTypeSet::iterator
7366               Ptr = CandidateTypes[0].pointer_begin(),
7367            PtrEnd = CandidateTypes[0].pointer_end();
7368          Ptr != PtrEnd; ++Ptr) {
7369       QualType ParamTy = *Ptr;
7370       QualType PointeeTy = ParamTy->getPointeeType();
7371       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7372         continue;
7373 
7374       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7375         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7376           continue;
7377 
7378       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7379                             &ParamTy, Args, CandidateSet);
7380     }
7381   }
7382 
7383   // C++ [over.built]p9:
7384   //  For every promoted arithmetic type T, there exist candidate
7385   //  operator functions of the form
7386   //
7387   //       T         operator+(T);
7388   //       T         operator-(T);
7389   void addUnaryPlusOrMinusArithmeticOverloads() {
7390     if (!HasArithmeticOrEnumeralCandidateType)
7391       return;
7392 
7393     for (unsigned Arith = FirstPromotedArithmeticType;
7394          Arith < LastPromotedArithmeticType; ++Arith) {
7395       QualType ArithTy = getArithmeticType(Arith);
7396       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7397     }
7398 
7399     // Extension: We also add these operators for vector types.
7400     for (BuiltinCandidateTypeSet::iterator
7401               Vec = CandidateTypes[0].vector_begin(),
7402            VecEnd = CandidateTypes[0].vector_end();
7403          Vec != VecEnd; ++Vec) {
7404       QualType VecTy = *Vec;
7405       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7406     }
7407   }
7408 
7409   // C++ [over.built]p8:
7410   //   For every type T, there exist candidate operator functions of
7411   //   the form
7412   //
7413   //       T*         operator+(T*);
7414   void addUnaryPlusPointerOverloads() {
7415     for (BuiltinCandidateTypeSet::iterator
7416               Ptr = CandidateTypes[0].pointer_begin(),
7417            PtrEnd = CandidateTypes[0].pointer_end();
7418          Ptr != PtrEnd; ++Ptr) {
7419       QualType ParamTy = *Ptr;
7420       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7421     }
7422   }
7423 
7424   // C++ [over.built]p10:
7425   //   For every promoted integral type T, there exist candidate
7426   //   operator functions of the form
7427   //
7428   //        T         operator~(T);
7429   void addUnaryTildePromotedIntegralOverloads() {
7430     if (!HasArithmeticOrEnumeralCandidateType)
7431       return;
7432 
7433     for (unsigned Int = FirstPromotedIntegralType;
7434          Int < LastPromotedIntegralType; ++Int) {
7435       QualType IntTy = getArithmeticType(Int);
7436       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7437     }
7438 
7439     // Extension: We also add this operator for vector types.
7440     for (BuiltinCandidateTypeSet::iterator
7441               Vec = CandidateTypes[0].vector_begin(),
7442            VecEnd = CandidateTypes[0].vector_end();
7443          Vec != VecEnd; ++Vec) {
7444       QualType VecTy = *Vec;
7445       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7446     }
7447   }
7448 
7449   // C++ [over.match.oper]p16:
7450   //   For every pointer to member type T, there exist candidate operator
7451   //   functions of the form
7452   //
7453   //        bool operator==(T,T);
7454   //        bool operator!=(T,T);
7455   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7456     /// Set of (canonical) types that we've already handled.
7457     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7458 
7459     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7460       for (BuiltinCandidateTypeSet::iterator
7461                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7462              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7463            MemPtr != MemPtrEnd;
7464            ++MemPtr) {
7465         // Don't add the same builtin candidate twice.
7466         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7467           continue;
7468 
7469         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7470         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7471       }
7472     }
7473   }
7474 
7475   // C++ [over.built]p15:
7476   //
7477   //   For every T, where T is an enumeration type, a pointer type, or
7478   //   std::nullptr_t, there exist candidate operator functions of the form
7479   //
7480   //        bool       operator<(T, T);
7481   //        bool       operator>(T, T);
7482   //        bool       operator<=(T, T);
7483   //        bool       operator>=(T, T);
7484   //        bool       operator==(T, T);
7485   //        bool       operator!=(T, T);
7486   void addRelationalPointerOrEnumeralOverloads() {
7487     // C++ [over.match.oper]p3:
7488     //   [...]the built-in candidates include all of the candidate operator
7489     //   functions defined in 13.6 that, compared to the given operator, [...]
7490     //   do not have the same parameter-type-list as any non-template non-member
7491     //   candidate.
7492     //
7493     // Note that in practice, this only affects enumeration types because there
7494     // aren't any built-in candidates of record type, and a user-defined operator
7495     // must have an operand of record or enumeration type. Also, the only other
7496     // overloaded operator with enumeration arguments, operator=,
7497     // cannot be overloaded for enumeration types, so this is the only place
7498     // where we must suppress candidates like this.
7499     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7500       UserDefinedBinaryOperators;
7501 
7502     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7503       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7504           CandidateTypes[ArgIdx].enumeration_end()) {
7505         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7506                                          CEnd = CandidateSet.end();
7507              C != CEnd; ++C) {
7508           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7509             continue;
7510 
7511           if (C->Function->isFunctionTemplateSpecialization())
7512             continue;
7513 
7514           QualType FirstParamType =
7515             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7516           QualType SecondParamType =
7517             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7518 
7519           // Skip if either parameter isn't of enumeral type.
7520           if (!FirstParamType->isEnumeralType() ||
7521               !SecondParamType->isEnumeralType())
7522             continue;
7523 
7524           // Add this operator to the set of known user-defined operators.
7525           UserDefinedBinaryOperators.insert(
7526             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7527                            S.Context.getCanonicalType(SecondParamType)));
7528         }
7529       }
7530     }
7531 
7532     /// Set of (canonical) types that we've already handled.
7533     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7534 
7535     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7536       for (BuiltinCandidateTypeSet::iterator
7537                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7538              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7539            Ptr != PtrEnd; ++Ptr) {
7540         // Don't add the same builtin candidate twice.
7541         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7542           continue;
7543 
7544         QualType ParamTypes[2] = { *Ptr, *Ptr };
7545         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7546       }
7547       for (BuiltinCandidateTypeSet::iterator
7548                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7549              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7550            Enum != EnumEnd; ++Enum) {
7551         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7552 
7553         // Don't add the same builtin candidate twice, or if a user defined
7554         // candidate exists.
7555         if (!AddedTypes.insert(CanonType).second ||
7556             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7557                                                             CanonType)))
7558           continue;
7559 
7560         QualType ParamTypes[2] = { *Enum, *Enum };
7561         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7562       }
7563 
7564       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7565         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7566         if (AddedTypes.insert(NullPtrTy).second &&
7567             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7568                                                              NullPtrTy))) {
7569           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7570           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7571                                 CandidateSet);
7572         }
7573       }
7574     }
7575   }
7576 
7577   // C++ [over.built]p13:
7578   //
7579   //   For every cv-qualified or cv-unqualified object type T
7580   //   there exist candidate operator functions of the form
7581   //
7582   //      T*         operator+(T*, ptrdiff_t);
7583   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7584   //      T*         operator-(T*, ptrdiff_t);
7585   //      T*         operator+(ptrdiff_t, T*);
7586   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7587   //
7588   // C++ [over.built]p14:
7589   //
7590   //   For every T, where T is a pointer to object type, there
7591   //   exist candidate operator functions of the form
7592   //
7593   //      ptrdiff_t  operator-(T, T);
7594   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7595     /// Set of (canonical) types that we've already handled.
7596     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7597 
7598     for (int Arg = 0; Arg < 2; ++Arg) {
7599       QualType AsymmetricParamTypes[2] = {
7600         S.Context.getPointerDiffType(),
7601         S.Context.getPointerDiffType(),
7602       };
7603       for (BuiltinCandidateTypeSet::iterator
7604                 Ptr = CandidateTypes[Arg].pointer_begin(),
7605              PtrEnd = CandidateTypes[Arg].pointer_end();
7606            Ptr != PtrEnd; ++Ptr) {
7607         QualType PointeeTy = (*Ptr)->getPointeeType();
7608         if (!PointeeTy->isObjectType())
7609           continue;
7610 
7611         AsymmetricParamTypes[Arg] = *Ptr;
7612         if (Arg == 0 || Op == OO_Plus) {
7613           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7614           // T* operator+(ptrdiff_t, T*);
7615           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7616         }
7617         if (Op == OO_Minus) {
7618           // ptrdiff_t operator-(T, T);
7619           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7620             continue;
7621 
7622           QualType ParamTypes[2] = { *Ptr, *Ptr };
7623           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7624                                 Args, CandidateSet);
7625         }
7626       }
7627     }
7628   }
7629 
7630   // C++ [over.built]p12:
7631   //
7632   //   For every pair of promoted arithmetic types L and R, there
7633   //   exist candidate operator functions of the form
7634   //
7635   //        LR         operator*(L, R);
7636   //        LR         operator/(L, R);
7637   //        LR         operator+(L, R);
7638   //        LR         operator-(L, R);
7639   //        bool       operator<(L, R);
7640   //        bool       operator>(L, R);
7641   //        bool       operator<=(L, R);
7642   //        bool       operator>=(L, R);
7643   //        bool       operator==(L, R);
7644   //        bool       operator!=(L, R);
7645   //
7646   //   where LR is the result of the usual arithmetic conversions
7647   //   between types L and R.
7648   //
7649   // C++ [over.built]p24:
7650   //
7651   //   For every pair of promoted arithmetic types L and R, there exist
7652   //   candidate operator functions of the form
7653   //
7654   //        LR       operator?(bool, L, R);
7655   //
7656   //   where LR is the result of the usual arithmetic conversions
7657   //   between types L and R.
7658   // Our candidates ignore the first parameter.
7659   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7660     if (!HasArithmeticOrEnumeralCandidateType)
7661       return;
7662 
7663     for (unsigned Left = FirstPromotedArithmeticType;
7664          Left < LastPromotedArithmeticType; ++Left) {
7665       for (unsigned Right = FirstPromotedArithmeticType;
7666            Right < LastPromotedArithmeticType; ++Right) {
7667         QualType LandR[2] = { getArithmeticType(Left),
7668                               getArithmeticType(Right) };
7669         QualType Result =
7670           isComparison ? S.Context.BoolTy
7671                        : getUsualArithmeticConversions(Left, Right);
7672         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7673       }
7674     }
7675 
7676     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7677     // conditional operator for vector types.
7678     for (BuiltinCandidateTypeSet::iterator
7679               Vec1 = CandidateTypes[0].vector_begin(),
7680            Vec1End = CandidateTypes[0].vector_end();
7681          Vec1 != Vec1End; ++Vec1) {
7682       for (BuiltinCandidateTypeSet::iterator
7683                 Vec2 = CandidateTypes[1].vector_begin(),
7684              Vec2End = CandidateTypes[1].vector_end();
7685            Vec2 != Vec2End; ++Vec2) {
7686         QualType LandR[2] = { *Vec1, *Vec2 };
7687         QualType Result = S.Context.BoolTy;
7688         if (!isComparison) {
7689           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7690             Result = *Vec1;
7691           else
7692             Result = *Vec2;
7693         }
7694 
7695         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7696       }
7697     }
7698   }
7699 
7700   // C++ [over.built]p17:
7701   //
7702   //   For every pair of promoted integral types L and R, there
7703   //   exist candidate operator functions of the form
7704   //
7705   //      LR         operator%(L, R);
7706   //      LR         operator&(L, R);
7707   //      LR         operator^(L, R);
7708   //      LR         operator|(L, R);
7709   //      L          operator<<(L, R);
7710   //      L          operator>>(L, R);
7711   //
7712   //   where LR is the result of the usual arithmetic conversions
7713   //   between types L and R.
7714   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7715     if (!HasArithmeticOrEnumeralCandidateType)
7716       return;
7717 
7718     for (unsigned Left = FirstPromotedIntegralType;
7719          Left < LastPromotedIntegralType; ++Left) {
7720       for (unsigned Right = FirstPromotedIntegralType;
7721            Right < LastPromotedIntegralType; ++Right) {
7722         QualType LandR[2] = { getArithmeticType(Left),
7723                               getArithmeticType(Right) };
7724         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7725             ? LandR[0]
7726             : getUsualArithmeticConversions(Left, Right);
7727         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7728       }
7729     }
7730   }
7731 
7732   // C++ [over.built]p20:
7733   //
7734   //   For every pair (T, VQ), where T is an enumeration or
7735   //   pointer to member type and VQ is either volatile or
7736   //   empty, there exist candidate operator functions of the form
7737   //
7738   //        VQ T&      operator=(VQ T&, T);
7739   void addAssignmentMemberPointerOrEnumeralOverloads() {
7740     /// Set of (canonical) types that we've already handled.
7741     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7742 
7743     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7744       for (BuiltinCandidateTypeSet::iterator
7745                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7746              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7747            Enum != EnumEnd; ++Enum) {
7748         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7749           continue;
7750 
7751         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7752       }
7753 
7754       for (BuiltinCandidateTypeSet::iterator
7755                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7756              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7757            MemPtr != MemPtrEnd; ++MemPtr) {
7758         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7759           continue;
7760 
7761         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7762       }
7763     }
7764   }
7765 
7766   // C++ [over.built]p19:
7767   //
7768   //   For every pair (T, VQ), where T is any type and VQ is either
7769   //   volatile or empty, there exist candidate operator functions
7770   //   of the form
7771   //
7772   //        T*VQ&      operator=(T*VQ&, T*);
7773   //
7774   // C++ [over.built]p21:
7775   //
7776   //   For every pair (T, VQ), where T is a cv-qualified or
7777   //   cv-unqualified object type and VQ is either volatile or
7778   //   empty, there exist candidate operator functions of the form
7779   //
7780   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7781   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7782   void addAssignmentPointerOverloads(bool isEqualOp) {
7783     /// Set of (canonical) types that we've already handled.
7784     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7785 
7786     for (BuiltinCandidateTypeSet::iterator
7787               Ptr = CandidateTypes[0].pointer_begin(),
7788            PtrEnd = CandidateTypes[0].pointer_end();
7789          Ptr != PtrEnd; ++Ptr) {
7790       // If this is operator=, keep track of the builtin candidates we added.
7791       if (isEqualOp)
7792         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7793       else if (!(*Ptr)->getPointeeType()->isObjectType())
7794         continue;
7795 
7796       // non-volatile version
7797       QualType ParamTypes[2] = {
7798         S.Context.getLValueReferenceType(*Ptr),
7799         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7800       };
7801       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7802                             /*IsAssigmentOperator=*/ isEqualOp);
7803 
7804       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7805                           VisibleTypeConversionsQuals.hasVolatile();
7806       if (NeedVolatile) {
7807         // volatile version
7808         ParamTypes[0] =
7809           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7810         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7811                               /*IsAssigmentOperator=*/isEqualOp);
7812       }
7813 
7814       if (!(*Ptr).isRestrictQualified() &&
7815           VisibleTypeConversionsQuals.hasRestrict()) {
7816         // restrict version
7817         ParamTypes[0]
7818           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7819         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7820                               /*IsAssigmentOperator=*/isEqualOp);
7821 
7822         if (NeedVolatile) {
7823           // volatile restrict version
7824           ParamTypes[0]
7825             = S.Context.getLValueReferenceType(
7826                 S.Context.getCVRQualifiedType(*Ptr,
7827                                               (Qualifiers::Volatile |
7828                                                Qualifiers::Restrict)));
7829           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7830                                 /*IsAssigmentOperator=*/isEqualOp);
7831         }
7832       }
7833     }
7834 
7835     if (isEqualOp) {
7836       for (BuiltinCandidateTypeSet::iterator
7837                 Ptr = CandidateTypes[1].pointer_begin(),
7838              PtrEnd = CandidateTypes[1].pointer_end();
7839            Ptr != PtrEnd; ++Ptr) {
7840         // Make sure we don't add the same candidate twice.
7841         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7842           continue;
7843 
7844         QualType ParamTypes[2] = {
7845           S.Context.getLValueReferenceType(*Ptr),
7846           *Ptr,
7847         };
7848 
7849         // non-volatile version
7850         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7851                               /*IsAssigmentOperator=*/true);
7852 
7853         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7854                            VisibleTypeConversionsQuals.hasVolatile();
7855         if (NeedVolatile) {
7856           // volatile version
7857           ParamTypes[0] =
7858             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7859           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7860                                 /*IsAssigmentOperator=*/true);
7861         }
7862 
7863         if (!(*Ptr).isRestrictQualified() &&
7864             VisibleTypeConversionsQuals.hasRestrict()) {
7865           // restrict version
7866           ParamTypes[0]
7867             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7868           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7869                                 /*IsAssigmentOperator=*/true);
7870 
7871           if (NeedVolatile) {
7872             // volatile restrict version
7873             ParamTypes[0]
7874               = S.Context.getLValueReferenceType(
7875                   S.Context.getCVRQualifiedType(*Ptr,
7876                                                 (Qualifiers::Volatile |
7877                                                  Qualifiers::Restrict)));
7878             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7879                                   /*IsAssigmentOperator=*/true);
7880           }
7881         }
7882       }
7883     }
7884   }
7885 
7886   // C++ [over.built]p18:
7887   //
7888   //   For every triple (L, VQ, R), where L is an arithmetic type,
7889   //   VQ is either volatile or empty, and R is a promoted
7890   //   arithmetic type, there exist candidate operator functions of
7891   //   the form
7892   //
7893   //        VQ L&      operator=(VQ L&, R);
7894   //        VQ L&      operator*=(VQ L&, R);
7895   //        VQ L&      operator/=(VQ L&, R);
7896   //        VQ L&      operator+=(VQ L&, R);
7897   //        VQ L&      operator-=(VQ L&, R);
7898   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7899     if (!HasArithmeticOrEnumeralCandidateType)
7900       return;
7901 
7902     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7903       for (unsigned Right = FirstPromotedArithmeticType;
7904            Right < LastPromotedArithmeticType; ++Right) {
7905         QualType ParamTypes[2];
7906         ParamTypes[1] = getArithmeticType(Right);
7907 
7908         // Add this built-in operator as a candidate (VQ is empty).
7909         ParamTypes[0] =
7910           S.Context.getLValueReferenceType(getArithmeticType(Left));
7911         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7912                               /*IsAssigmentOperator=*/isEqualOp);
7913 
7914         // Add this built-in operator as a candidate (VQ is 'volatile').
7915         if (VisibleTypeConversionsQuals.hasVolatile()) {
7916           ParamTypes[0] =
7917             S.Context.getVolatileType(getArithmeticType(Left));
7918           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7919           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7920                                 /*IsAssigmentOperator=*/isEqualOp);
7921         }
7922       }
7923     }
7924 
7925     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7926     for (BuiltinCandidateTypeSet::iterator
7927               Vec1 = CandidateTypes[0].vector_begin(),
7928            Vec1End = CandidateTypes[0].vector_end();
7929          Vec1 != Vec1End; ++Vec1) {
7930       for (BuiltinCandidateTypeSet::iterator
7931                 Vec2 = CandidateTypes[1].vector_begin(),
7932              Vec2End = CandidateTypes[1].vector_end();
7933            Vec2 != Vec2End; ++Vec2) {
7934         QualType ParamTypes[2];
7935         ParamTypes[1] = *Vec2;
7936         // Add this built-in operator as a candidate (VQ is empty).
7937         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7938         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7939                               /*IsAssigmentOperator=*/isEqualOp);
7940 
7941         // Add this built-in operator as a candidate (VQ is 'volatile').
7942         if (VisibleTypeConversionsQuals.hasVolatile()) {
7943           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7944           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7945           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7946                                 /*IsAssigmentOperator=*/isEqualOp);
7947         }
7948       }
7949     }
7950   }
7951 
7952   // C++ [over.built]p22:
7953   //
7954   //   For every triple (L, VQ, R), where L is an integral type, VQ
7955   //   is either volatile or empty, and R is a promoted integral
7956   //   type, there exist candidate operator functions of the form
7957   //
7958   //        VQ L&       operator%=(VQ L&, R);
7959   //        VQ L&       operator<<=(VQ L&, R);
7960   //        VQ L&       operator>>=(VQ L&, R);
7961   //        VQ L&       operator&=(VQ L&, R);
7962   //        VQ L&       operator^=(VQ L&, R);
7963   //        VQ L&       operator|=(VQ L&, R);
7964   void addAssignmentIntegralOverloads() {
7965     if (!HasArithmeticOrEnumeralCandidateType)
7966       return;
7967 
7968     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7969       for (unsigned Right = FirstPromotedIntegralType;
7970            Right < LastPromotedIntegralType; ++Right) {
7971         QualType ParamTypes[2];
7972         ParamTypes[1] = getArithmeticType(Right);
7973 
7974         // Add this built-in operator as a candidate (VQ is empty).
7975         ParamTypes[0] =
7976           S.Context.getLValueReferenceType(getArithmeticType(Left));
7977         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7978         if (VisibleTypeConversionsQuals.hasVolatile()) {
7979           // Add this built-in operator as a candidate (VQ is 'volatile').
7980           ParamTypes[0] = getArithmeticType(Left);
7981           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7982           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7983           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7984         }
7985       }
7986     }
7987   }
7988 
7989   // C++ [over.operator]p23:
7990   //
7991   //   There also exist candidate operator functions of the form
7992   //
7993   //        bool        operator!(bool);
7994   //        bool        operator&&(bool, bool);
7995   //        bool        operator||(bool, bool);
7996   void addExclaimOverload() {
7997     QualType ParamTy = S.Context.BoolTy;
7998     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7999                           /*IsAssignmentOperator=*/false,
8000                           /*NumContextualBoolArguments=*/1);
8001   }
8002   void addAmpAmpOrPipePipeOverload() {
8003     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8004     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8005                           /*IsAssignmentOperator=*/false,
8006                           /*NumContextualBoolArguments=*/2);
8007   }
8008 
8009   // C++ [over.built]p13:
8010   //
8011   //   For every cv-qualified or cv-unqualified object type T there
8012   //   exist candidate operator functions of the form
8013   //
8014   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8015   //        T&         operator[](T*, ptrdiff_t);
8016   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8017   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8018   //        T&         operator[](ptrdiff_t, T*);
8019   void addSubscriptOverloads() {
8020     for (BuiltinCandidateTypeSet::iterator
8021               Ptr = CandidateTypes[0].pointer_begin(),
8022            PtrEnd = CandidateTypes[0].pointer_end();
8023          Ptr != PtrEnd; ++Ptr) {
8024       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8025       QualType PointeeType = (*Ptr)->getPointeeType();
8026       if (!PointeeType->isObjectType())
8027         continue;
8028 
8029       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8030 
8031       // T& operator[](T*, ptrdiff_t)
8032       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8033     }
8034 
8035     for (BuiltinCandidateTypeSet::iterator
8036               Ptr = CandidateTypes[1].pointer_begin(),
8037            PtrEnd = CandidateTypes[1].pointer_end();
8038          Ptr != PtrEnd; ++Ptr) {
8039       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8040       QualType PointeeType = (*Ptr)->getPointeeType();
8041       if (!PointeeType->isObjectType())
8042         continue;
8043 
8044       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8045 
8046       // T& operator[](ptrdiff_t, T*)
8047       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8048     }
8049   }
8050 
8051   // C++ [over.built]p11:
8052   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8053   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8054   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8055   //    there exist candidate operator functions of the form
8056   //
8057   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8058   //
8059   //    where CV12 is the union of CV1 and CV2.
8060   void addArrowStarOverloads() {
8061     for (BuiltinCandidateTypeSet::iterator
8062              Ptr = CandidateTypes[0].pointer_begin(),
8063            PtrEnd = CandidateTypes[0].pointer_end();
8064          Ptr != PtrEnd; ++Ptr) {
8065       QualType C1Ty = (*Ptr);
8066       QualType C1;
8067       QualifierCollector Q1;
8068       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8069       if (!isa<RecordType>(C1))
8070         continue;
8071       // heuristic to reduce number of builtin candidates in the set.
8072       // Add volatile/restrict version only if there are conversions to a
8073       // volatile/restrict type.
8074       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8075         continue;
8076       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8077         continue;
8078       for (BuiltinCandidateTypeSet::iterator
8079                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8080              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8081            MemPtr != MemPtrEnd; ++MemPtr) {
8082         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8083         QualType C2 = QualType(mptr->getClass(), 0);
8084         C2 = C2.getUnqualifiedType();
8085         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8086           break;
8087         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8088         // build CV12 T&
8089         QualType T = mptr->getPointeeType();
8090         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8091             T.isVolatileQualified())
8092           continue;
8093         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8094             T.isRestrictQualified())
8095           continue;
8096         T = Q1.apply(S.Context, T);
8097         QualType ResultTy = S.Context.getLValueReferenceType(T);
8098         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8099       }
8100     }
8101   }
8102 
8103   // Note that we don't consider the first argument, since it has been
8104   // contextually converted to bool long ago. The candidates below are
8105   // therefore added as binary.
8106   //
8107   // C++ [over.built]p25:
8108   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8109   //   enumeration type, there exist candidate operator functions of the form
8110   //
8111   //        T        operator?(bool, T, T);
8112   //
8113   void addConditionalOperatorOverloads() {
8114     /// Set of (canonical) types that we've already handled.
8115     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8116 
8117     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8118       for (BuiltinCandidateTypeSet::iterator
8119                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8120              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8121            Ptr != PtrEnd; ++Ptr) {
8122         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8123           continue;
8124 
8125         QualType ParamTypes[2] = { *Ptr, *Ptr };
8126         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8127       }
8128 
8129       for (BuiltinCandidateTypeSet::iterator
8130                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8131              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8132            MemPtr != MemPtrEnd; ++MemPtr) {
8133         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8134           continue;
8135 
8136         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8137         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8138       }
8139 
8140       if (S.getLangOpts().CPlusPlus11) {
8141         for (BuiltinCandidateTypeSet::iterator
8142                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8143                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8144              Enum != EnumEnd; ++Enum) {
8145           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8146             continue;
8147 
8148           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8149             continue;
8150 
8151           QualType ParamTypes[2] = { *Enum, *Enum };
8152           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8153         }
8154       }
8155     }
8156   }
8157 };
8158 
8159 } // end anonymous namespace
8160 
8161 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8162 /// operator overloads to the candidate set (C++ [over.built]), based
8163 /// on the operator @p Op and the arguments given. For example, if the
8164 /// operator is a binary '+', this routine might add "int
8165 /// operator+(int, int)" to cover integer addition.
8166 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8167                                         SourceLocation OpLoc,
8168                                         ArrayRef<Expr *> Args,
8169                                         OverloadCandidateSet &CandidateSet) {
8170   // Find all of the types that the arguments can convert to, but only
8171   // if the operator we're looking at has built-in operator candidates
8172   // that make use of these types. Also record whether we encounter non-record
8173   // candidate types or either arithmetic or enumeral candidate types.
8174   Qualifiers VisibleTypeConversionsQuals;
8175   VisibleTypeConversionsQuals.addConst();
8176   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8177     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8178 
8179   bool HasNonRecordCandidateType = false;
8180   bool HasArithmeticOrEnumeralCandidateType = false;
8181   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8182   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8183     CandidateTypes.emplace_back(*this);
8184     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8185                                                  OpLoc,
8186                                                  true,
8187                                                  (Op == OO_Exclaim ||
8188                                                   Op == OO_AmpAmp ||
8189                                                   Op == OO_PipePipe),
8190                                                  VisibleTypeConversionsQuals);
8191     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8192         CandidateTypes[ArgIdx].hasNonRecordTypes();
8193     HasArithmeticOrEnumeralCandidateType =
8194         HasArithmeticOrEnumeralCandidateType ||
8195         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8196   }
8197 
8198   // Exit early when no non-record types have been added to the candidate set
8199   // for any of the arguments to the operator.
8200   //
8201   // We can't exit early for !, ||, or &&, since there we have always have
8202   // 'bool' overloads.
8203   if (!HasNonRecordCandidateType &&
8204       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8205     return;
8206 
8207   // Setup an object to manage the common state for building overloads.
8208   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8209                                            VisibleTypeConversionsQuals,
8210                                            HasArithmeticOrEnumeralCandidateType,
8211                                            CandidateTypes, CandidateSet);
8212 
8213   // Dispatch over the operation to add in only those overloads which apply.
8214   switch (Op) {
8215   case OO_None:
8216   case NUM_OVERLOADED_OPERATORS:
8217     llvm_unreachable("Expected an overloaded operator");
8218 
8219   case OO_New:
8220   case OO_Delete:
8221   case OO_Array_New:
8222   case OO_Array_Delete:
8223   case OO_Call:
8224     llvm_unreachable(
8225                     "Special operators don't use AddBuiltinOperatorCandidates");
8226 
8227   case OO_Comma:
8228   case OO_Arrow:
8229     // C++ [over.match.oper]p3:
8230     //   -- For the operator ',', the unary operator '&', or the
8231     //      operator '->', the built-in candidates set is empty.
8232     break;
8233 
8234   case OO_Plus: // '+' is either unary or binary
8235     if (Args.size() == 1)
8236       OpBuilder.addUnaryPlusPointerOverloads();
8237     // Fall through.
8238 
8239   case OO_Minus: // '-' is either unary or binary
8240     if (Args.size() == 1) {
8241       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8242     } else {
8243       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8244       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8245     }
8246     break;
8247 
8248   case OO_Star: // '*' is either unary or binary
8249     if (Args.size() == 1)
8250       OpBuilder.addUnaryStarPointerOverloads();
8251     else
8252       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8253     break;
8254 
8255   case OO_Slash:
8256     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8257     break;
8258 
8259   case OO_PlusPlus:
8260   case OO_MinusMinus:
8261     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8262     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8263     break;
8264 
8265   case OO_EqualEqual:
8266   case OO_ExclaimEqual:
8267     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8268     // Fall through.
8269 
8270   case OO_Less:
8271   case OO_Greater:
8272   case OO_LessEqual:
8273   case OO_GreaterEqual:
8274     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8275     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8276     break;
8277 
8278   case OO_Percent:
8279   case OO_Caret:
8280   case OO_Pipe:
8281   case OO_LessLess:
8282   case OO_GreaterGreater:
8283     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8284     break;
8285 
8286   case OO_Amp: // '&' is either unary or binary
8287     if (Args.size() == 1)
8288       // C++ [over.match.oper]p3:
8289       //   -- For the operator ',', the unary operator '&', or the
8290       //      operator '->', the built-in candidates set is empty.
8291       break;
8292 
8293     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8294     break;
8295 
8296   case OO_Tilde:
8297     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8298     break;
8299 
8300   case OO_Equal:
8301     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8302     // Fall through.
8303 
8304   case OO_PlusEqual:
8305   case OO_MinusEqual:
8306     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8307     // Fall through.
8308 
8309   case OO_StarEqual:
8310   case OO_SlashEqual:
8311     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8312     break;
8313 
8314   case OO_PercentEqual:
8315   case OO_LessLessEqual:
8316   case OO_GreaterGreaterEqual:
8317   case OO_AmpEqual:
8318   case OO_CaretEqual:
8319   case OO_PipeEqual:
8320     OpBuilder.addAssignmentIntegralOverloads();
8321     break;
8322 
8323   case OO_Exclaim:
8324     OpBuilder.addExclaimOverload();
8325     break;
8326 
8327   case OO_AmpAmp:
8328   case OO_PipePipe:
8329     OpBuilder.addAmpAmpOrPipePipeOverload();
8330     break;
8331 
8332   case OO_Subscript:
8333     OpBuilder.addSubscriptOverloads();
8334     break;
8335 
8336   case OO_ArrowStar:
8337     OpBuilder.addArrowStarOverloads();
8338     break;
8339 
8340   case OO_Conditional:
8341     OpBuilder.addConditionalOperatorOverloads();
8342     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8343     break;
8344   }
8345 }
8346 
8347 /// \brief Add function candidates found via argument-dependent lookup
8348 /// to the set of overloading candidates.
8349 ///
8350 /// This routine performs argument-dependent name lookup based on the
8351 /// given function name (which may also be an operator name) and adds
8352 /// all of the overload candidates found by ADL to the overload
8353 /// candidate set (C++ [basic.lookup.argdep]).
8354 void
8355 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8356                                            SourceLocation Loc,
8357                                            ArrayRef<Expr *> Args,
8358                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8359                                            OverloadCandidateSet& CandidateSet,
8360                                            bool PartialOverloading) {
8361   ADLResult Fns;
8362 
8363   // FIXME: This approach for uniquing ADL results (and removing
8364   // redundant candidates from the set) relies on pointer-equality,
8365   // which means we need to key off the canonical decl.  However,
8366   // always going back to the canonical decl might not get us the
8367   // right set of default arguments.  What default arguments are
8368   // we supposed to consider on ADL candidates, anyway?
8369 
8370   // FIXME: Pass in the explicit template arguments?
8371   ArgumentDependentLookup(Name, Loc, Args, Fns);
8372 
8373   // Erase all of the candidates we already knew about.
8374   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8375                                    CandEnd = CandidateSet.end();
8376        Cand != CandEnd; ++Cand)
8377     if (Cand->Function) {
8378       Fns.erase(Cand->Function);
8379       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8380         Fns.erase(FunTmpl);
8381     }
8382 
8383   // For each of the ADL candidates we found, add it to the overload
8384   // set.
8385   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8386     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8387     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8388       if (ExplicitTemplateArgs)
8389         continue;
8390 
8391       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8392                            PartialOverloading);
8393     } else
8394       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8395                                    FoundDecl, ExplicitTemplateArgs,
8396                                    Args, CandidateSet, PartialOverloading);
8397   }
8398 }
8399 
8400 /// isBetterOverloadCandidate - Determines whether the first overload
8401 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8402 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8403                                       const OverloadCandidate &Cand2,
8404                                       SourceLocation Loc,
8405                                       bool UserDefinedConversion) {
8406   // Define viable functions to be better candidates than non-viable
8407   // functions.
8408   if (!Cand2.Viable)
8409     return Cand1.Viable;
8410   else if (!Cand1.Viable)
8411     return false;
8412 
8413   // C++ [over.match.best]p1:
8414   //
8415   //   -- if F is a static member function, ICS1(F) is defined such
8416   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8417   //      any function G, and, symmetrically, ICS1(G) is neither
8418   //      better nor worse than ICS1(F).
8419   unsigned StartArg = 0;
8420   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8421     StartArg = 1;
8422 
8423   // C++ [over.match.best]p1:
8424   //   A viable function F1 is defined to be a better function than another
8425   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8426   //   conversion sequence than ICSi(F2), and then...
8427   unsigned NumArgs = Cand1.NumConversions;
8428   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8429   bool HasBetterConversion = false;
8430   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8431     switch (CompareImplicitConversionSequences(S,
8432                                                Cand1.Conversions[ArgIdx],
8433                                                Cand2.Conversions[ArgIdx])) {
8434     case ImplicitConversionSequence::Better:
8435       // Cand1 has a better conversion sequence.
8436       HasBetterConversion = true;
8437       break;
8438 
8439     case ImplicitConversionSequence::Worse:
8440       // Cand1 can't be better than Cand2.
8441       return false;
8442 
8443     case ImplicitConversionSequence::Indistinguishable:
8444       // Do nothing.
8445       break;
8446     }
8447   }
8448 
8449   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8450   //       ICSj(F2), or, if not that,
8451   if (HasBetterConversion)
8452     return true;
8453 
8454   //   -- the context is an initialization by user-defined conversion
8455   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8456   //      from the return type of F1 to the destination type (i.e.,
8457   //      the type of the entity being initialized) is a better
8458   //      conversion sequence than the standard conversion sequence
8459   //      from the return type of F2 to the destination type.
8460   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8461       isa<CXXConversionDecl>(Cand1.Function) &&
8462       isa<CXXConversionDecl>(Cand2.Function)) {
8463     // First check whether we prefer one of the conversion functions over the
8464     // other. This only distinguishes the results in non-standard, extension
8465     // cases such as the conversion from a lambda closure type to a function
8466     // pointer or block.
8467     ImplicitConversionSequence::CompareKind Result =
8468         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8469     if (Result == ImplicitConversionSequence::Indistinguishable)
8470       Result = CompareStandardConversionSequences(S,
8471                                                   Cand1.FinalConversion,
8472                                                   Cand2.FinalConversion);
8473 
8474     if (Result != ImplicitConversionSequence::Indistinguishable)
8475       return Result == ImplicitConversionSequence::Better;
8476 
8477     // FIXME: Compare kind of reference binding if conversion functions
8478     // convert to a reference type used in direct reference binding, per
8479     // C++14 [over.match.best]p1 section 2 bullet 3.
8480   }
8481 
8482   //    -- F1 is a non-template function and F2 is a function template
8483   //       specialization, or, if not that,
8484   bool Cand1IsSpecialization = Cand1.Function &&
8485                                Cand1.Function->getPrimaryTemplate();
8486   bool Cand2IsSpecialization = Cand2.Function &&
8487                                Cand2.Function->getPrimaryTemplate();
8488   if (Cand1IsSpecialization != Cand2IsSpecialization)
8489     return Cand2IsSpecialization;
8490 
8491   //   -- F1 and F2 are function template specializations, and the function
8492   //      template for F1 is more specialized than the template for F2
8493   //      according to the partial ordering rules described in 14.5.5.2, or,
8494   //      if not that,
8495   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8496     if (FunctionTemplateDecl *BetterTemplate
8497           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8498                                          Cand2.Function->getPrimaryTemplate(),
8499                                          Loc,
8500                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8501                                                              : TPOC_Call,
8502                                          Cand1.ExplicitCallArguments,
8503                                          Cand2.ExplicitCallArguments))
8504       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8505   }
8506 
8507   // Check for enable_if value-based overload resolution.
8508   if (Cand1.Function && Cand2.Function &&
8509       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8510        Cand2.Function->hasAttr<EnableIfAttr>())) {
8511     // FIXME: The next several lines are just
8512     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8513     // instead of reverse order which is how they're stored in the AST.
8514     AttrVec Cand1Attrs;
8515     if (Cand1.Function->hasAttrs()) {
8516       Cand1Attrs = Cand1.Function->getAttrs();
8517       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8518                                       IsNotEnableIfAttr),
8519                        Cand1Attrs.end());
8520       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8521     }
8522 
8523     AttrVec Cand2Attrs;
8524     if (Cand2.Function->hasAttrs()) {
8525       Cand2Attrs = Cand2.Function->getAttrs();
8526       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8527                                       IsNotEnableIfAttr),
8528                        Cand2Attrs.end());
8529       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8530     }
8531 
8532     // Candidate 1 is better if it has strictly more attributes and
8533     // the common sequence is identical.
8534     if (Cand1Attrs.size() <= Cand2Attrs.size())
8535       return false;
8536 
8537     auto Cand1I = Cand1Attrs.begin();
8538     for (auto &Cand2A : Cand2Attrs) {
8539       auto &Cand1A = *Cand1I++;
8540       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8541       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8542                                                      S.getASTContext(), true);
8543       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8544                                                      S.getASTContext(), true);
8545       if (Cand1ID != Cand2ID)
8546         return false;
8547     }
8548 
8549     return true;
8550   }
8551 
8552   if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8553       Cand1.Function && Cand2.Function) {
8554     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8555     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8556            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8557   }
8558 
8559   return false;
8560 }
8561 
8562 /// \brief Computes the best viable function (C++ 13.3.3)
8563 /// within an overload candidate set.
8564 ///
8565 /// \param Loc The location of the function name (or operator symbol) for
8566 /// which overload resolution occurs.
8567 ///
8568 /// \param Best If overload resolution was successful or found a deleted
8569 /// function, \p Best points to the candidate function found.
8570 ///
8571 /// \returns The result of overload resolution.
8572 OverloadingResult
8573 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8574                                          iterator &Best,
8575                                          bool UserDefinedConversion) {
8576   // Find the best viable function.
8577   Best = end();
8578   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8579     if (Cand->Viable)
8580       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8581                                                      UserDefinedConversion))
8582         Best = Cand;
8583   }
8584 
8585   // If we didn't find any viable functions, abort.
8586   if (Best == end())
8587     return OR_No_Viable_Function;
8588 
8589   // Make sure that this function is better than every other viable
8590   // function. If not, we have an ambiguity.
8591   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8592     if (Cand->Viable &&
8593         Cand != Best &&
8594         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8595                                    UserDefinedConversion)) {
8596       Best = end();
8597       return OR_Ambiguous;
8598     }
8599   }
8600 
8601   // Best is the best viable function.
8602   if (Best->Function &&
8603       (Best->Function->isDeleted() ||
8604        S.isFunctionConsideredUnavailable(Best->Function)))
8605     return OR_Deleted;
8606 
8607   return OR_Success;
8608 }
8609 
8610 namespace {
8611 
8612 enum OverloadCandidateKind {
8613   oc_function,
8614   oc_method,
8615   oc_constructor,
8616   oc_function_template,
8617   oc_method_template,
8618   oc_constructor_template,
8619   oc_implicit_default_constructor,
8620   oc_implicit_copy_constructor,
8621   oc_implicit_move_constructor,
8622   oc_implicit_copy_assignment,
8623   oc_implicit_move_assignment,
8624   oc_implicit_inherited_constructor
8625 };
8626 
8627 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8628                                                 FunctionDecl *Fn,
8629                                                 std::string &Description) {
8630   bool isTemplate = false;
8631 
8632   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8633     isTemplate = true;
8634     Description = S.getTemplateArgumentBindingsText(
8635       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8636   }
8637 
8638   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8639     if (!Ctor->isImplicit())
8640       return isTemplate ? oc_constructor_template : oc_constructor;
8641 
8642     if (Ctor->getInheritedConstructor())
8643       return oc_implicit_inherited_constructor;
8644 
8645     if (Ctor->isDefaultConstructor())
8646       return oc_implicit_default_constructor;
8647 
8648     if (Ctor->isMoveConstructor())
8649       return oc_implicit_move_constructor;
8650 
8651     assert(Ctor->isCopyConstructor() &&
8652            "unexpected sort of implicit constructor");
8653     return oc_implicit_copy_constructor;
8654   }
8655 
8656   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8657     // This actually gets spelled 'candidate function' for now, but
8658     // it doesn't hurt to split it out.
8659     if (!Meth->isImplicit())
8660       return isTemplate ? oc_method_template : oc_method;
8661 
8662     if (Meth->isMoveAssignmentOperator())
8663       return oc_implicit_move_assignment;
8664 
8665     if (Meth->isCopyAssignmentOperator())
8666       return oc_implicit_copy_assignment;
8667 
8668     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8669     return oc_method;
8670   }
8671 
8672   return isTemplate ? oc_function_template : oc_function;
8673 }
8674 
8675 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8676   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8677   if (!Ctor) return;
8678 
8679   Ctor = Ctor->getInheritedConstructor();
8680   if (!Ctor) return;
8681 
8682   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8683 }
8684 
8685 } // end anonymous namespace
8686 
8687 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8688                                     const FunctionDecl *FD) {
8689   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8690     bool AlwaysTrue;
8691     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8692       return false;
8693     if (!AlwaysTrue)
8694       return false;
8695   }
8696   return true;
8697 }
8698 
8699 // Notes the location of an overload candidate.
8700 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8701                                  bool TakingAddress) {
8702   std::string FnDesc;
8703   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8704   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8705                              << (unsigned) K << FnDesc;
8706   if (TakingAddress && !isFunctionAlwaysEnabled(Context, Fn))
8707     PD << ft_addr_enable_if;
8708   else
8709     HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8710   Diag(Fn->getLocation(), PD);
8711   MaybeEmitInheritedConstructorNote(*this, Fn);
8712 }
8713 
8714 // Notes the location of all overload candidates designated through
8715 // OverloadedExpr
8716 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8717                                      bool TakingAddress) {
8718   assert(OverloadedExpr->getType() == Context.OverloadTy);
8719 
8720   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8721   OverloadExpr *OvlExpr = Ovl.Expression;
8722 
8723   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8724                             IEnd = OvlExpr->decls_end();
8725        I != IEnd; ++I) {
8726     if (FunctionTemplateDecl *FunTmpl =
8727                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8728       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8729                             TakingAddress);
8730     } else if (FunctionDecl *Fun
8731                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8732       NoteOverloadCandidate(Fun, DestType, TakingAddress);
8733     }
8734   }
8735 }
8736 
8737 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8738 /// "lead" diagnostic; it will be given two arguments, the source and
8739 /// target types of the conversion.
8740 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8741                                  Sema &S,
8742                                  SourceLocation CaretLoc,
8743                                  const PartialDiagnostic &PDiag) const {
8744   S.Diag(CaretLoc, PDiag)
8745     << Ambiguous.getFromType() << Ambiguous.getToType();
8746   // FIXME: The note limiting machinery is borrowed from
8747   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8748   // refactoring here.
8749   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8750   unsigned CandsShown = 0;
8751   AmbiguousConversionSequence::const_iterator I, E;
8752   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8753     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8754       break;
8755     ++CandsShown;
8756     S.NoteOverloadCandidate(*I);
8757   }
8758   if (I != E)
8759     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8760 }
8761 
8762 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8763                                   unsigned I) {
8764   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8765   assert(Conv.isBad());
8766   assert(Cand->Function && "for now, candidate must be a function");
8767   FunctionDecl *Fn = Cand->Function;
8768 
8769   // There's a conversion slot for the object argument if this is a
8770   // non-constructor method.  Note that 'I' corresponds the
8771   // conversion-slot index.
8772   bool isObjectArgument = false;
8773   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8774     if (I == 0)
8775       isObjectArgument = true;
8776     else
8777       I--;
8778   }
8779 
8780   std::string FnDesc;
8781   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8782 
8783   Expr *FromExpr = Conv.Bad.FromExpr;
8784   QualType FromTy = Conv.Bad.getFromType();
8785   QualType ToTy = Conv.Bad.getToType();
8786 
8787   if (FromTy == S.Context.OverloadTy) {
8788     assert(FromExpr && "overload set argument came from implicit argument?");
8789     Expr *E = FromExpr->IgnoreParens();
8790     if (isa<UnaryOperator>(E))
8791       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8792     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8793 
8794     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8795       << (unsigned) FnKind << FnDesc
8796       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8797       << ToTy << Name << I+1;
8798     MaybeEmitInheritedConstructorNote(S, Fn);
8799     return;
8800   }
8801 
8802   // Do some hand-waving analysis to see if the non-viability is due
8803   // to a qualifier mismatch.
8804   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8805   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8806   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8807     CToTy = RT->getPointeeType();
8808   else {
8809     // TODO: detect and diagnose the full richness of const mismatches.
8810     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8811       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8812         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8813   }
8814 
8815   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8816       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8817     Qualifiers FromQs = CFromTy.getQualifiers();
8818     Qualifiers ToQs = CToTy.getQualifiers();
8819 
8820     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8821       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8822         << (unsigned) FnKind << FnDesc
8823         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8824         << FromTy
8825         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8826         << (unsigned) isObjectArgument << I+1;
8827       MaybeEmitInheritedConstructorNote(S, Fn);
8828       return;
8829     }
8830 
8831     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8832       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8833         << (unsigned) FnKind << FnDesc
8834         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8835         << FromTy
8836         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8837         << (unsigned) isObjectArgument << I+1;
8838       MaybeEmitInheritedConstructorNote(S, Fn);
8839       return;
8840     }
8841 
8842     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8843       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8844       << (unsigned) FnKind << FnDesc
8845       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8846       << FromTy
8847       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8848       << (unsigned) isObjectArgument << I+1;
8849       MaybeEmitInheritedConstructorNote(S, Fn);
8850       return;
8851     }
8852 
8853     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8854     assert(CVR && "unexpected qualifiers mismatch");
8855 
8856     if (isObjectArgument) {
8857       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8858         << (unsigned) FnKind << FnDesc
8859         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8860         << FromTy << (CVR - 1);
8861     } else {
8862       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8863         << (unsigned) FnKind << FnDesc
8864         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8865         << FromTy << (CVR - 1) << I+1;
8866     }
8867     MaybeEmitInheritedConstructorNote(S, Fn);
8868     return;
8869   }
8870 
8871   // Special diagnostic for failure to convert an initializer list, since
8872   // telling the user that it has type void is not useful.
8873   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8874     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8875       << (unsigned) FnKind << FnDesc
8876       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8877       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8878     MaybeEmitInheritedConstructorNote(S, Fn);
8879     return;
8880   }
8881 
8882   // Diagnose references or pointers to incomplete types differently,
8883   // since it's far from impossible that the incompleteness triggered
8884   // the failure.
8885   QualType TempFromTy = FromTy.getNonReferenceType();
8886   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8887     TempFromTy = PTy->getPointeeType();
8888   if (TempFromTy->isIncompleteType()) {
8889     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8890       << (unsigned) FnKind << FnDesc
8891       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8892       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8893     MaybeEmitInheritedConstructorNote(S, Fn);
8894     return;
8895   }
8896 
8897   // Diagnose base -> derived pointer conversions.
8898   unsigned BaseToDerivedConversion = 0;
8899   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8900     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8901       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8902                                                FromPtrTy->getPointeeType()) &&
8903           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8904           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8905           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8906                           FromPtrTy->getPointeeType()))
8907         BaseToDerivedConversion = 1;
8908     }
8909   } else if (const ObjCObjectPointerType *FromPtrTy
8910                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8911     if (const ObjCObjectPointerType *ToPtrTy
8912                                         = ToTy->getAs<ObjCObjectPointerType>())
8913       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8914         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8915           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8916                                                 FromPtrTy->getPointeeType()) &&
8917               FromIface->isSuperClassOf(ToIface))
8918             BaseToDerivedConversion = 2;
8919   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8920     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8921         !FromTy->isIncompleteType() &&
8922         !ToRefTy->getPointeeType()->isIncompleteType() &&
8923         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8924       BaseToDerivedConversion = 3;
8925     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8926                ToTy.getNonReferenceType().getCanonicalType() ==
8927                FromTy.getNonReferenceType().getCanonicalType()) {
8928       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8929         << (unsigned) FnKind << FnDesc
8930         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8931         << (unsigned) isObjectArgument << I + 1;
8932       MaybeEmitInheritedConstructorNote(S, Fn);
8933       return;
8934     }
8935   }
8936 
8937   if (BaseToDerivedConversion) {
8938     S.Diag(Fn->getLocation(),
8939            diag::note_ovl_candidate_bad_base_to_derived_conv)
8940       << (unsigned) FnKind << FnDesc
8941       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8942       << (BaseToDerivedConversion - 1)
8943       << FromTy << ToTy << I+1;
8944     MaybeEmitInheritedConstructorNote(S, Fn);
8945     return;
8946   }
8947 
8948   if (isa<ObjCObjectPointerType>(CFromTy) &&
8949       isa<PointerType>(CToTy)) {
8950       Qualifiers FromQs = CFromTy.getQualifiers();
8951       Qualifiers ToQs = CToTy.getQualifiers();
8952       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8953         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8954         << (unsigned) FnKind << FnDesc
8955         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8956         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8957         MaybeEmitInheritedConstructorNote(S, Fn);
8958         return;
8959       }
8960   }
8961 
8962   // Emit the generic diagnostic and, optionally, add the hints to it.
8963   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8964   FDiag << (unsigned) FnKind << FnDesc
8965     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8966     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8967     << (unsigned) (Cand->Fix.Kind);
8968 
8969   // If we can fix the conversion, suggest the FixIts.
8970   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8971        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8972     FDiag << *HI;
8973   S.Diag(Fn->getLocation(), FDiag);
8974 
8975   MaybeEmitInheritedConstructorNote(S, Fn);
8976 }
8977 
8978 /// Additional arity mismatch diagnosis specific to a function overload
8979 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8980 /// over a candidate in any candidate set.
8981 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8982                                unsigned NumArgs) {
8983   FunctionDecl *Fn = Cand->Function;
8984   unsigned MinParams = Fn->getMinRequiredArguments();
8985 
8986   // With invalid overloaded operators, it's possible that we think we
8987   // have an arity mismatch when in fact it looks like we have the
8988   // right number of arguments, because only overloaded operators have
8989   // the weird behavior of overloading member and non-member functions.
8990   // Just don't report anything.
8991   if (Fn->isInvalidDecl() &&
8992       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8993     return true;
8994 
8995   if (NumArgs < MinParams) {
8996     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8997            (Cand->FailureKind == ovl_fail_bad_deduction &&
8998             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8999   } else {
9000     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9001            (Cand->FailureKind == ovl_fail_bad_deduction &&
9002             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9003   }
9004 
9005   return false;
9006 }
9007 
9008 /// General arity mismatch diagnosis over a candidate in a candidate set.
9009 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
9010   assert(isa<FunctionDecl>(D) &&
9011       "The templated declaration should at least be a function"
9012       " when diagnosing bad template argument deduction due to too many"
9013       " or too few arguments");
9014 
9015   FunctionDecl *Fn = cast<FunctionDecl>(D);
9016 
9017   // TODO: treat calls to a missing default constructor as a special case
9018   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9019   unsigned MinParams = Fn->getMinRequiredArguments();
9020 
9021   // at least / at most / exactly
9022   unsigned mode, modeCount;
9023   if (NumFormalArgs < MinParams) {
9024     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9025         FnTy->isTemplateVariadic())
9026       mode = 0; // "at least"
9027     else
9028       mode = 2; // "exactly"
9029     modeCount = MinParams;
9030   } else {
9031     if (MinParams != FnTy->getNumParams())
9032       mode = 1; // "at most"
9033     else
9034       mode = 2; // "exactly"
9035     modeCount = FnTy->getNumParams();
9036   }
9037 
9038   std::string Description;
9039   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9040 
9041   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9042     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9043       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9044       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9045   else
9046     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9047       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9048       << mode << modeCount << NumFormalArgs;
9049   MaybeEmitInheritedConstructorNote(S, Fn);
9050 }
9051 
9052 /// Arity mismatch diagnosis specific to a function overload candidate.
9053 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9054                                   unsigned NumFormalArgs) {
9055   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9056     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9057 }
9058 
9059 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9060   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9061     return FD->getDescribedFunctionTemplate();
9062   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9063     return RD->getDescribedClassTemplate();
9064 
9065   llvm_unreachable("Unsupported: Getting the described template declaration"
9066                    " for bad deduction diagnosis");
9067 }
9068 
9069 /// Diagnose a failed template-argument deduction.
9070 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9071                                  DeductionFailureInfo &DeductionFailure,
9072                                  unsigned NumArgs) {
9073   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9074   NamedDecl *ParamD;
9075   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9076   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9077   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9078   switch (DeductionFailure.Result) {
9079   case Sema::TDK_Success:
9080     llvm_unreachable("TDK_success while diagnosing bad deduction");
9081 
9082   case Sema::TDK_Incomplete: {
9083     assert(ParamD && "no parameter found for incomplete deduction result");
9084     S.Diag(Templated->getLocation(),
9085            diag::note_ovl_candidate_incomplete_deduction)
9086         << ParamD->getDeclName();
9087     MaybeEmitInheritedConstructorNote(S, Templated);
9088     return;
9089   }
9090 
9091   case Sema::TDK_Underqualified: {
9092     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9093     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9094 
9095     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9096 
9097     // Param will have been canonicalized, but it should just be a
9098     // qualified version of ParamD, so move the qualifiers to that.
9099     QualifierCollector Qs;
9100     Qs.strip(Param);
9101     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9102     assert(S.Context.hasSameType(Param, NonCanonParam));
9103 
9104     // Arg has also been canonicalized, but there's nothing we can do
9105     // about that.  It also doesn't matter as much, because it won't
9106     // have any template parameters in it (because deduction isn't
9107     // done on dependent types).
9108     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9109 
9110     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9111         << ParamD->getDeclName() << Arg << NonCanonParam;
9112     MaybeEmitInheritedConstructorNote(S, Templated);
9113     return;
9114   }
9115 
9116   case Sema::TDK_Inconsistent: {
9117     assert(ParamD && "no parameter found for inconsistent deduction result");
9118     int which = 0;
9119     if (isa<TemplateTypeParmDecl>(ParamD))
9120       which = 0;
9121     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9122       which = 1;
9123     else {
9124       which = 2;
9125     }
9126 
9127     S.Diag(Templated->getLocation(),
9128            diag::note_ovl_candidate_inconsistent_deduction)
9129         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9130         << *DeductionFailure.getSecondArg();
9131     MaybeEmitInheritedConstructorNote(S, Templated);
9132     return;
9133   }
9134 
9135   case Sema::TDK_InvalidExplicitArguments:
9136     assert(ParamD && "no parameter found for invalid explicit arguments");
9137     if (ParamD->getDeclName())
9138       S.Diag(Templated->getLocation(),
9139              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9140           << ParamD->getDeclName();
9141     else {
9142       int index = 0;
9143       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9144         index = TTP->getIndex();
9145       else if (NonTypeTemplateParmDecl *NTTP
9146                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9147         index = NTTP->getIndex();
9148       else
9149         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9150       S.Diag(Templated->getLocation(),
9151              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9152           << (index + 1);
9153     }
9154     MaybeEmitInheritedConstructorNote(S, Templated);
9155     return;
9156 
9157   case Sema::TDK_TooManyArguments:
9158   case Sema::TDK_TooFewArguments:
9159     DiagnoseArityMismatch(S, Templated, NumArgs);
9160     return;
9161 
9162   case Sema::TDK_InstantiationDepth:
9163     S.Diag(Templated->getLocation(),
9164            diag::note_ovl_candidate_instantiation_depth);
9165     MaybeEmitInheritedConstructorNote(S, Templated);
9166     return;
9167 
9168   case Sema::TDK_SubstitutionFailure: {
9169     // Format the template argument list into the argument string.
9170     SmallString<128> TemplateArgString;
9171     if (TemplateArgumentList *Args =
9172             DeductionFailure.getTemplateArgumentList()) {
9173       TemplateArgString = " ";
9174       TemplateArgString += S.getTemplateArgumentBindingsText(
9175           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9176     }
9177 
9178     // If this candidate was disabled by enable_if, say so.
9179     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9180     if (PDiag && PDiag->second.getDiagID() ==
9181           diag::err_typename_nested_not_found_enable_if) {
9182       // FIXME: Use the source range of the condition, and the fully-qualified
9183       //        name of the enable_if template. These are both present in PDiag.
9184       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9185         << "'enable_if'" << TemplateArgString;
9186       return;
9187     }
9188 
9189     // Format the SFINAE diagnostic into the argument string.
9190     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9191     //        formatted message in another diagnostic.
9192     SmallString<128> SFINAEArgString;
9193     SourceRange R;
9194     if (PDiag) {
9195       SFINAEArgString = ": ";
9196       R = SourceRange(PDiag->first, PDiag->first);
9197       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9198     }
9199 
9200     S.Diag(Templated->getLocation(),
9201            diag::note_ovl_candidate_substitution_failure)
9202         << TemplateArgString << SFINAEArgString << R;
9203     MaybeEmitInheritedConstructorNote(S, Templated);
9204     return;
9205   }
9206 
9207   case Sema::TDK_FailedOverloadResolution: {
9208     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9209     S.Diag(Templated->getLocation(),
9210            diag::note_ovl_candidate_failed_overload_resolution)
9211         << R.Expression->getName();
9212     return;
9213   }
9214 
9215   case Sema::TDK_NonDeducedMismatch: {
9216     // FIXME: Provide a source location to indicate what we couldn't match.
9217     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9218     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9219     if (FirstTA.getKind() == TemplateArgument::Template &&
9220         SecondTA.getKind() == TemplateArgument::Template) {
9221       TemplateName FirstTN = FirstTA.getAsTemplate();
9222       TemplateName SecondTN = SecondTA.getAsTemplate();
9223       if (FirstTN.getKind() == TemplateName::Template &&
9224           SecondTN.getKind() == TemplateName::Template) {
9225         if (FirstTN.getAsTemplateDecl()->getName() ==
9226             SecondTN.getAsTemplateDecl()->getName()) {
9227           // FIXME: This fixes a bad diagnostic where both templates are named
9228           // the same.  This particular case is a bit difficult since:
9229           // 1) It is passed as a string to the diagnostic printer.
9230           // 2) The diagnostic printer only attempts to find a better
9231           //    name for types, not decls.
9232           // Ideally, this should folded into the diagnostic printer.
9233           S.Diag(Templated->getLocation(),
9234                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9235               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9236           return;
9237         }
9238       }
9239     }
9240     // FIXME: For generic lambda parameters, check if the function is a lambda
9241     // call operator, and if so, emit a prettier and more informative
9242     // diagnostic that mentions 'auto' and lambda in addition to
9243     // (or instead of?) the canonical template type parameters.
9244     S.Diag(Templated->getLocation(),
9245            diag::note_ovl_candidate_non_deduced_mismatch)
9246         << FirstTA << SecondTA;
9247     return;
9248   }
9249   // TODO: diagnose these individually, then kill off
9250   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9251   case Sema::TDK_MiscellaneousDeductionFailure:
9252     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9253     MaybeEmitInheritedConstructorNote(S, Templated);
9254     return;
9255   }
9256 }
9257 
9258 /// Diagnose a failed template-argument deduction, for function calls.
9259 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9260                                  unsigned NumArgs) {
9261   unsigned TDK = Cand->DeductionFailure.Result;
9262   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9263     if (CheckArityMismatch(S, Cand, NumArgs))
9264       return;
9265   }
9266   DiagnoseBadDeduction(S, Cand->Function, // pattern
9267                        Cand->DeductionFailure, NumArgs);
9268 }
9269 
9270 /// CUDA: diagnose an invalid call across targets.
9271 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9272   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9273   FunctionDecl *Callee = Cand->Function;
9274 
9275   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9276                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9277 
9278   std::string FnDesc;
9279   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9280 
9281   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9282       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9283 
9284   // This could be an implicit constructor for which we could not infer the
9285   // target due to a collsion. Diagnose that case.
9286   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9287   if (Meth != nullptr && Meth->isImplicit()) {
9288     CXXRecordDecl *ParentClass = Meth->getParent();
9289     Sema::CXXSpecialMember CSM;
9290 
9291     switch (FnKind) {
9292     default:
9293       return;
9294     case oc_implicit_default_constructor:
9295       CSM = Sema::CXXDefaultConstructor;
9296       break;
9297     case oc_implicit_copy_constructor:
9298       CSM = Sema::CXXCopyConstructor;
9299       break;
9300     case oc_implicit_move_constructor:
9301       CSM = Sema::CXXMoveConstructor;
9302       break;
9303     case oc_implicit_copy_assignment:
9304       CSM = Sema::CXXCopyAssignment;
9305       break;
9306     case oc_implicit_move_assignment:
9307       CSM = Sema::CXXMoveAssignment;
9308       break;
9309     };
9310 
9311     bool ConstRHS = false;
9312     if (Meth->getNumParams()) {
9313       if (const ReferenceType *RT =
9314               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9315         ConstRHS = RT->getPointeeType().isConstQualified();
9316       }
9317     }
9318 
9319     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9320                                               /* ConstRHS */ ConstRHS,
9321                                               /* Diagnose */ true);
9322   }
9323 }
9324 
9325 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9326   FunctionDecl *Callee = Cand->Function;
9327   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9328 
9329   S.Diag(Callee->getLocation(),
9330          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9331       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9332 }
9333 
9334 /// Generates a 'note' diagnostic for an overload candidate.  We've
9335 /// already generated a primary error at the call site.
9336 ///
9337 /// It really does need to be a single diagnostic with its caret
9338 /// pointed at the candidate declaration.  Yes, this creates some
9339 /// major challenges of technical writing.  Yes, this makes pointing
9340 /// out problems with specific arguments quite awkward.  It's still
9341 /// better than generating twenty screens of text for every failed
9342 /// overload.
9343 ///
9344 /// It would be great to be able to express per-candidate problems
9345 /// more richly for those diagnostic clients that cared, but we'd
9346 /// still have to be just as careful with the default diagnostics.
9347 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9348                                   unsigned NumArgs) {
9349   FunctionDecl *Fn = Cand->Function;
9350 
9351   // Note deleted candidates, but only if they're viable.
9352   if (Cand->Viable && (Fn->isDeleted() ||
9353       S.isFunctionConsideredUnavailable(Fn))) {
9354     std::string FnDesc;
9355     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9356 
9357     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9358       << FnKind << FnDesc
9359       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9360     MaybeEmitInheritedConstructorNote(S, Fn);
9361     return;
9362   }
9363 
9364   // We don't really have anything else to say about viable candidates.
9365   if (Cand->Viable) {
9366     S.NoteOverloadCandidate(Fn);
9367     return;
9368   }
9369 
9370   switch (Cand->FailureKind) {
9371   case ovl_fail_too_many_arguments:
9372   case ovl_fail_too_few_arguments:
9373     return DiagnoseArityMismatch(S, Cand, NumArgs);
9374 
9375   case ovl_fail_bad_deduction:
9376     return DiagnoseBadDeduction(S, Cand, NumArgs);
9377 
9378   case ovl_fail_illegal_constructor: {
9379     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9380       << (Fn->getPrimaryTemplate() ? 1 : 0);
9381     MaybeEmitInheritedConstructorNote(S, Fn);
9382     return;
9383   }
9384 
9385   case ovl_fail_trivial_conversion:
9386   case ovl_fail_bad_final_conversion:
9387   case ovl_fail_final_conversion_not_exact:
9388     return S.NoteOverloadCandidate(Fn);
9389 
9390   case ovl_fail_bad_conversion: {
9391     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9392     for (unsigned N = Cand->NumConversions; I != N; ++I)
9393       if (Cand->Conversions[I].isBad())
9394         return DiagnoseBadConversion(S, Cand, I);
9395 
9396     // FIXME: this currently happens when we're called from SemaInit
9397     // when user-conversion overload fails.  Figure out how to handle
9398     // those conditions and diagnose them well.
9399     return S.NoteOverloadCandidate(Fn);
9400   }
9401 
9402   case ovl_fail_bad_target:
9403     return DiagnoseBadTarget(S, Cand);
9404 
9405   case ovl_fail_enable_if:
9406     return DiagnoseFailedEnableIfAttr(S, Cand);
9407   }
9408 }
9409 
9410 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9411   // Desugar the type of the surrogate down to a function type,
9412   // retaining as many typedefs as possible while still showing
9413   // the function type (and, therefore, its parameter types).
9414   QualType FnType = Cand->Surrogate->getConversionType();
9415   bool isLValueReference = false;
9416   bool isRValueReference = false;
9417   bool isPointer = false;
9418   if (const LValueReferenceType *FnTypeRef =
9419         FnType->getAs<LValueReferenceType>()) {
9420     FnType = FnTypeRef->getPointeeType();
9421     isLValueReference = true;
9422   } else if (const RValueReferenceType *FnTypeRef =
9423                FnType->getAs<RValueReferenceType>()) {
9424     FnType = FnTypeRef->getPointeeType();
9425     isRValueReference = true;
9426   }
9427   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9428     FnType = FnTypePtr->getPointeeType();
9429     isPointer = true;
9430   }
9431   // Desugar down to a function type.
9432   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9433   // Reconstruct the pointer/reference as appropriate.
9434   if (isPointer) FnType = S.Context.getPointerType(FnType);
9435   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9436   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9437 
9438   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9439     << FnType;
9440   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9441 }
9442 
9443 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9444                                          SourceLocation OpLoc,
9445                                          OverloadCandidate *Cand) {
9446   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9447   std::string TypeStr("operator");
9448   TypeStr += Opc;
9449   TypeStr += "(";
9450   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9451   if (Cand->NumConversions == 1) {
9452     TypeStr += ")";
9453     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9454   } else {
9455     TypeStr += ", ";
9456     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9457     TypeStr += ")";
9458     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9459   }
9460 }
9461 
9462 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9463                                          OverloadCandidate *Cand) {
9464   unsigned NoOperands = Cand->NumConversions;
9465   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9466     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9467     if (ICS.isBad()) break; // all meaningless after first invalid
9468     if (!ICS.isAmbiguous()) continue;
9469 
9470     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9471                               S.PDiag(diag::note_ambiguous_type_conversion));
9472   }
9473 }
9474 
9475 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9476   if (Cand->Function)
9477     return Cand->Function->getLocation();
9478   if (Cand->IsSurrogate)
9479     return Cand->Surrogate->getLocation();
9480   return SourceLocation();
9481 }
9482 
9483 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9484   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9485   case Sema::TDK_Success:
9486     llvm_unreachable("TDK_success while diagnosing bad deduction");
9487 
9488   case Sema::TDK_Invalid:
9489   case Sema::TDK_Incomplete:
9490     return 1;
9491 
9492   case Sema::TDK_Underqualified:
9493   case Sema::TDK_Inconsistent:
9494     return 2;
9495 
9496   case Sema::TDK_SubstitutionFailure:
9497   case Sema::TDK_NonDeducedMismatch:
9498   case Sema::TDK_MiscellaneousDeductionFailure:
9499     return 3;
9500 
9501   case Sema::TDK_InstantiationDepth:
9502   case Sema::TDK_FailedOverloadResolution:
9503     return 4;
9504 
9505   case Sema::TDK_InvalidExplicitArguments:
9506     return 5;
9507 
9508   case Sema::TDK_TooManyArguments:
9509   case Sema::TDK_TooFewArguments:
9510     return 6;
9511   }
9512   llvm_unreachable("Unhandled deduction result");
9513 }
9514 
9515 namespace {
9516 struct CompareOverloadCandidatesForDisplay {
9517   Sema &S;
9518   size_t NumArgs;
9519 
9520   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9521       : S(S), NumArgs(nArgs) {}
9522 
9523   bool operator()(const OverloadCandidate *L,
9524                   const OverloadCandidate *R) {
9525     // Fast-path this check.
9526     if (L == R) return false;
9527 
9528     // Order first by viability.
9529     if (L->Viable) {
9530       if (!R->Viable) return true;
9531 
9532       // TODO: introduce a tri-valued comparison for overload
9533       // candidates.  Would be more worthwhile if we had a sort
9534       // that could exploit it.
9535       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9536       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9537     } else if (R->Viable)
9538       return false;
9539 
9540     assert(L->Viable == R->Viable);
9541 
9542     // Criteria by which we can sort non-viable candidates:
9543     if (!L->Viable) {
9544       // 1. Arity mismatches come after other candidates.
9545       if (L->FailureKind == ovl_fail_too_many_arguments ||
9546           L->FailureKind == ovl_fail_too_few_arguments) {
9547         if (R->FailureKind == ovl_fail_too_many_arguments ||
9548             R->FailureKind == ovl_fail_too_few_arguments) {
9549           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9550           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9551           if (LDist == RDist) {
9552             if (L->FailureKind == R->FailureKind)
9553               // Sort non-surrogates before surrogates.
9554               return !L->IsSurrogate && R->IsSurrogate;
9555             // Sort candidates requiring fewer parameters than there were
9556             // arguments given after candidates requiring more parameters
9557             // than there were arguments given.
9558             return L->FailureKind == ovl_fail_too_many_arguments;
9559           }
9560           return LDist < RDist;
9561         }
9562         return false;
9563       }
9564       if (R->FailureKind == ovl_fail_too_many_arguments ||
9565           R->FailureKind == ovl_fail_too_few_arguments)
9566         return true;
9567 
9568       // 2. Bad conversions come first and are ordered by the number
9569       // of bad conversions and quality of good conversions.
9570       if (L->FailureKind == ovl_fail_bad_conversion) {
9571         if (R->FailureKind != ovl_fail_bad_conversion)
9572           return true;
9573 
9574         // The conversion that can be fixed with a smaller number of changes,
9575         // comes first.
9576         unsigned numLFixes = L->Fix.NumConversionsFixed;
9577         unsigned numRFixes = R->Fix.NumConversionsFixed;
9578         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9579         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9580         if (numLFixes != numRFixes) {
9581           return numLFixes < numRFixes;
9582         }
9583 
9584         // If there's any ordering between the defined conversions...
9585         // FIXME: this might not be transitive.
9586         assert(L->NumConversions == R->NumConversions);
9587 
9588         int leftBetter = 0;
9589         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9590         for (unsigned E = L->NumConversions; I != E; ++I) {
9591           switch (CompareImplicitConversionSequences(S,
9592                                                      L->Conversions[I],
9593                                                      R->Conversions[I])) {
9594           case ImplicitConversionSequence::Better:
9595             leftBetter++;
9596             break;
9597 
9598           case ImplicitConversionSequence::Worse:
9599             leftBetter--;
9600             break;
9601 
9602           case ImplicitConversionSequence::Indistinguishable:
9603             break;
9604           }
9605         }
9606         if (leftBetter > 0) return true;
9607         if (leftBetter < 0) return false;
9608 
9609       } else if (R->FailureKind == ovl_fail_bad_conversion)
9610         return false;
9611 
9612       if (L->FailureKind == ovl_fail_bad_deduction) {
9613         if (R->FailureKind != ovl_fail_bad_deduction)
9614           return true;
9615 
9616         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9617           return RankDeductionFailure(L->DeductionFailure)
9618                < RankDeductionFailure(R->DeductionFailure);
9619       } else if (R->FailureKind == ovl_fail_bad_deduction)
9620         return false;
9621 
9622       // TODO: others?
9623     }
9624 
9625     // Sort everything else by location.
9626     SourceLocation LLoc = GetLocationForCandidate(L);
9627     SourceLocation RLoc = GetLocationForCandidate(R);
9628 
9629     // Put candidates without locations (e.g. builtins) at the end.
9630     if (LLoc.isInvalid()) return false;
9631     if (RLoc.isInvalid()) return true;
9632 
9633     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9634   }
9635 };
9636 }
9637 
9638 /// CompleteNonViableCandidate - Normally, overload resolution only
9639 /// computes up to the first. Produces the FixIt set if possible.
9640 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9641                                        ArrayRef<Expr *> Args) {
9642   assert(!Cand->Viable);
9643 
9644   // Don't do anything on failures other than bad conversion.
9645   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9646 
9647   // We only want the FixIts if all the arguments can be corrected.
9648   bool Unfixable = false;
9649   // Use a implicit copy initialization to check conversion fixes.
9650   Cand->Fix.setConversionChecker(TryCopyInitialization);
9651 
9652   // Skip forward to the first bad conversion.
9653   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9654   unsigned ConvCount = Cand->NumConversions;
9655   while (true) {
9656     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9657     ConvIdx++;
9658     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9659       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9660       break;
9661     }
9662   }
9663 
9664   if (ConvIdx == ConvCount)
9665     return;
9666 
9667   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9668          "remaining conversion is initialized?");
9669 
9670   // FIXME: this should probably be preserved from the overload
9671   // operation somehow.
9672   bool SuppressUserConversions = false;
9673 
9674   const FunctionProtoType* Proto;
9675   unsigned ArgIdx = ConvIdx;
9676 
9677   if (Cand->IsSurrogate) {
9678     QualType ConvType
9679       = Cand->Surrogate->getConversionType().getNonReferenceType();
9680     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9681       ConvType = ConvPtrType->getPointeeType();
9682     Proto = ConvType->getAs<FunctionProtoType>();
9683     ArgIdx--;
9684   } else if (Cand->Function) {
9685     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9686     if (isa<CXXMethodDecl>(Cand->Function) &&
9687         !isa<CXXConstructorDecl>(Cand->Function))
9688       ArgIdx--;
9689   } else {
9690     // Builtin binary operator with a bad first conversion.
9691     assert(ConvCount <= 3);
9692     for (; ConvIdx != ConvCount; ++ConvIdx)
9693       Cand->Conversions[ConvIdx]
9694         = TryCopyInitialization(S, Args[ConvIdx],
9695                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9696                                 SuppressUserConversions,
9697                                 /*InOverloadResolution*/ true,
9698                                 /*AllowObjCWritebackConversion=*/
9699                                   S.getLangOpts().ObjCAutoRefCount);
9700     return;
9701   }
9702 
9703   // Fill in the rest of the conversions.
9704   unsigned NumParams = Proto->getNumParams();
9705   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9706     if (ArgIdx < NumParams) {
9707       Cand->Conversions[ConvIdx] = TryCopyInitialization(
9708           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9709           /*InOverloadResolution=*/true,
9710           /*AllowObjCWritebackConversion=*/
9711           S.getLangOpts().ObjCAutoRefCount);
9712       // Store the FixIt in the candidate if it exists.
9713       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9714         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9715     }
9716     else
9717       Cand->Conversions[ConvIdx].setEllipsis();
9718   }
9719 }
9720 
9721 /// PrintOverloadCandidates - When overload resolution fails, prints
9722 /// diagnostic messages containing the candidates in the candidate
9723 /// set.
9724 void OverloadCandidateSet::NoteCandidates(Sema &S,
9725                                           OverloadCandidateDisplayKind OCD,
9726                                           ArrayRef<Expr *> Args,
9727                                           StringRef Opc,
9728                                           SourceLocation OpLoc) {
9729   // Sort the candidates by viability and position.  Sorting directly would
9730   // be prohibitive, so we make a set of pointers and sort those.
9731   SmallVector<OverloadCandidate*, 32> Cands;
9732   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9733   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9734     if (Cand->Viable)
9735       Cands.push_back(Cand);
9736     else if (OCD == OCD_AllCandidates) {
9737       CompleteNonViableCandidate(S, Cand, Args);
9738       if (Cand->Function || Cand->IsSurrogate)
9739         Cands.push_back(Cand);
9740       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9741       // want to list every possible builtin candidate.
9742     }
9743   }
9744 
9745   std::sort(Cands.begin(), Cands.end(),
9746             CompareOverloadCandidatesForDisplay(S, Args.size()));
9747 
9748   bool ReportedAmbiguousConversions = false;
9749 
9750   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9751   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9752   unsigned CandsShown = 0;
9753   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9754     OverloadCandidate *Cand = *I;
9755 
9756     // Set an arbitrary limit on the number of candidate functions we'll spam
9757     // the user with.  FIXME: This limit should depend on details of the
9758     // candidate list.
9759     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9760       break;
9761     }
9762     ++CandsShown;
9763 
9764     if (Cand->Function)
9765       NoteFunctionCandidate(S, Cand, Args.size());
9766     else if (Cand->IsSurrogate)
9767       NoteSurrogateCandidate(S, Cand);
9768     else {
9769       assert(Cand->Viable &&
9770              "Non-viable built-in candidates are not added to Cands.");
9771       // Generally we only see ambiguities including viable builtin
9772       // operators if overload resolution got screwed up by an
9773       // ambiguous user-defined conversion.
9774       //
9775       // FIXME: It's quite possible for different conversions to see
9776       // different ambiguities, though.
9777       if (!ReportedAmbiguousConversions) {
9778         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9779         ReportedAmbiguousConversions = true;
9780       }
9781 
9782       // If this is a viable builtin, print it.
9783       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9784     }
9785   }
9786 
9787   if (I != E)
9788     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9789 }
9790 
9791 static SourceLocation
9792 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9793   return Cand->Specialization ? Cand->Specialization->getLocation()
9794                               : SourceLocation();
9795 }
9796 
9797 namespace {
9798 struct CompareTemplateSpecCandidatesForDisplay {
9799   Sema &S;
9800   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9801 
9802   bool operator()(const TemplateSpecCandidate *L,
9803                   const TemplateSpecCandidate *R) {
9804     // Fast-path this check.
9805     if (L == R)
9806       return false;
9807 
9808     // Assuming that both candidates are not matches...
9809 
9810     // Sort by the ranking of deduction failures.
9811     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9812       return RankDeductionFailure(L->DeductionFailure) <
9813              RankDeductionFailure(R->DeductionFailure);
9814 
9815     // Sort everything else by location.
9816     SourceLocation LLoc = GetLocationForCandidate(L);
9817     SourceLocation RLoc = GetLocationForCandidate(R);
9818 
9819     // Put candidates without locations (e.g. builtins) at the end.
9820     if (LLoc.isInvalid())
9821       return false;
9822     if (RLoc.isInvalid())
9823       return true;
9824 
9825     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9826   }
9827 };
9828 }
9829 
9830 /// Diagnose a template argument deduction failure.
9831 /// We are treating these failures as overload failures due to bad
9832 /// deductions.
9833 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9834   DiagnoseBadDeduction(S, Specialization, // pattern
9835                        DeductionFailure, /*NumArgs=*/0);
9836 }
9837 
9838 void TemplateSpecCandidateSet::destroyCandidates() {
9839   for (iterator i = begin(), e = end(); i != e; ++i) {
9840     i->DeductionFailure.Destroy();
9841   }
9842 }
9843 
9844 void TemplateSpecCandidateSet::clear() {
9845   destroyCandidates();
9846   Candidates.clear();
9847 }
9848 
9849 /// NoteCandidates - When no template specialization match is found, prints
9850 /// diagnostic messages containing the non-matching specializations that form
9851 /// the candidate set.
9852 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9853 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9854 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9855   // Sort the candidates by position (assuming no candidate is a match).
9856   // Sorting directly would be prohibitive, so we make a set of pointers
9857   // and sort those.
9858   SmallVector<TemplateSpecCandidate *, 32> Cands;
9859   Cands.reserve(size());
9860   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9861     if (Cand->Specialization)
9862       Cands.push_back(Cand);
9863     // Otherwise, this is a non-matching builtin candidate.  We do not,
9864     // in general, want to list every possible builtin candidate.
9865   }
9866 
9867   std::sort(Cands.begin(), Cands.end(),
9868             CompareTemplateSpecCandidatesForDisplay(S));
9869 
9870   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9871   // for generalization purposes (?).
9872   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9873 
9874   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9875   unsigned CandsShown = 0;
9876   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9877     TemplateSpecCandidate *Cand = *I;
9878 
9879     // Set an arbitrary limit on the number of candidates we'll spam
9880     // the user with.  FIXME: This limit should depend on details of the
9881     // candidate list.
9882     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9883       break;
9884     ++CandsShown;
9885 
9886     assert(Cand->Specialization &&
9887            "Non-matching built-in candidates are not added to Cands.");
9888     Cand->NoteDeductionFailure(S);
9889   }
9890 
9891   if (I != E)
9892     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9893 }
9894 
9895 // [PossiblyAFunctionType]  -->   [Return]
9896 // NonFunctionType --> NonFunctionType
9897 // R (A) --> R(A)
9898 // R (*)(A) --> R (A)
9899 // R (&)(A) --> R (A)
9900 // R (S::*)(A) --> R (A)
9901 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9902   QualType Ret = PossiblyAFunctionType;
9903   if (const PointerType *ToTypePtr =
9904     PossiblyAFunctionType->getAs<PointerType>())
9905     Ret = ToTypePtr->getPointeeType();
9906   else if (const ReferenceType *ToTypeRef =
9907     PossiblyAFunctionType->getAs<ReferenceType>())
9908     Ret = ToTypeRef->getPointeeType();
9909   else if (const MemberPointerType *MemTypePtr =
9910     PossiblyAFunctionType->getAs<MemberPointerType>())
9911     Ret = MemTypePtr->getPointeeType();
9912   Ret =
9913     Context.getCanonicalType(Ret).getUnqualifiedType();
9914   return Ret;
9915 }
9916 
9917 namespace {
9918 // A helper class to help with address of function resolution
9919 // - allows us to avoid passing around all those ugly parameters
9920 class AddressOfFunctionResolver {
9921   Sema& S;
9922   Expr* SourceExpr;
9923   const QualType& TargetType;
9924   QualType TargetFunctionType; // Extracted function type from target type
9925 
9926   bool Complain;
9927   //DeclAccessPair& ResultFunctionAccessPair;
9928   ASTContext& Context;
9929 
9930   bool TargetTypeIsNonStaticMemberFunction;
9931   bool FoundNonTemplateFunction;
9932   bool StaticMemberFunctionFromBoundPointer;
9933   bool HasComplained;
9934 
9935   OverloadExpr::FindResult OvlExprInfo;
9936   OverloadExpr *OvlExpr;
9937   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9938   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9939   TemplateSpecCandidateSet FailedCandidates;
9940 
9941 public:
9942   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9943                             const QualType &TargetType, bool Complain)
9944       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9945         Complain(Complain), Context(S.getASTContext()),
9946         TargetTypeIsNonStaticMemberFunction(
9947             !!TargetType->getAs<MemberPointerType>()),
9948         FoundNonTemplateFunction(false),
9949         StaticMemberFunctionFromBoundPointer(false),
9950         HasComplained(false),
9951         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9952         OvlExpr(OvlExprInfo.Expression),
9953         FailedCandidates(OvlExpr->getNameLoc()) {
9954     ExtractUnqualifiedFunctionTypeFromTargetType();
9955 
9956     if (TargetFunctionType->isFunctionType()) {
9957       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9958         if (!UME->isImplicitAccess() &&
9959             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9960           StaticMemberFunctionFromBoundPointer = true;
9961     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9962       DeclAccessPair dap;
9963       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9964               OvlExpr, false, &dap)) {
9965         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9966           if (!Method->isStatic()) {
9967             // If the target type is a non-function type and the function found
9968             // is a non-static member function, pretend as if that was the
9969             // target, it's the only possible type to end up with.
9970             TargetTypeIsNonStaticMemberFunction = true;
9971 
9972             // And skip adding the function if its not in the proper form.
9973             // We'll diagnose this due to an empty set of functions.
9974             if (!OvlExprInfo.HasFormOfMemberPointer)
9975               return;
9976           }
9977 
9978         Matches.push_back(std::make_pair(dap, Fn));
9979       }
9980       return;
9981     }
9982 
9983     if (OvlExpr->hasExplicitTemplateArgs())
9984       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9985 
9986     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9987       // C++ [over.over]p4:
9988       //   If more than one function is selected, [...]
9989       if (Matches.size() > 1) {
9990         if (FoundNonTemplateFunction)
9991           EliminateAllTemplateMatches();
9992         else
9993           EliminateAllExceptMostSpecializedTemplate();
9994       }
9995     }
9996 
9997     if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
9998         Matches.size() > 1)
9999       EliminateSuboptimalCudaMatches();
10000   }
10001 
10002   bool hasComplained() const { return HasComplained; }
10003 
10004 private:
10005   bool isTargetTypeAFunction() const {
10006     return TargetFunctionType->isFunctionType();
10007   }
10008 
10009   // [ToType]     [Return]
10010 
10011   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10012   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10013   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10014   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10015     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10016   }
10017 
10018   // return true if any matching specializations were found
10019   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10020                                    const DeclAccessPair& CurAccessFunPair) {
10021     if (CXXMethodDecl *Method
10022               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10023       // Skip non-static function templates when converting to pointer, and
10024       // static when converting to member pointer.
10025       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10026         return false;
10027     }
10028     else if (TargetTypeIsNonStaticMemberFunction)
10029       return false;
10030 
10031     // C++ [over.over]p2:
10032     //   If the name is a function template, template argument deduction is
10033     //   done (14.8.2.2), and if the argument deduction succeeds, the
10034     //   resulting template argument list is used to generate a single
10035     //   function template specialization, which is added to the set of
10036     //   overloaded functions considered.
10037     FunctionDecl *Specialization = nullptr;
10038     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10039     if (Sema::TemplateDeductionResult Result
10040           = S.DeduceTemplateArguments(FunctionTemplate,
10041                                       &OvlExplicitTemplateArgs,
10042                                       TargetFunctionType, Specialization,
10043                                       Info, /*InOverloadResolution=*/true)) {
10044       // Make a note of the failed deduction for diagnostics.
10045       FailedCandidates.addCandidate()
10046           .set(FunctionTemplate->getTemplatedDecl(),
10047                MakeDeductionFailureInfo(Context, Result, Info));
10048       return false;
10049     }
10050 
10051     // Template argument deduction ensures that we have an exact match or
10052     // compatible pointer-to-function arguments that would be adjusted by ICS.
10053     // This function template specicalization works.
10054     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
10055     assert(S.isSameOrCompatibleFunctionType(
10056               Context.getCanonicalType(Specialization->getType()),
10057               Context.getCanonicalType(TargetFunctionType)) ||
10058            (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType()));
10059 
10060     if (!isFunctionAlwaysEnabled(S.Context, Specialization))
10061       return false;
10062 
10063     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10064     return true;
10065   }
10066 
10067   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10068                                       const DeclAccessPair& CurAccessFunPair) {
10069     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10070       // Skip non-static functions when converting to pointer, and static
10071       // when converting to member pointer.
10072       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10073         return false;
10074     }
10075     else if (TargetTypeIsNonStaticMemberFunction)
10076       return false;
10077 
10078     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10079       if (S.getLangOpts().CUDA)
10080         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10081           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
10082             return false;
10083 
10084       // If any candidate has a placeholder return type, trigger its deduction
10085       // now.
10086       if (S.getLangOpts().CPlusPlus14 &&
10087           FunDecl->getReturnType()->isUndeducedType() &&
10088           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10089         HasComplained |= Complain;
10090         return false;
10091       }
10092 
10093       if (!isFunctionAlwaysEnabled(S.Context, FunDecl))
10094         return false;
10095 
10096       QualType ResultTy;
10097       if (Context.hasSameUnqualifiedType(TargetFunctionType,
10098                                          FunDecl->getType()) ||
10099           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10100                                  ResultTy) ||
10101           (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10102         Matches.push_back(std::make_pair(
10103             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10104         FoundNonTemplateFunction = true;
10105         return true;
10106       }
10107     }
10108 
10109     return false;
10110   }
10111 
10112   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10113     bool Ret = false;
10114 
10115     // If the overload expression doesn't have the form of a pointer to
10116     // member, don't try to convert it to a pointer-to-member type.
10117     if (IsInvalidFormOfPointerToMemberFunction())
10118       return false;
10119 
10120     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10121                                E = OvlExpr->decls_end();
10122          I != E; ++I) {
10123       // Look through any using declarations to find the underlying function.
10124       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10125 
10126       // C++ [over.over]p3:
10127       //   Non-member functions and static member functions match
10128       //   targets of type "pointer-to-function" or "reference-to-function."
10129       //   Nonstatic member functions match targets of
10130       //   type "pointer-to-member-function."
10131       // Note that according to DR 247, the containing class does not matter.
10132       if (FunctionTemplateDecl *FunctionTemplate
10133                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10134         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10135           Ret = true;
10136       }
10137       // If we have explicit template arguments supplied, skip non-templates.
10138       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10139                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10140         Ret = true;
10141     }
10142     assert(Ret || Matches.empty());
10143     return Ret;
10144   }
10145 
10146   void EliminateAllExceptMostSpecializedTemplate() {
10147     //   [...] and any given function template specialization F1 is
10148     //   eliminated if the set contains a second function template
10149     //   specialization whose function template is more specialized
10150     //   than the function template of F1 according to the partial
10151     //   ordering rules of 14.5.5.2.
10152 
10153     // The algorithm specified above is quadratic. We instead use a
10154     // two-pass algorithm (similar to the one used to identify the
10155     // best viable function in an overload set) that identifies the
10156     // best function template (if it exists).
10157 
10158     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10159     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10160       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10161 
10162     // TODO: It looks like FailedCandidates does not serve much purpose
10163     // here, since the no_viable diagnostic has index 0.
10164     UnresolvedSetIterator Result = S.getMostSpecialized(
10165         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10166         SourceExpr->getLocStart(), S.PDiag(),
10167         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10168                                                      .second->getDeclName(),
10169         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10170         Complain, TargetFunctionType);
10171 
10172     if (Result != MatchesCopy.end()) {
10173       // Make it the first and only element
10174       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10175       Matches[0].second = cast<FunctionDecl>(*Result);
10176       Matches.resize(1);
10177     } else
10178       HasComplained |= Complain;
10179   }
10180 
10181   void EliminateAllTemplateMatches() {
10182     //   [...] any function template specializations in the set are
10183     //   eliminated if the set also contains a non-template function, [...]
10184     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10185       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10186         ++I;
10187       else {
10188         Matches[I] = Matches[--N];
10189         Matches.resize(N);
10190       }
10191     }
10192   }
10193 
10194   void EliminateSuboptimalCudaMatches() {
10195     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10196   }
10197 
10198 public:
10199   void ComplainNoMatchesFound() const {
10200     assert(Matches.empty());
10201     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10202         << OvlExpr->getName() << TargetFunctionType
10203         << OvlExpr->getSourceRange();
10204     if (FailedCandidates.empty())
10205       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10206                                   /*TakingAddress=*/true);
10207     else {
10208       // We have some deduction failure messages. Use them to diagnose
10209       // the function templates, and diagnose the non-template candidates
10210       // normally.
10211       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10212                                  IEnd = OvlExpr->decls_end();
10213            I != IEnd; ++I)
10214         if (FunctionDecl *Fun =
10215                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10216           S.NoteOverloadCandidate(Fun, TargetFunctionType,
10217                                   /*TakingAddress=*/true);
10218       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10219     }
10220   }
10221 
10222   bool IsInvalidFormOfPointerToMemberFunction() const {
10223     return TargetTypeIsNonStaticMemberFunction &&
10224       !OvlExprInfo.HasFormOfMemberPointer;
10225   }
10226 
10227   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10228       // TODO: Should we condition this on whether any functions might
10229       // have matched, or is it more appropriate to do that in callers?
10230       // TODO: a fixit wouldn't hurt.
10231       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10232         << TargetType << OvlExpr->getSourceRange();
10233   }
10234 
10235   bool IsStaticMemberFunctionFromBoundPointer() const {
10236     return StaticMemberFunctionFromBoundPointer;
10237   }
10238 
10239   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10240     S.Diag(OvlExpr->getLocStart(),
10241            diag::err_invalid_form_pointer_member_function)
10242       << OvlExpr->getSourceRange();
10243   }
10244 
10245   void ComplainOfInvalidConversion() const {
10246     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10247       << OvlExpr->getName() << TargetType;
10248   }
10249 
10250   void ComplainMultipleMatchesFound() const {
10251     assert(Matches.size() > 1);
10252     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10253       << OvlExpr->getName()
10254       << OvlExpr->getSourceRange();
10255     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10256                                 /*TakingAddress=*/true);
10257   }
10258 
10259   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10260 
10261   int getNumMatches() const { return Matches.size(); }
10262 
10263   FunctionDecl* getMatchingFunctionDecl() const {
10264     if (Matches.size() != 1) return nullptr;
10265     return Matches[0].second;
10266   }
10267 
10268   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10269     if (Matches.size() != 1) return nullptr;
10270     return &Matches[0].first;
10271   }
10272 };
10273 }
10274 
10275 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10276 /// an overloaded function (C++ [over.over]), where @p From is an
10277 /// expression with overloaded function type and @p ToType is the type
10278 /// we're trying to resolve to. For example:
10279 ///
10280 /// @code
10281 /// int f(double);
10282 /// int f(int);
10283 ///
10284 /// int (*pfd)(double) = f; // selects f(double)
10285 /// @endcode
10286 ///
10287 /// This routine returns the resulting FunctionDecl if it could be
10288 /// resolved, and NULL otherwise. When @p Complain is true, this
10289 /// routine will emit diagnostics if there is an error.
10290 FunctionDecl *
10291 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10292                                          QualType TargetType,
10293                                          bool Complain,
10294                                          DeclAccessPair &FoundResult,
10295                                          bool *pHadMultipleCandidates) {
10296   assert(AddressOfExpr->getType() == Context.OverloadTy);
10297 
10298   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10299                                      Complain);
10300   int NumMatches = Resolver.getNumMatches();
10301   FunctionDecl *Fn = nullptr;
10302   bool ShouldComplain = Complain && !Resolver.hasComplained();
10303   if (NumMatches == 0 && ShouldComplain) {
10304     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10305       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10306     else
10307       Resolver.ComplainNoMatchesFound();
10308   }
10309   else if (NumMatches > 1 && ShouldComplain)
10310     Resolver.ComplainMultipleMatchesFound();
10311   else if (NumMatches == 1) {
10312     Fn = Resolver.getMatchingFunctionDecl();
10313     assert(Fn);
10314     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10315     if (Complain) {
10316       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10317         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10318       else
10319         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10320     }
10321   }
10322 
10323   if (pHadMultipleCandidates)
10324     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10325   return Fn;
10326 }
10327 
10328 /// \brief Given an expression that refers to an overloaded function, try to
10329 /// resolve that overloaded function expression down to a single function.
10330 ///
10331 /// This routine can only resolve template-ids that refer to a single function
10332 /// template, where that template-id refers to a single template whose template
10333 /// arguments are either provided by the template-id or have defaults,
10334 /// as described in C++0x [temp.arg.explicit]p3.
10335 ///
10336 /// If no template-ids are found, no diagnostics are emitted and NULL is
10337 /// returned.
10338 FunctionDecl *
10339 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10340                                                   bool Complain,
10341                                                   DeclAccessPair *FoundResult) {
10342   // C++ [over.over]p1:
10343   //   [...] [Note: any redundant set of parentheses surrounding the
10344   //   overloaded function name is ignored (5.1). ]
10345   // C++ [over.over]p1:
10346   //   [...] The overloaded function name can be preceded by the &
10347   //   operator.
10348 
10349   // If we didn't actually find any template-ids, we're done.
10350   if (!ovl->hasExplicitTemplateArgs())
10351     return nullptr;
10352 
10353   TemplateArgumentListInfo ExplicitTemplateArgs;
10354   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10355   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10356 
10357   // Look through all of the overloaded functions, searching for one
10358   // whose type matches exactly.
10359   FunctionDecl *Matched = nullptr;
10360   for (UnresolvedSetIterator I = ovl->decls_begin(),
10361          E = ovl->decls_end(); I != E; ++I) {
10362     // C++0x [temp.arg.explicit]p3:
10363     //   [...] In contexts where deduction is done and fails, or in contexts
10364     //   where deduction is not done, if a template argument list is
10365     //   specified and it, along with any default template arguments,
10366     //   identifies a single function template specialization, then the
10367     //   template-id is an lvalue for the function template specialization.
10368     FunctionTemplateDecl *FunctionTemplate
10369       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10370 
10371     // C++ [over.over]p2:
10372     //   If the name is a function template, template argument deduction is
10373     //   done (14.8.2.2), and if the argument deduction succeeds, the
10374     //   resulting template argument list is used to generate a single
10375     //   function template specialization, which is added to the set of
10376     //   overloaded functions considered.
10377     FunctionDecl *Specialization = nullptr;
10378     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10379     if (TemplateDeductionResult Result
10380           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10381                                     Specialization, Info,
10382                                     /*InOverloadResolution=*/true)) {
10383       // Make a note of the failed deduction for diagnostics.
10384       // TODO: Actually use the failed-deduction info?
10385       FailedCandidates.addCandidate()
10386           .set(FunctionTemplate->getTemplatedDecl(),
10387                MakeDeductionFailureInfo(Context, Result, Info));
10388       continue;
10389     }
10390 
10391     assert(Specialization && "no specialization and no error?");
10392 
10393     // Multiple matches; we can't resolve to a single declaration.
10394     if (Matched) {
10395       if (Complain) {
10396         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10397           << ovl->getName();
10398         NoteAllOverloadCandidates(ovl);
10399       }
10400       return nullptr;
10401     }
10402 
10403     Matched = Specialization;
10404     if (FoundResult) *FoundResult = I.getPair();
10405   }
10406 
10407   if (Matched && getLangOpts().CPlusPlus14 &&
10408       Matched->getReturnType()->isUndeducedType() &&
10409       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10410     return nullptr;
10411 
10412   return Matched;
10413 }
10414 
10415 
10416 
10417 
10418 // Resolve and fix an overloaded expression that can be resolved
10419 // because it identifies a single function template specialization.
10420 //
10421 // Last three arguments should only be supplied if Complain = true
10422 //
10423 // Return true if it was logically possible to so resolve the
10424 // expression, regardless of whether or not it succeeded.  Always
10425 // returns true if 'complain' is set.
10426 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10427                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10428                       bool complain, SourceRange OpRangeForComplaining,
10429                                            QualType DestTypeForComplaining,
10430                                             unsigned DiagIDForComplaining) {
10431   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10432 
10433   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10434 
10435   DeclAccessPair found;
10436   ExprResult SingleFunctionExpression;
10437   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10438                            ovl.Expression, /*complain*/ false, &found)) {
10439     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10440       SrcExpr = ExprError();
10441       return true;
10442     }
10443 
10444     // It is only correct to resolve to an instance method if we're
10445     // resolving a form that's permitted to be a pointer to member.
10446     // Otherwise we'll end up making a bound member expression, which
10447     // is illegal in all the contexts we resolve like this.
10448     if (!ovl.HasFormOfMemberPointer &&
10449         isa<CXXMethodDecl>(fn) &&
10450         cast<CXXMethodDecl>(fn)->isInstance()) {
10451       if (!complain) return false;
10452 
10453       Diag(ovl.Expression->getExprLoc(),
10454            diag::err_bound_member_function)
10455         << 0 << ovl.Expression->getSourceRange();
10456 
10457       // TODO: I believe we only end up here if there's a mix of
10458       // static and non-static candidates (otherwise the expression
10459       // would have 'bound member' type, not 'overload' type).
10460       // Ideally we would note which candidate was chosen and why
10461       // the static candidates were rejected.
10462       SrcExpr = ExprError();
10463       return true;
10464     }
10465 
10466     // Fix the expression to refer to 'fn'.
10467     SingleFunctionExpression =
10468         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10469 
10470     // If desired, do function-to-pointer decay.
10471     if (doFunctionPointerConverion) {
10472       SingleFunctionExpression =
10473         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10474       if (SingleFunctionExpression.isInvalid()) {
10475         SrcExpr = ExprError();
10476         return true;
10477       }
10478     }
10479   }
10480 
10481   if (!SingleFunctionExpression.isUsable()) {
10482     if (complain) {
10483       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10484         << ovl.Expression->getName()
10485         << DestTypeForComplaining
10486         << OpRangeForComplaining
10487         << ovl.Expression->getQualifierLoc().getSourceRange();
10488       NoteAllOverloadCandidates(SrcExpr.get());
10489 
10490       SrcExpr = ExprError();
10491       return true;
10492     }
10493 
10494     return false;
10495   }
10496 
10497   SrcExpr = SingleFunctionExpression;
10498   return true;
10499 }
10500 
10501 /// \brief Add a single candidate to the overload set.
10502 static void AddOverloadedCallCandidate(Sema &S,
10503                                        DeclAccessPair FoundDecl,
10504                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10505                                        ArrayRef<Expr *> Args,
10506                                        OverloadCandidateSet &CandidateSet,
10507                                        bool PartialOverloading,
10508                                        bool KnownValid) {
10509   NamedDecl *Callee = FoundDecl.getDecl();
10510   if (isa<UsingShadowDecl>(Callee))
10511     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10512 
10513   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10514     if (ExplicitTemplateArgs) {
10515       assert(!KnownValid && "Explicit template arguments?");
10516       return;
10517     }
10518     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10519                            /*SuppressUsedConversions=*/false,
10520                            PartialOverloading);
10521     return;
10522   }
10523 
10524   if (FunctionTemplateDecl *FuncTemplate
10525       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10526     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10527                                    ExplicitTemplateArgs, Args, CandidateSet,
10528                                    /*SuppressUsedConversions=*/false,
10529                                    PartialOverloading);
10530     return;
10531   }
10532 
10533   assert(!KnownValid && "unhandled case in overloaded call candidate");
10534 }
10535 
10536 /// \brief Add the overload candidates named by callee and/or found by argument
10537 /// dependent lookup to the given overload set.
10538 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10539                                        ArrayRef<Expr *> Args,
10540                                        OverloadCandidateSet &CandidateSet,
10541                                        bool PartialOverloading) {
10542 
10543 #ifndef NDEBUG
10544   // Verify that ArgumentDependentLookup is consistent with the rules
10545   // in C++0x [basic.lookup.argdep]p3:
10546   //
10547   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10548   //   and let Y be the lookup set produced by argument dependent
10549   //   lookup (defined as follows). If X contains
10550   //
10551   //     -- a declaration of a class member, or
10552   //
10553   //     -- a block-scope function declaration that is not a
10554   //        using-declaration, or
10555   //
10556   //     -- a declaration that is neither a function or a function
10557   //        template
10558   //
10559   //   then Y is empty.
10560 
10561   if (ULE->requiresADL()) {
10562     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10563            E = ULE->decls_end(); I != E; ++I) {
10564       assert(!(*I)->getDeclContext()->isRecord());
10565       assert(isa<UsingShadowDecl>(*I) ||
10566              !(*I)->getDeclContext()->isFunctionOrMethod());
10567       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10568     }
10569   }
10570 #endif
10571 
10572   // It would be nice to avoid this copy.
10573   TemplateArgumentListInfo TABuffer;
10574   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10575   if (ULE->hasExplicitTemplateArgs()) {
10576     ULE->copyTemplateArgumentsInto(TABuffer);
10577     ExplicitTemplateArgs = &TABuffer;
10578   }
10579 
10580   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10581          E = ULE->decls_end(); I != E; ++I)
10582     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10583                                CandidateSet, PartialOverloading,
10584                                /*KnownValid*/ true);
10585 
10586   if (ULE->requiresADL())
10587     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10588                                          Args, ExplicitTemplateArgs,
10589                                          CandidateSet, PartialOverloading);
10590 }
10591 
10592 /// Determine whether a declaration with the specified name could be moved into
10593 /// a different namespace.
10594 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10595   switch (Name.getCXXOverloadedOperator()) {
10596   case OO_New: case OO_Array_New:
10597   case OO_Delete: case OO_Array_Delete:
10598     return false;
10599 
10600   default:
10601     return true;
10602   }
10603 }
10604 
10605 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10606 /// template, where the non-dependent name was declared after the template
10607 /// was defined. This is common in code written for a compilers which do not
10608 /// correctly implement two-stage name lookup.
10609 ///
10610 /// Returns true if a viable candidate was found and a diagnostic was issued.
10611 static bool
10612 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10613                        const CXXScopeSpec &SS, LookupResult &R,
10614                        OverloadCandidateSet::CandidateSetKind CSK,
10615                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10616                        ArrayRef<Expr *> Args,
10617                        bool *DoDiagnoseEmptyLookup = nullptr) {
10618   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10619     return false;
10620 
10621   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10622     if (DC->isTransparentContext())
10623       continue;
10624 
10625     SemaRef.LookupQualifiedName(R, DC);
10626 
10627     if (!R.empty()) {
10628       R.suppressDiagnostics();
10629 
10630       if (isa<CXXRecordDecl>(DC)) {
10631         // Don't diagnose names we find in classes; we get much better
10632         // diagnostics for these from DiagnoseEmptyLookup.
10633         R.clear();
10634         if (DoDiagnoseEmptyLookup)
10635           *DoDiagnoseEmptyLookup = true;
10636         return false;
10637       }
10638 
10639       OverloadCandidateSet Candidates(FnLoc, CSK);
10640       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10641         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10642                                    ExplicitTemplateArgs, Args,
10643                                    Candidates, false, /*KnownValid*/ false);
10644 
10645       OverloadCandidateSet::iterator Best;
10646       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10647         // No viable functions. Don't bother the user with notes for functions
10648         // which don't work and shouldn't be found anyway.
10649         R.clear();
10650         return false;
10651       }
10652 
10653       // Find the namespaces where ADL would have looked, and suggest
10654       // declaring the function there instead.
10655       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10656       Sema::AssociatedClassSet AssociatedClasses;
10657       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10658                                                  AssociatedNamespaces,
10659                                                  AssociatedClasses);
10660       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10661       if (canBeDeclaredInNamespace(R.getLookupName())) {
10662         DeclContext *Std = SemaRef.getStdNamespace();
10663         for (Sema::AssociatedNamespaceSet::iterator
10664                it = AssociatedNamespaces.begin(),
10665                end = AssociatedNamespaces.end(); it != end; ++it) {
10666           // Never suggest declaring a function within namespace 'std'.
10667           if (Std && Std->Encloses(*it))
10668             continue;
10669 
10670           // Never suggest declaring a function within a namespace with a
10671           // reserved name, like __gnu_cxx.
10672           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10673           if (NS &&
10674               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10675             continue;
10676 
10677           SuggestedNamespaces.insert(*it);
10678         }
10679       }
10680 
10681       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10682         << R.getLookupName();
10683       if (SuggestedNamespaces.empty()) {
10684         SemaRef.Diag(Best->Function->getLocation(),
10685                      diag::note_not_found_by_two_phase_lookup)
10686           << R.getLookupName() << 0;
10687       } else if (SuggestedNamespaces.size() == 1) {
10688         SemaRef.Diag(Best->Function->getLocation(),
10689                      diag::note_not_found_by_two_phase_lookup)
10690           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10691       } else {
10692         // FIXME: It would be useful to list the associated namespaces here,
10693         // but the diagnostics infrastructure doesn't provide a way to produce
10694         // a localized representation of a list of items.
10695         SemaRef.Diag(Best->Function->getLocation(),
10696                      diag::note_not_found_by_two_phase_lookup)
10697           << R.getLookupName() << 2;
10698       }
10699 
10700       // Try to recover by calling this function.
10701       return true;
10702     }
10703 
10704     R.clear();
10705   }
10706 
10707   return false;
10708 }
10709 
10710 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10711 /// template, where the non-dependent operator was declared after the template
10712 /// was defined.
10713 ///
10714 /// Returns true if a viable candidate was found and a diagnostic was issued.
10715 static bool
10716 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10717                                SourceLocation OpLoc,
10718                                ArrayRef<Expr *> Args) {
10719   DeclarationName OpName =
10720     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10721   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10722   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10723                                 OverloadCandidateSet::CSK_Operator,
10724                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10725 }
10726 
10727 namespace {
10728 class BuildRecoveryCallExprRAII {
10729   Sema &SemaRef;
10730 public:
10731   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10732     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10733     SemaRef.IsBuildingRecoveryCallExpr = true;
10734   }
10735 
10736   ~BuildRecoveryCallExprRAII() {
10737     SemaRef.IsBuildingRecoveryCallExpr = false;
10738   }
10739 };
10740 
10741 }
10742 
10743 static std::unique_ptr<CorrectionCandidateCallback>
10744 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10745               bool HasTemplateArgs, bool AllowTypoCorrection) {
10746   if (!AllowTypoCorrection)
10747     return llvm::make_unique<NoTypoCorrectionCCC>();
10748   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10749                                                   HasTemplateArgs, ME);
10750 }
10751 
10752 /// Attempts to recover from a call where no functions were found.
10753 ///
10754 /// Returns true if new candidates were found.
10755 static ExprResult
10756 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10757                       UnresolvedLookupExpr *ULE,
10758                       SourceLocation LParenLoc,
10759                       MutableArrayRef<Expr *> Args,
10760                       SourceLocation RParenLoc,
10761                       bool EmptyLookup, bool AllowTypoCorrection) {
10762   // Do not try to recover if it is already building a recovery call.
10763   // This stops infinite loops for template instantiations like
10764   //
10765   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10766   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10767   //
10768   if (SemaRef.IsBuildingRecoveryCallExpr)
10769     return ExprError();
10770   BuildRecoveryCallExprRAII RCE(SemaRef);
10771 
10772   CXXScopeSpec SS;
10773   SS.Adopt(ULE->getQualifierLoc());
10774   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10775 
10776   TemplateArgumentListInfo TABuffer;
10777   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10778   if (ULE->hasExplicitTemplateArgs()) {
10779     ULE->copyTemplateArgumentsInto(TABuffer);
10780     ExplicitTemplateArgs = &TABuffer;
10781   }
10782 
10783   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10784                  Sema::LookupOrdinaryName);
10785   bool DoDiagnoseEmptyLookup = EmptyLookup;
10786   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10787                               OverloadCandidateSet::CSK_Normal,
10788                               ExplicitTemplateArgs, Args,
10789                               &DoDiagnoseEmptyLookup) &&
10790     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
10791         S, SS, R,
10792         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10793                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10794         ExplicitTemplateArgs, Args)))
10795     return ExprError();
10796 
10797   assert(!R.empty() && "lookup results empty despite recovery");
10798 
10799   // Build an implicit member call if appropriate.  Just drop the
10800   // casts and such from the call, we don't really care.
10801   ExprResult NewFn = ExprError();
10802   if ((*R.begin())->isCXXClassMember())
10803     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10804                                                     ExplicitTemplateArgs, S);
10805   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10806     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10807                                         ExplicitTemplateArgs);
10808   else
10809     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10810 
10811   if (NewFn.isInvalid())
10812     return ExprError();
10813 
10814   // This shouldn't cause an infinite loop because we're giving it
10815   // an expression with viable lookup results, which should never
10816   // end up here.
10817   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10818                                MultiExprArg(Args.data(), Args.size()),
10819                                RParenLoc);
10820 }
10821 
10822 /// \brief Constructs and populates an OverloadedCandidateSet from
10823 /// the given function.
10824 /// \returns true when an the ExprResult output parameter has been set.
10825 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10826                                   UnresolvedLookupExpr *ULE,
10827                                   MultiExprArg Args,
10828                                   SourceLocation RParenLoc,
10829                                   OverloadCandidateSet *CandidateSet,
10830                                   ExprResult *Result) {
10831 #ifndef NDEBUG
10832   if (ULE->requiresADL()) {
10833     // To do ADL, we must have found an unqualified name.
10834     assert(!ULE->getQualifier() && "qualified name with ADL");
10835 
10836     // We don't perform ADL for implicit declarations of builtins.
10837     // Verify that this was correctly set up.
10838     FunctionDecl *F;
10839     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10840         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10841         F->getBuiltinID() && F->isImplicit())
10842       llvm_unreachable("performing ADL for builtin");
10843 
10844     // We don't perform ADL in C.
10845     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10846   }
10847 #endif
10848 
10849   UnbridgedCastsSet UnbridgedCasts;
10850   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10851     *Result = ExprError();
10852     return true;
10853   }
10854 
10855   // Add the functions denoted by the callee to the set of candidate
10856   // functions, including those from argument-dependent lookup.
10857   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10858 
10859   if (getLangOpts().MSVCCompat &&
10860       CurContext->isDependentContext() && !isSFINAEContext() &&
10861       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10862 
10863     OverloadCandidateSet::iterator Best;
10864     if (CandidateSet->empty() ||
10865         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
10866             OR_No_Viable_Function) {
10867       // In Microsoft mode, if we are inside a template class member function then
10868       // create a type dependent CallExpr. The goal is to postpone name lookup
10869       // to instantiation time to be able to search into type dependent base
10870       // classes.
10871       CallExpr *CE = new (Context) CallExpr(
10872           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
10873       CE->setTypeDependent(true);
10874       CE->setValueDependent(true);
10875       CE->setInstantiationDependent(true);
10876       *Result = CE;
10877       return true;
10878     }
10879   }
10880 
10881   if (CandidateSet->empty())
10882     return false;
10883 
10884   UnbridgedCasts.restore();
10885   return false;
10886 }
10887 
10888 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10889 /// the completed call expression. If overload resolution fails, emits
10890 /// diagnostics and returns ExprError()
10891 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10892                                            UnresolvedLookupExpr *ULE,
10893                                            SourceLocation LParenLoc,
10894                                            MultiExprArg Args,
10895                                            SourceLocation RParenLoc,
10896                                            Expr *ExecConfig,
10897                                            OverloadCandidateSet *CandidateSet,
10898                                            OverloadCandidateSet::iterator *Best,
10899                                            OverloadingResult OverloadResult,
10900                                            bool AllowTypoCorrection) {
10901   if (CandidateSet->empty())
10902     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10903                                  RParenLoc, /*EmptyLookup=*/true,
10904                                  AllowTypoCorrection);
10905 
10906   switch (OverloadResult) {
10907   case OR_Success: {
10908     FunctionDecl *FDecl = (*Best)->Function;
10909     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10910     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10911       return ExprError();
10912     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10913     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10914                                          ExecConfig);
10915   }
10916 
10917   case OR_No_Viable_Function: {
10918     // Try to recover by looking for viable functions which the user might
10919     // have meant to call.
10920     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10921                                                 Args, RParenLoc,
10922                                                 /*EmptyLookup=*/false,
10923                                                 AllowTypoCorrection);
10924     if (!Recovery.isInvalid())
10925       return Recovery;
10926 
10927     SemaRef.Diag(Fn->getLocStart(),
10928          diag::err_ovl_no_viable_function_in_call)
10929       << ULE->getName() << Fn->getSourceRange();
10930     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10931     break;
10932   }
10933 
10934   case OR_Ambiguous:
10935     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10936       << ULE->getName() << Fn->getSourceRange();
10937     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10938     break;
10939 
10940   case OR_Deleted: {
10941     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10942       << (*Best)->Function->isDeleted()
10943       << ULE->getName()
10944       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10945       << Fn->getSourceRange();
10946     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10947 
10948     // We emitted an error for the unvailable/deleted function call but keep
10949     // the call in the AST.
10950     FunctionDecl *FDecl = (*Best)->Function;
10951     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10952     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10953                                          ExecConfig);
10954   }
10955   }
10956 
10957   // Overload resolution failed.
10958   return ExprError();
10959 }
10960 
10961 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10962 /// (which eventually refers to the declaration Func) and the call
10963 /// arguments Args/NumArgs, attempt to resolve the function call down
10964 /// to a specific function. If overload resolution succeeds, returns
10965 /// the call expression produced by overload resolution.
10966 /// Otherwise, emits diagnostics and returns ExprError.
10967 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10968                                          UnresolvedLookupExpr *ULE,
10969                                          SourceLocation LParenLoc,
10970                                          MultiExprArg Args,
10971                                          SourceLocation RParenLoc,
10972                                          Expr *ExecConfig,
10973                                          bool AllowTypoCorrection) {
10974   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10975                                     OverloadCandidateSet::CSK_Normal);
10976   ExprResult result;
10977 
10978   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10979                              &result))
10980     return result;
10981 
10982   OverloadCandidateSet::iterator Best;
10983   OverloadingResult OverloadResult =
10984       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10985 
10986   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10987                                   RParenLoc, ExecConfig, &CandidateSet,
10988                                   &Best, OverloadResult,
10989                                   AllowTypoCorrection);
10990 }
10991 
10992 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10993   return Functions.size() > 1 ||
10994     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10995 }
10996 
10997 /// \brief Create a unary operation that may resolve to an overloaded
10998 /// operator.
10999 ///
11000 /// \param OpLoc The location of the operator itself (e.g., '*').
11001 ///
11002 /// \param OpcIn The UnaryOperator::Opcode that describes this
11003 /// operator.
11004 ///
11005 /// \param Fns The set of non-member functions that will be
11006 /// considered by overload resolution. The caller needs to build this
11007 /// set based on the context using, e.g.,
11008 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11009 /// set should not contain any member functions; those will be added
11010 /// by CreateOverloadedUnaryOp().
11011 ///
11012 /// \param Input The input argument.
11013 ExprResult
11014 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
11015                               const UnresolvedSetImpl &Fns,
11016                               Expr *Input) {
11017   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
11018 
11019   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11020   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11021   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11022   // TODO: provide better source location info.
11023   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11024 
11025   if (checkPlaceholderForOverload(*this, Input))
11026     return ExprError();
11027 
11028   Expr *Args[2] = { Input, nullptr };
11029   unsigned NumArgs = 1;
11030 
11031   // For post-increment and post-decrement, add the implicit '0' as
11032   // the second argument, so that we know this is a post-increment or
11033   // post-decrement.
11034   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11035     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11036     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11037                                      SourceLocation());
11038     NumArgs = 2;
11039   }
11040 
11041   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11042 
11043   if (Input->isTypeDependent()) {
11044     if (Fns.empty())
11045       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11046                                          VK_RValue, OK_Ordinary, OpLoc);
11047 
11048     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11049     UnresolvedLookupExpr *Fn
11050       = UnresolvedLookupExpr::Create(Context, NamingClass,
11051                                      NestedNameSpecifierLoc(), OpNameInfo,
11052                                      /*ADL*/ true, IsOverloaded(Fns),
11053                                      Fns.begin(), Fns.end());
11054     return new (Context)
11055         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11056                             VK_RValue, OpLoc, false);
11057   }
11058 
11059   // Build an empty overload set.
11060   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11061 
11062   // Add the candidates from the given function set.
11063   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11064 
11065   // Add operator candidates that are member functions.
11066   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11067 
11068   // Add candidates from ADL.
11069   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11070                                        /*ExplicitTemplateArgs*/nullptr,
11071                                        CandidateSet);
11072 
11073   // Add builtin operator candidates.
11074   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11075 
11076   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11077 
11078   // Perform overload resolution.
11079   OverloadCandidateSet::iterator Best;
11080   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11081   case OR_Success: {
11082     // We found a built-in operator or an overloaded operator.
11083     FunctionDecl *FnDecl = Best->Function;
11084 
11085     if (FnDecl) {
11086       // We matched an overloaded operator. Build a call to that
11087       // operator.
11088 
11089       // Convert the arguments.
11090       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11091         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11092 
11093         ExprResult InputRes =
11094           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11095                                               Best->FoundDecl, Method);
11096         if (InputRes.isInvalid())
11097           return ExprError();
11098         Input = InputRes.get();
11099       } else {
11100         // Convert the arguments.
11101         ExprResult InputInit
11102           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11103                                                       Context,
11104                                                       FnDecl->getParamDecl(0)),
11105                                       SourceLocation(),
11106                                       Input);
11107         if (InputInit.isInvalid())
11108           return ExprError();
11109         Input = InputInit.get();
11110       }
11111 
11112       // Build the actual expression node.
11113       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11114                                                 HadMultipleCandidates, OpLoc);
11115       if (FnExpr.isInvalid())
11116         return ExprError();
11117 
11118       // Determine the result type.
11119       QualType ResultTy = FnDecl->getReturnType();
11120       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11121       ResultTy = ResultTy.getNonLValueExprType(Context);
11122 
11123       Args[0] = Input;
11124       CallExpr *TheCall =
11125         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11126                                           ResultTy, VK, OpLoc, false);
11127 
11128       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11129         return ExprError();
11130 
11131       return MaybeBindToTemporary(TheCall);
11132     } else {
11133       // We matched a built-in operator. Convert the arguments, then
11134       // break out so that we will build the appropriate built-in
11135       // operator node.
11136       ExprResult InputRes =
11137         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11138                                   Best->Conversions[0], AA_Passing);
11139       if (InputRes.isInvalid())
11140         return ExprError();
11141       Input = InputRes.get();
11142       break;
11143     }
11144   }
11145 
11146   case OR_No_Viable_Function:
11147     // This is an erroneous use of an operator which can be overloaded by
11148     // a non-member function. Check for non-member operators which were
11149     // defined too late to be candidates.
11150     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11151       // FIXME: Recover by calling the found function.
11152       return ExprError();
11153 
11154     // No viable function; fall through to handling this as a
11155     // built-in operator, which will produce an error message for us.
11156     break;
11157 
11158   case OR_Ambiguous:
11159     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11160         << UnaryOperator::getOpcodeStr(Opc)
11161         << Input->getType()
11162         << Input->getSourceRange();
11163     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11164                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11165     return ExprError();
11166 
11167   case OR_Deleted:
11168     Diag(OpLoc, diag::err_ovl_deleted_oper)
11169       << Best->Function->isDeleted()
11170       << UnaryOperator::getOpcodeStr(Opc)
11171       << getDeletedOrUnavailableSuffix(Best->Function)
11172       << Input->getSourceRange();
11173     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11174                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11175     return ExprError();
11176   }
11177 
11178   // Either we found no viable overloaded operator or we matched a
11179   // built-in operator. In either case, fall through to trying to
11180   // build a built-in operation.
11181   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11182 }
11183 
11184 /// \brief Create a binary operation that may resolve to an overloaded
11185 /// operator.
11186 ///
11187 /// \param OpLoc The location of the operator itself (e.g., '+').
11188 ///
11189 /// \param OpcIn The BinaryOperator::Opcode that describes this
11190 /// operator.
11191 ///
11192 /// \param Fns The set of non-member functions that will be
11193 /// considered by overload resolution. The caller needs to build this
11194 /// set based on the context using, e.g.,
11195 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11196 /// set should not contain any member functions; those will be added
11197 /// by CreateOverloadedBinOp().
11198 ///
11199 /// \param LHS Left-hand argument.
11200 /// \param RHS Right-hand argument.
11201 ExprResult
11202 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11203                             unsigned OpcIn,
11204                             const UnresolvedSetImpl &Fns,
11205                             Expr *LHS, Expr *RHS) {
11206   Expr *Args[2] = { LHS, RHS };
11207   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11208 
11209   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11210   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11211   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11212 
11213   // If either side is type-dependent, create an appropriate dependent
11214   // expression.
11215   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11216     if (Fns.empty()) {
11217       // If there are no functions to store, just build a dependent
11218       // BinaryOperator or CompoundAssignment.
11219       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11220         return new (Context) BinaryOperator(
11221             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11222             OpLoc, FPFeatures.fp_contract);
11223 
11224       return new (Context) CompoundAssignOperator(
11225           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11226           Context.DependentTy, Context.DependentTy, OpLoc,
11227           FPFeatures.fp_contract);
11228     }
11229 
11230     // FIXME: save results of ADL from here?
11231     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11232     // TODO: provide better source location info in DNLoc component.
11233     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11234     UnresolvedLookupExpr *Fn
11235       = UnresolvedLookupExpr::Create(Context, NamingClass,
11236                                      NestedNameSpecifierLoc(), OpNameInfo,
11237                                      /*ADL*/ true, IsOverloaded(Fns),
11238                                      Fns.begin(), Fns.end());
11239     return new (Context)
11240         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11241                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11242   }
11243 
11244   // Always do placeholder-like conversions on the RHS.
11245   if (checkPlaceholderForOverload(*this, Args[1]))
11246     return ExprError();
11247 
11248   // Do placeholder-like conversion on the LHS; note that we should
11249   // not get here with a PseudoObject LHS.
11250   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11251   if (checkPlaceholderForOverload(*this, Args[0]))
11252     return ExprError();
11253 
11254   // If this is the assignment operator, we only perform overload resolution
11255   // if the left-hand side is a class or enumeration type. This is actually
11256   // a hack. The standard requires that we do overload resolution between the
11257   // various built-in candidates, but as DR507 points out, this can lead to
11258   // problems. So we do it this way, which pretty much follows what GCC does.
11259   // Note that we go the traditional code path for compound assignment forms.
11260   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11261     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11262 
11263   // If this is the .* operator, which is not overloadable, just
11264   // create a built-in binary operator.
11265   if (Opc == BO_PtrMemD)
11266     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11267 
11268   // Build an empty overload set.
11269   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11270 
11271   // Add the candidates from the given function set.
11272   AddFunctionCandidates(Fns, Args, CandidateSet);
11273 
11274   // Add operator candidates that are member functions.
11275   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11276 
11277   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11278   // performed for an assignment operator (nor for operator[] nor operator->,
11279   // which don't get here).
11280   if (Opc != BO_Assign)
11281     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11282                                          /*ExplicitTemplateArgs*/ nullptr,
11283                                          CandidateSet);
11284 
11285   // Add builtin operator candidates.
11286   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11287 
11288   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11289 
11290   // Perform overload resolution.
11291   OverloadCandidateSet::iterator Best;
11292   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11293     case OR_Success: {
11294       // We found a built-in operator or an overloaded operator.
11295       FunctionDecl *FnDecl = Best->Function;
11296 
11297       if (FnDecl) {
11298         // We matched an overloaded operator. Build a call to that
11299         // operator.
11300 
11301         // Convert the arguments.
11302         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11303           // Best->Access is only meaningful for class members.
11304           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11305 
11306           ExprResult Arg1 =
11307             PerformCopyInitialization(
11308               InitializedEntity::InitializeParameter(Context,
11309                                                      FnDecl->getParamDecl(0)),
11310               SourceLocation(), Args[1]);
11311           if (Arg1.isInvalid())
11312             return ExprError();
11313 
11314           ExprResult Arg0 =
11315             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11316                                                 Best->FoundDecl, Method);
11317           if (Arg0.isInvalid())
11318             return ExprError();
11319           Args[0] = Arg0.getAs<Expr>();
11320           Args[1] = RHS = Arg1.getAs<Expr>();
11321         } else {
11322           // Convert the arguments.
11323           ExprResult Arg0 = PerformCopyInitialization(
11324             InitializedEntity::InitializeParameter(Context,
11325                                                    FnDecl->getParamDecl(0)),
11326             SourceLocation(), Args[0]);
11327           if (Arg0.isInvalid())
11328             return ExprError();
11329 
11330           ExprResult Arg1 =
11331             PerformCopyInitialization(
11332               InitializedEntity::InitializeParameter(Context,
11333                                                      FnDecl->getParamDecl(1)),
11334               SourceLocation(), Args[1]);
11335           if (Arg1.isInvalid())
11336             return ExprError();
11337           Args[0] = LHS = Arg0.getAs<Expr>();
11338           Args[1] = RHS = Arg1.getAs<Expr>();
11339         }
11340 
11341         // Build the actual expression node.
11342         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11343                                                   Best->FoundDecl,
11344                                                   HadMultipleCandidates, OpLoc);
11345         if (FnExpr.isInvalid())
11346           return ExprError();
11347 
11348         // Determine the result type.
11349         QualType ResultTy = FnDecl->getReturnType();
11350         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11351         ResultTy = ResultTy.getNonLValueExprType(Context);
11352 
11353         CXXOperatorCallExpr *TheCall =
11354           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11355                                             Args, ResultTy, VK, OpLoc,
11356                                             FPFeatures.fp_contract);
11357 
11358         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11359                                 FnDecl))
11360           return ExprError();
11361 
11362         ArrayRef<const Expr *> ArgsArray(Args, 2);
11363         // Cut off the implicit 'this'.
11364         if (isa<CXXMethodDecl>(FnDecl))
11365           ArgsArray = ArgsArray.slice(1);
11366 
11367         // Check for a self move.
11368         if (Op == OO_Equal)
11369           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11370 
11371         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11372                   TheCall->getSourceRange(), VariadicDoesNotApply);
11373 
11374         return MaybeBindToTemporary(TheCall);
11375       } else {
11376         // We matched a built-in operator. Convert the arguments, then
11377         // break out so that we will build the appropriate built-in
11378         // operator node.
11379         ExprResult ArgsRes0 =
11380           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11381                                     Best->Conversions[0], AA_Passing);
11382         if (ArgsRes0.isInvalid())
11383           return ExprError();
11384         Args[0] = ArgsRes0.get();
11385 
11386         ExprResult ArgsRes1 =
11387           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11388                                     Best->Conversions[1], AA_Passing);
11389         if (ArgsRes1.isInvalid())
11390           return ExprError();
11391         Args[1] = ArgsRes1.get();
11392         break;
11393       }
11394     }
11395 
11396     case OR_No_Viable_Function: {
11397       // C++ [over.match.oper]p9:
11398       //   If the operator is the operator , [...] and there are no
11399       //   viable functions, then the operator is assumed to be the
11400       //   built-in operator and interpreted according to clause 5.
11401       if (Opc == BO_Comma)
11402         break;
11403 
11404       // For class as left operand for assignment or compound assigment
11405       // operator do not fall through to handling in built-in, but report that
11406       // no overloaded assignment operator found
11407       ExprResult Result = ExprError();
11408       if (Args[0]->getType()->isRecordType() &&
11409           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11410         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11411              << BinaryOperator::getOpcodeStr(Opc)
11412              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11413         if (Args[0]->getType()->isIncompleteType()) {
11414           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11415             << Args[0]->getType()
11416             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11417         }
11418       } else {
11419         // This is an erroneous use of an operator which can be overloaded by
11420         // a non-member function. Check for non-member operators which were
11421         // defined too late to be candidates.
11422         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11423           // FIXME: Recover by calling the found function.
11424           return ExprError();
11425 
11426         // No viable function; try to create a built-in operation, which will
11427         // produce an error. Then, show the non-viable candidates.
11428         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11429       }
11430       assert(Result.isInvalid() &&
11431              "C++ binary operator overloading is missing candidates!");
11432       if (Result.isInvalid())
11433         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11434                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11435       return Result;
11436     }
11437 
11438     case OR_Ambiguous:
11439       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11440           << BinaryOperator::getOpcodeStr(Opc)
11441           << Args[0]->getType() << Args[1]->getType()
11442           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11443       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11444                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11445       return ExprError();
11446 
11447     case OR_Deleted:
11448       if (isImplicitlyDeleted(Best->Function)) {
11449         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11450         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11451           << Context.getRecordType(Method->getParent())
11452           << getSpecialMember(Method);
11453 
11454         // The user probably meant to call this special member. Just
11455         // explain why it's deleted.
11456         NoteDeletedFunction(Method);
11457         return ExprError();
11458       } else {
11459         Diag(OpLoc, diag::err_ovl_deleted_oper)
11460           << Best->Function->isDeleted()
11461           << BinaryOperator::getOpcodeStr(Opc)
11462           << getDeletedOrUnavailableSuffix(Best->Function)
11463           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11464       }
11465       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11466                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11467       return ExprError();
11468   }
11469 
11470   // We matched a built-in operator; build it.
11471   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11472 }
11473 
11474 ExprResult
11475 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11476                                          SourceLocation RLoc,
11477                                          Expr *Base, Expr *Idx) {
11478   Expr *Args[2] = { Base, Idx };
11479   DeclarationName OpName =
11480       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11481 
11482   // If either side is type-dependent, create an appropriate dependent
11483   // expression.
11484   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11485 
11486     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11487     // CHECKME: no 'operator' keyword?
11488     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11489     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11490     UnresolvedLookupExpr *Fn
11491       = UnresolvedLookupExpr::Create(Context, NamingClass,
11492                                      NestedNameSpecifierLoc(), OpNameInfo,
11493                                      /*ADL*/ true, /*Overloaded*/ false,
11494                                      UnresolvedSetIterator(),
11495                                      UnresolvedSetIterator());
11496     // Can't add any actual overloads yet
11497 
11498     return new (Context)
11499         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11500                             Context.DependentTy, VK_RValue, RLoc, false);
11501   }
11502 
11503   // Handle placeholders on both operands.
11504   if (checkPlaceholderForOverload(*this, Args[0]))
11505     return ExprError();
11506   if (checkPlaceholderForOverload(*this, Args[1]))
11507     return ExprError();
11508 
11509   // Build an empty overload set.
11510   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11511 
11512   // Subscript can only be overloaded as a member function.
11513 
11514   // Add operator candidates that are member functions.
11515   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11516 
11517   // Add builtin operator candidates.
11518   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11519 
11520   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11521 
11522   // Perform overload resolution.
11523   OverloadCandidateSet::iterator Best;
11524   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11525     case OR_Success: {
11526       // We found a built-in operator or an overloaded operator.
11527       FunctionDecl *FnDecl = Best->Function;
11528 
11529       if (FnDecl) {
11530         // We matched an overloaded operator. Build a call to that
11531         // operator.
11532 
11533         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11534 
11535         // Convert the arguments.
11536         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11537         ExprResult Arg0 =
11538           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11539                                               Best->FoundDecl, Method);
11540         if (Arg0.isInvalid())
11541           return ExprError();
11542         Args[0] = Arg0.get();
11543 
11544         // Convert the arguments.
11545         ExprResult InputInit
11546           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11547                                                       Context,
11548                                                       FnDecl->getParamDecl(0)),
11549                                       SourceLocation(),
11550                                       Args[1]);
11551         if (InputInit.isInvalid())
11552           return ExprError();
11553 
11554         Args[1] = InputInit.getAs<Expr>();
11555 
11556         // Build the actual expression node.
11557         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11558         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11559         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11560                                                   Best->FoundDecl,
11561                                                   HadMultipleCandidates,
11562                                                   OpLocInfo.getLoc(),
11563                                                   OpLocInfo.getInfo());
11564         if (FnExpr.isInvalid())
11565           return ExprError();
11566 
11567         // Determine the result type
11568         QualType ResultTy = FnDecl->getReturnType();
11569         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11570         ResultTy = ResultTy.getNonLValueExprType(Context);
11571 
11572         CXXOperatorCallExpr *TheCall =
11573           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11574                                             FnExpr.get(), Args,
11575                                             ResultTy, VK, RLoc,
11576                                             false);
11577 
11578         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11579           return ExprError();
11580 
11581         return MaybeBindToTemporary(TheCall);
11582       } else {
11583         // We matched a built-in operator. Convert the arguments, then
11584         // break out so that we will build the appropriate built-in
11585         // operator node.
11586         ExprResult ArgsRes0 =
11587           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11588                                     Best->Conversions[0], AA_Passing);
11589         if (ArgsRes0.isInvalid())
11590           return ExprError();
11591         Args[0] = ArgsRes0.get();
11592 
11593         ExprResult ArgsRes1 =
11594           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11595                                     Best->Conversions[1], AA_Passing);
11596         if (ArgsRes1.isInvalid())
11597           return ExprError();
11598         Args[1] = ArgsRes1.get();
11599 
11600         break;
11601       }
11602     }
11603 
11604     case OR_No_Viable_Function: {
11605       if (CandidateSet.empty())
11606         Diag(LLoc, diag::err_ovl_no_oper)
11607           << Args[0]->getType() << /*subscript*/ 0
11608           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11609       else
11610         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11611           << Args[0]->getType()
11612           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11613       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11614                                   "[]", LLoc);
11615       return ExprError();
11616     }
11617 
11618     case OR_Ambiguous:
11619       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11620           << "[]"
11621           << Args[0]->getType() << Args[1]->getType()
11622           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11623       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11624                                   "[]", LLoc);
11625       return ExprError();
11626 
11627     case OR_Deleted:
11628       Diag(LLoc, diag::err_ovl_deleted_oper)
11629         << Best->Function->isDeleted() << "[]"
11630         << getDeletedOrUnavailableSuffix(Best->Function)
11631         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11632       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11633                                   "[]", LLoc);
11634       return ExprError();
11635     }
11636 
11637   // We matched a built-in operator; build it.
11638   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11639 }
11640 
11641 /// BuildCallToMemberFunction - Build a call to a member
11642 /// function. MemExpr is the expression that refers to the member
11643 /// function (and includes the object parameter), Args/NumArgs are the
11644 /// arguments to the function call (not including the object
11645 /// parameter). The caller needs to validate that the member
11646 /// expression refers to a non-static member function or an overloaded
11647 /// member function.
11648 ExprResult
11649 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11650                                 SourceLocation LParenLoc,
11651                                 MultiExprArg Args,
11652                                 SourceLocation RParenLoc) {
11653   assert(MemExprE->getType() == Context.BoundMemberTy ||
11654          MemExprE->getType() == Context.OverloadTy);
11655 
11656   // Dig out the member expression. This holds both the object
11657   // argument and the member function we're referring to.
11658   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11659 
11660   // Determine whether this is a call to a pointer-to-member function.
11661   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11662     assert(op->getType() == Context.BoundMemberTy);
11663     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11664 
11665     QualType fnType =
11666       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11667 
11668     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11669     QualType resultType = proto->getCallResultType(Context);
11670     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11671 
11672     // Check that the object type isn't more qualified than the
11673     // member function we're calling.
11674     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11675 
11676     QualType objectType = op->getLHS()->getType();
11677     if (op->getOpcode() == BO_PtrMemI)
11678       objectType = objectType->castAs<PointerType>()->getPointeeType();
11679     Qualifiers objectQuals = objectType.getQualifiers();
11680 
11681     Qualifiers difference = objectQuals - funcQuals;
11682     difference.removeObjCGCAttr();
11683     difference.removeAddressSpace();
11684     if (difference) {
11685       std::string qualsString = difference.getAsString();
11686       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11687         << fnType.getUnqualifiedType()
11688         << qualsString
11689         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11690     }
11691 
11692     CXXMemberCallExpr *call
11693       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11694                                         resultType, valueKind, RParenLoc);
11695 
11696     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11697                             call, nullptr))
11698       return ExprError();
11699 
11700     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11701       return ExprError();
11702 
11703     if (CheckOtherCall(call, proto))
11704       return ExprError();
11705 
11706     return MaybeBindToTemporary(call);
11707   }
11708 
11709   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11710     return new (Context)
11711         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11712 
11713   UnbridgedCastsSet UnbridgedCasts;
11714   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11715     return ExprError();
11716 
11717   MemberExpr *MemExpr;
11718   CXXMethodDecl *Method = nullptr;
11719   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11720   NestedNameSpecifier *Qualifier = nullptr;
11721   if (isa<MemberExpr>(NakedMemExpr)) {
11722     MemExpr = cast<MemberExpr>(NakedMemExpr);
11723     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11724     FoundDecl = MemExpr->getFoundDecl();
11725     Qualifier = MemExpr->getQualifier();
11726     UnbridgedCasts.restore();
11727   } else {
11728     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11729     Qualifier = UnresExpr->getQualifier();
11730 
11731     QualType ObjectType = UnresExpr->getBaseType();
11732     Expr::Classification ObjectClassification
11733       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11734                             : UnresExpr->getBase()->Classify(Context);
11735 
11736     // Add overload candidates
11737     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11738                                       OverloadCandidateSet::CSK_Normal);
11739 
11740     // FIXME: avoid copy.
11741     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11742     if (UnresExpr->hasExplicitTemplateArgs()) {
11743       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11744       TemplateArgs = &TemplateArgsBuffer;
11745     }
11746 
11747     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11748            E = UnresExpr->decls_end(); I != E; ++I) {
11749 
11750       NamedDecl *Func = *I;
11751       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11752       if (isa<UsingShadowDecl>(Func))
11753         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11754 
11755 
11756       // Microsoft supports direct constructor calls.
11757       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11758         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11759                              Args, CandidateSet);
11760       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11761         // If explicit template arguments were provided, we can't call a
11762         // non-template member function.
11763         if (TemplateArgs)
11764           continue;
11765 
11766         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11767                            ObjectClassification, Args, CandidateSet,
11768                            /*SuppressUserConversions=*/false);
11769       } else {
11770         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11771                                    I.getPair(), ActingDC, TemplateArgs,
11772                                    ObjectType,  ObjectClassification,
11773                                    Args, CandidateSet,
11774                                    /*SuppressUsedConversions=*/false);
11775       }
11776     }
11777 
11778     DeclarationName DeclName = UnresExpr->getMemberName();
11779 
11780     UnbridgedCasts.restore();
11781 
11782     OverloadCandidateSet::iterator Best;
11783     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11784                                             Best)) {
11785     case OR_Success:
11786       Method = cast<CXXMethodDecl>(Best->Function);
11787       FoundDecl = Best->FoundDecl;
11788       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11789       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11790         return ExprError();
11791       // If FoundDecl is different from Method (such as if one is a template
11792       // and the other a specialization), make sure DiagnoseUseOfDecl is
11793       // called on both.
11794       // FIXME: This would be more comprehensively addressed by modifying
11795       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11796       // being used.
11797       if (Method != FoundDecl.getDecl() &&
11798                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11799         return ExprError();
11800       break;
11801 
11802     case OR_No_Viable_Function:
11803       Diag(UnresExpr->getMemberLoc(),
11804            diag::err_ovl_no_viable_member_function_in_call)
11805         << DeclName << MemExprE->getSourceRange();
11806       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11807       // FIXME: Leaking incoming expressions!
11808       return ExprError();
11809 
11810     case OR_Ambiguous:
11811       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11812         << DeclName << MemExprE->getSourceRange();
11813       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11814       // FIXME: Leaking incoming expressions!
11815       return ExprError();
11816 
11817     case OR_Deleted:
11818       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11819         << Best->Function->isDeleted()
11820         << DeclName
11821         << getDeletedOrUnavailableSuffix(Best->Function)
11822         << MemExprE->getSourceRange();
11823       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11824       // FIXME: Leaking incoming expressions!
11825       return ExprError();
11826     }
11827 
11828     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11829 
11830     // If overload resolution picked a static member, build a
11831     // non-member call based on that function.
11832     if (Method->isStatic()) {
11833       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11834                                    RParenLoc);
11835     }
11836 
11837     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11838   }
11839 
11840   QualType ResultType = Method->getReturnType();
11841   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11842   ResultType = ResultType.getNonLValueExprType(Context);
11843 
11844   assert(Method && "Member call to something that isn't a method?");
11845   CXXMemberCallExpr *TheCall =
11846     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11847                                     ResultType, VK, RParenLoc);
11848 
11849   // (CUDA B.1): Check for invalid calls between targets.
11850   if (getLangOpts().CUDA) {
11851     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11852       if (CheckCUDATarget(Caller, Method)) {
11853         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11854             << IdentifyCUDATarget(Method) << Method->getIdentifier()
11855             << IdentifyCUDATarget(Caller);
11856         return ExprError();
11857       }
11858     }
11859   }
11860 
11861   // Check for a valid return type.
11862   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11863                           TheCall, Method))
11864     return ExprError();
11865 
11866   // Convert the object argument (for a non-static member function call).
11867   // We only need to do this if there was actually an overload; otherwise
11868   // it was done at lookup.
11869   if (!Method->isStatic()) {
11870     ExprResult ObjectArg =
11871       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11872                                           FoundDecl, Method);
11873     if (ObjectArg.isInvalid())
11874       return ExprError();
11875     MemExpr->setBase(ObjectArg.get());
11876   }
11877 
11878   // Convert the rest of the arguments
11879   const FunctionProtoType *Proto =
11880     Method->getType()->getAs<FunctionProtoType>();
11881   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11882                               RParenLoc))
11883     return ExprError();
11884 
11885   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11886 
11887   if (CheckFunctionCall(Method, TheCall, Proto))
11888     return ExprError();
11889 
11890   // In the case the method to call was not selected by the overloading
11891   // resolution process, we still need to handle the enable_if attribute. Do
11892   // that here, so it will not hide previous -- and more relevant -- errors
11893   if (isa<MemberExpr>(NakedMemExpr)) {
11894     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
11895       Diag(MemExprE->getLocStart(),
11896            diag::err_ovl_no_viable_member_function_in_call)
11897           << Method << Method->getSourceRange();
11898       Diag(Method->getLocation(),
11899            diag::note_ovl_candidate_disabled_by_enable_if_attr)
11900           << Attr->getCond()->getSourceRange() << Attr->getMessage();
11901       return ExprError();
11902     }
11903   }
11904 
11905   if ((isa<CXXConstructorDecl>(CurContext) ||
11906        isa<CXXDestructorDecl>(CurContext)) &&
11907       TheCall->getMethodDecl()->isPure()) {
11908     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11909 
11910     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
11911         MemExpr->performsVirtualDispatch(getLangOpts())) {
11912       Diag(MemExpr->getLocStart(),
11913            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11914         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11915         << MD->getParent()->getDeclName();
11916 
11917       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11918       if (getLangOpts().AppleKext)
11919         Diag(MemExpr->getLocStart(),
11920              diag::note_pure_qualified_call_kext)
11921              << MD->getParent()->getDeclName()
11922              << MD->getDeclName();
11923     }
11924   }
11925   return MaybeBindToTemporary(TheCall);
11926 }
11927 
11928 /// BuildCallToObjectOfClassType - Build a call to an object of class
11929 /// type (C++ [over.call.object]), which can end up invoking an
11930 /// overloaded function call operator (@c operator()) or performing a
11931 /// user-defined conversion on the object argument.
11932 ExprResult
11933 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11934                                    SourceLocation LParenLoc,
11935                                    MultiExprArg Args,
11936                                    SourceLocation RParenLoc) {
11937   if (checkPlaceholderForOverload(*this, Obj))
11938     return ExprError();
11939   ExprResult Object = Obj;
11940 
11941   UnbridgedCastsSet UnbridgedCasts;
11942   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11943     return ExprError();
11944 
11945   assert(Object.get()->getType()->isRecordType() &&
11946          "Requires object type argument");
11947   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11948 
11949   // C++ [over.call.object]p1:
11950   //  If the primary-expression E in the function call syntax
11951   //  evaluates to a class object of type "cv T", then the set of
11952   //  candidate functions includes at least the function call
11953   //  operators of T. The function call operators of T are obtained by
11954   //  ordinary lookup of the name operator() in the context of
11955   //  (E).operator().
11956   OverloadCandidateSet CandidateSet(LParenLoc,
11957                                     OverloadCandidateSet::CSK_Operator);
11958   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11959 
11960   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11961                           diag::err_incomplete_object_call, Object.get()))
11962     return true;
11963 
11964   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11965   LookupQualifiedName(R, Record->getDecl());
11966   R.suppressDiagnostics();
11967 
11968   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11969        Oper != OperEnd; ++Oper) {
11970     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11971                        Object.get()->Classify(Context),
11972                        Args, CandidateSet,
11973                        /*SuppressUserConversions=*/ false);
11974   }
11975 
11976   // C++ [over.call.object]p2:
11977   //   In addition, for each (non-explicit in C++0x) conversion function
11978   //   declared in T of the form
11979   //
11980   //        operator conversion-type-id () cv-qualifier;
11981   //
11982   //   where cv-qualifier is the same cv-qualification as, or a
11983   //   greater cv-qualification than, cv, and where conversion-type-id
11984   //   denotes the type "pointer to function of (P1,...,Pn) returning
11985   //   R", or the type "reference to pointer to function of
11986   //   (P1,...,Pn) returning R", or the type "reference to function
11987   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11988   //   is also considered as a candidate function. Similarly,
11989   //   surrogate call functions are added to the set of candidate
11990   //   functions for each conversion function declared in an
11991   //   accessible base class provided the function is not hidden
11992   //   within T by another intervening declaration.
11993   const auto &Conversions =
11994       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11995   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
11996     NamedDecl *D = *I;
11997     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11998     if (isa<UsingShadowDecl>(D))
11999       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12000 
12001     // Skip over templated conversion functions; they aren't
12002     // surrogates.
12003     if (isa<FunctionTemplateDecl>(D))
12004       continue;
12005 
12006     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12007     if (!Conv->isExplicit()) {
12008       // Strip the reference type (if any) and then the pointer type (if
12009       // any) to get down to what might be a function type.
12010       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12011       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12012         ConvType = ConvPtrType->getPointeeType();
12013 
12014       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12015       {
12016         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12017                               Object.get(), Args, CandidateSet);
12018       }
12019     }
12020   }
12021 
12022   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12023 
12024   // Perform overload resolution.
12025   OverloadCandidateSet::iterator Best;
12026   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12027                              Best)) {
12028   case OR_Success:
12029     // Overload resolution succeeded; we'll build the appropriate call
12030     // below.
12031     break;
12032 
12033   case OR_No_Viable_Function:
12034     if (CandidateSet.empty())
12035       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12036         << Object.get()->getType() << /*call*/ 1
12037         << Object.get()->getSourceRange();
12038     else
12039       Diag(Object.get()->getLocStart(),
12040            diag::err_ovl_no_viable_object_call)
12041         << Object.get()->getType() << Object.get()->getSourceRange();
12042     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12043     break;
12044 
12045   case OR_Ambiguous:
12046     Diag(Object.get()->getLocStart(),
12047          diag::err_ovl_ambiguous_object_call)
12048       << Object.get()->getType() << Object.get()->getSourceRange();
12049     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12050     break;
12051 
12052   case OR_Deleted:
12053     Diag(Object.get()->getLocStart(),
12054          diag::err_ovl_deleted_object_call)
12055       << Best->Function->isDeleted()
12056       << Object.get()->getType()
12057       << getDeletedOrUnavailableSuffix(Best->Function)
12058       << Object.get()->getSourceRange();
12059     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12060     break;
12061   }
12062 
12063   if (Best == CandidateSet.end())
12064     return true;
12065 
12066   UnbridgedCasts.restore();
12067 
12068   if (Best->Function == nullptr) {
12069     // Since there is no function declaration, this is one of the
12070     // surrogate candidates. Dig out the conversion function.
12071     CXXConversionDecl *Conv
12072       = cast<CXXConversionDecl>(
12073                          Best->Conversions[0].UserDefined.ConversionFunction);
12074 
12075     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12076                               Best->FoundDecl);
12077     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12078       return ExprError();
12079     assert(Conv == Best->FoundDecl.getDecl() &&
12080              "Found Decl & conversion-to-functionptr should be same, right?!");
12081     // We selected one of the surrogate functions that converts the
12082     // object parameter to a function pointer. Perform the conversion
12083     // on the object argument, then let ActOnCallExpr finish the job.
12084 
12085     // Create an implicit member expr to refer to the conversion operator.
12086     // and then call it.
12087     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12088                                              Conv, HadMultipleCandidates);
12089     if (Call.isInvalid())
12090       return ExprError();
12091     // Record usage of conversion in an implicit cast.
12092     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12093                                     CK_UserDefinedConversion, Call.get(),
12094                                     nullptr, VK_RValue);
12095 
12096     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12097   }
12098 
12099   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12100 
12101   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12102   // that calls this method, using Object for the implicit object
12103   // parameter and passing along the remaining arguments.
12104   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12105 
12106   // An error diagnostic has already been printed when parsing the declaration.
12107   if (Method->isInvalidDecl())
12108     return ExprError();
12109 
12110   const FunctionProtoType *Proto =
12111     Method->getType()->getAs<FunctionProtoType>();
12112 
12113   unsigned NumParams = Proto->getNumParams();
12114 
12115   DeclarationNameInfo OpLocInfo(
12116                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12117   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12118   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12119                                            HadMultipleCandidates,
12120                                            OpLocInfo.getLoc(),
12121                                            OpLocInfo.getInfo());
12122   if (NewFn.isInvalid())
12123     return true;
12124 
12125   // Build the full argument list for the method call (the implicit object
12126   // parameter is placed at the beginning of the list).
12127   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12128   MethodArgs[0] = Object.get();
12129   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12130 
12131   // Once we've built TheCall, all of the expressions are properly
12132   // owned.
12133   QualType ResultTy = Method->getReturnType();
12134   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12135   ResultTy = ResultTy.getNonLValueExprType(Context);
12136 
12137   CXXOperatorCallExpr *TheCall = new (Context)
12138       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12139                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12140                           ResultTy, VK, RParenLoc, false);
12141   MethodArgs.reset();
12142 
12143   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12144     return true;
12145 
12146   // We may have default arguments. If so, we need to allocate more
12147   // slots in the call for them.
12148   if (Args.size() < NumParams)
12149     TheCall->setNumArgs(Context, NumParams + 1);
12150 
12151   bool IsError = false;
12152 
12153   // Initialize the implicit object parameter.
12154   ExprResult ObjRes =
12155     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12156                                         Best->FoundDecl, Method);
12157   if (ObjRes.isInvalid())
12158     IsError = true;
12159   else
12160     Object = ObjRes;
12161   TheCall->setArg(0, Object.get());
12162 
12163   // Check the argument types.
12164   for (unsigned i = 0; i != NumParams; i++) {
12165     Expr *Arg;
12166     if (i < Args.size()) {
12167       Arg = Args[i];
12168 
12169       // Pass the argument.
12170 
12171       ExprResult InputInit
12172         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12173                                                     Context,
12174                                                     Method->getParamDecl(i)),
12175                                     SourceLocation(), Arg);
12176 
12177       IsError |= InputInit.isInvalid();
12178       Arg = InputInit.getAs<Expr>();
12179     } else {
12180       ExprResult DefArg
12181         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12182       if (DefArg.isInvalid()) {
12183         IsError = true;
12184         break;
12185       }
12186 
12187       Arg = DefArg.getAs<Expr>();
12188     }
12189 
12190     TheCall->setArg(i + 1, Arg);
12191   }
12192 
12193   // If this is a variadic call, handle args passed through "...".
12194   if (Proto->isVariadic()) {
12195     // Promote the arguments (C99 6.5.2.2p7).
12196     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12197       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12198                                                         nullptr);
12199       IsError |= Arg.isInvalid();
12200       TheCall->setArg(i + 1, Arg.get());
12201     }
12202   }
12203 
12204   if (IsError) return true;
12205 
12206   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12207 
12208   if (CheckFunctionCall(Method, TheCall, Proto))
12209     return true;
12210 
12211   return MaybeBindToTemporary(TheCall);
12212 }
12213 
12214 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12215 ///  (if one exists), where @c Base is an expression of class type and
12216 /// @c Member is the name of the member we're trying to find.
12217 ExprResult
12218 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12219                                bool *NoArrowOperatorFound) {
12220   assert(Base->getType()->isRecordType() &&
12221          "left-hand side must have class type");
12222 
12223   if (checkPlaceholderForOverload(*this, Base))
12224     return ExprError();
12225 
12226   SourceLocation Loc = Base->getExprLoc();
12227 
12228   // C++ [over.ref]p1:
12229   //
12230   //   [...] An expression x->m is interpreted as (x.operator->())->m
12231   //   for a class object x of type T if T::operator->() exists and if
12232   //   the operator is selected as the best match function by the
12233   //   overload resolution mechanism (13.3).
12234   DeclarationName OpName =
12235     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12236   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12237   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12238 
12239   if (RequireCompleteType(Loc, Base->getType(),
12240                           diag::err_typecheck_incomplete_tag, Base))
12241     return ExprError();
12242 
12243   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12244   LookupQualifiedName(R, BaseRecord->getDecl());
12245   R.suppressDiagnostics();
12246 
12247   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12248        Oper != OperEnd; ++Oper) {
12249     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12250                        None, CandidateSet, /*SuppressUserConversions=*/false);
12251   }
12252 
12253   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12254 
12255   // Perform overload resolution.
12256   OverloadCandidateSet::iterator Best;
12257   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12258   case OR_Success:
12259     // Overload resolution succeeded; we'll build the call below.
12260     break;
12261 
12262   case OR_No_Viable_Function:
12263     if (CandidateSet.empty()) {
12264       QualType BaseType = Base->getType();
12265       if (NoArrowOperatorFound) {
12266         // Report this specific error to the caller instead of emitting a
12267         // diagnostic, as requested.
12268         *NoArrowOperatorFound = true;
12269         return ExprError();
12270       }
12271       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12272         << BaseType << Base->getSourceRange();
12273       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12274         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12275           << FixItHint::CreateReplacement(OpLoc, ".");
12276       }
12277     } else
12278       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12279         << "operator->" << Base->getSourceRange();
12280     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12281     return ExprError();
12282 
12283   case OR_Ambiguous:
12284     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12285       << "->" << Base->getType() << Base->getSourceRange();
12286     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12287     return ExprError();
12288 
12289   case OR_Deleted:
12290     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12291       << Best->Function->isDeleted()
12292       << "->"
12293       << getDeletedOrUnavailableSuffix(Best->Function)
12294       << Base->getSourceRange();
12295     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12296     return ExprError();
12297   }
12298 
12299   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12300 
12301   // Convert the object parameter.
12302   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12303   ExprResult BaseResult =
12304     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12305                                         Best->FoundDecl, Method);
12306   if (BaseResult.isInvalid())
12307     return ExprError();
12308   Base = BaseResult.get();
12309 
12310   // Build the operator call.
12311   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12312                                             HadMultipleCandidates, OpLoc);
12313   if (FnExpr.isInvalid())
12314     return ExprError();
12315 
12316   QualType ResultTy = Method->getReturnType();
12317   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12318   ResultTy = ResultTy.getNonLValueExprType(Context);
12319   CXXOperatorCallExpr *TheCall =
12320     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12321                                       Base, ResultTy, VK, OpLoc, false);
12322 
12323   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12324           return ExprError();
12325 
12326   return MaybeBindToTemporary(TheCall);
12327 }
12328 
12329 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12330 /// a literal operator described by the provided lookup results.
12331 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12332                                           DeclarationNameInfo &SuffixInfo,
12333                                           ArrayRef<Expr*> Args,
12334                                           SourceLocation LitEndLoc,
12335                                        TemplateArgumentListInfo *TemplateArgs) {
12336   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12337 
12338   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12339                                     OverloadCandidateSet::CSK_Normal);
12340   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12341                         /*SuppressUserConversions=*/true);
12342 
12343   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12344 
12345   // Perform overload resolution. This will usually be trivial, but might need
12346   // to perform substitutions for a literal operator template.
12347   OverloadCandidateSet::iterator Best;
12348   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12349   case OR_Success:
12350   case OR_Deleted:
12351     break;
12352 
12353   case OR_No_Viable_Function:
12354     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12355       << R.getLookupName();
12356     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12357     return ExprError();
12358 
12359   case OR_Ambiguous:
12360     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12361     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12362     return ExprError();
12363   }
12364 
12365   FunctionDecl *FD = Best->Function;
12366   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12367                                         HadMultipleCandidates,
12368                                         SuffixInfo.getLoc(),
12369                                         SuffixInfo.getInfo());
12370   if (Fn.isInvalid())
12371     return true;
12372 
12373   // Check the argument types. This should almost always be a no-op, except
12374   // that array-to-pointer decay is applied to string literals.
12375   Expr *ConvArgs[2];
12376   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12377     ExprResult InputInit = PerformCopyInitialization(
12378       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12379       SourceLocation(), Args[ArgIdx]);
12380     if (InputInit.isInvalid())
12381       return true;
12382     ConvArgs[ArgIdx] = InputInit.get();
12383   }
12384 
12385   QualType ResultTy = FD->getReturnType();
12386   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12387   ResultTy = ResultTy.getNonLValueExprType(Context);
12388 
12389   UserDefinedLiteral *UDL =
12390     new (Context) UserDefinedLiteral(Context, Fn.get(),
12391                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12392                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12393 
12394   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12395     return ExprError();
12396 
12397   if (CheckFunctionCall(FD, UDL, nullptr))
12398     return ExprError();
12399 
12400   return MaybeBindToTemporary(UDL);
12401 }
12402 
12403 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12404 /// given LookupResult is non-empty, it is assumed to describe a member which
12405 /// will be invoked. Otherwise, the function will be found via argument
12406 /// dependent lookup.
12407 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12408 /// otherwise CallExpr is set to ExprError() and some non-success value
12409 /// is returned.
12410 Sema::ForRangeStatus
12411 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12412                                 SourceLocation RangeLoc, VarDecl *Decl,
12413                                 BeginEndFunction BEF,
12414                                 const DeclarationNameInfo &NameInfo,
12415                                 LookupResult &MemberLookup,
12416                                 OverloadCandidateSet *CandidateSet,
12417                                 Expr *Range, ExprResult *CallExpr) {
12418   CandidateSet->clear();
12419   if (!MemberLookup.empty()) {
12420     ExprResult MemberRef =
12421         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12422                                  /*IsPtr=*/false, CXXScopeSpec(),
12423                                  /*TemplateKWLoc=*/SourceLocation(),
12424                                  /*FirstQualifierInScope=*/nullptr,
12425                                  MemberLookup,
12426                                  /*TemplateArgs=*/nullptr, S);
12427     if (MemberRef.isInvalid()) {
12428       *CallExpr = ExprError();
12429       Diag(Range->getLocStart(), diag::note_in_for_range)
12430           << RangeLoc << BEF << Range->getType();
12431       return FRS_DiagnosticIssued;
12432     }
12433     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12434     if (CallExpr->isInvalid()) {
12435       *CallExpr = ExprError();
12436       Diag(Range->getLocStart(), diag::note_in_for_range)
12437           << RangeLoc << BEF << Range->getType();
12438       return FRS_DiagnosticIssued;
12439     }
12440   } else {
12441     UnresolvedSet<0> FoundNames;
12442     UnresolvedLookupExpr *Fn =
12443       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12444                                    NestedNameSpecifierLoc(), NameInfo,
12445                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12446                                    FoundNames.begin(), FoundNames.end());
12447 
12448     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12449                                                     CandidateSet, CallExpr);
12450     if (CandidateSet->empty() || CandidateSetError) {
12451       *CallExpr = ExprError();
12452       return FRS_NoViableFunction;
12453     }
12454     OverloadCandidateSet::iterator Best;
12455     OverloadingResult OverloadResult =
12456         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12457 
12458     if (OverloadResult == OR_No_Viable_Function) {
12459       *CallExpr = ExprError();
12460       return FRS_NoViableFunction;
12461     }
12462     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12463                                          Loc, nullptr, CandidateSet, &Best,
12464                                          OverloadResult,
12465                                          /*AllowTypoCorrection=*/false);
12466     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12467       *CallExpr = ExprError();
12468       Diag(Range->getLocStart(), diag::note_in_for_range)
12469           << RangeLoc << BEF << Range->getType();
12470       return FRS_DiagnosticIssued;
12471     }
12472   }
12473   return FRS_Success;
12474 }
12475 
12476 
12477 /// FixOverloadedFunctionReference - E is an expression that refers to
12478 /// a C++ overloaded function (possibly with some parentheses and
12479 /// perhaps a '&' around it). We have resolved the overloaded function
12480 /// to the function declaration Fn, so patch up the expression E to
12481 /// refer (possibly indirectly) to Fn. Returns the new expr.
12482 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12483                                            FunctionDecl *Fn) {
12484   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12485     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12486                                                    Found, Fn);
12487     if (SubExpr == PE->getSubExpr())
12488       return PE;
12489 
12490     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12491   }
12492 
12493   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12494     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12495                                                    Found, Fn);
12496     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12497                                SubExpr->getType()) &&
12498            "Implicit cast type cannot be determined from overload");
12499     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12500     if (SubExpr == ICE->getSubExpr())
12501       return ICE;
12502 
12503     return ImplicitCastExpr::Create(Context, ICE->getType(),
12504                                     ICE->getCastKind(),
12505                                     SubExpr, nullptr,
12506                                     ICE->getValueKind());
12507   }
12508 
12509   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12510     assert(UnOp->getOpcode() == UO_AddrOf &&
12511            "Can only take the address of an overloaded function");
12512     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12513       if (Method->isStatic()) {
12514         // Do nothing: static member functions aren't any different
12515         // from non-member functions.
12516       } else {
12517         // Fix the subexpression, which really has to be an
12518         // UnresolvedLookupExpr holding an overloaded member function
12519         // or template.
12520         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12521                                                        Found, Fn);
12522         if (SubExpr == UnOp->getSubExpr())
12523           return UnOp;
12524 
12525         assert(isa<DeclRefExpr>(SubExpr)
12526                && "fixed to something other than a decl ref");
12527         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12528                && "fixed to a member ref with no nested name qualifier");
12529 
12530         // We have taken the address of a pointer to member
12531         // function. Perform the computation here so that we get the
12532         // appropriate pointer to member type.
12533         QualType ClassType
12534           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12535         QualType MemPtrType
12536           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12537 
12538         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12539                                            VK_RValue, OK_Ordinary,
12540                                            UnOp->getOperatorLoc());
12541       }
12542     }
12543     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12544                                                    Found, Fn);
12545     if (SubExpr == UnOp->getSubExpr())
12546       return UnOp;
12547 
12548     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12549                                      Context.getPointerType(SubExpr->getType()),
12550                                        VK_RValue, OK_Ordinary,
12551                                        UnOp->getOperatorLoc());
12552   }
12553 
12554   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12555     // FIXME: avoid copy.
12556     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12557     if (ULE->hasExplicitTemplateArgs()) {
12558       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12559       TemplateArgs = &TemplateArgsBuffer;
12560     }
12561 
12562     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12563                                            ULE->getQualifierLoc(),
12564                                            ULE->getTemplateKeywordLoc(),
12565                                            Fn,
12566                                            /*enclosing*/ false, // FIXME?
12567                                            ULE->getNameLoc(),
12568                                            Fn->getType(),
12569                                            VK_LValue,
12570                                            Found.getDecl(),
12571                                            TemplateArgs);
12572     MarkDeclRefReferenced(DRE);
12573     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12574     return DRE;
12575   }
12576 
12577   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12578     // FIXME: avoid copy.
12579     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12580     if (MemExpr->hasExplicitTemplateArgs()) {
12581       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12582       TemplateArgs = &TemplateArgsBuffer;
12583     }
12584 
12585     Expr *Base;
12586 
12587     // If we're filling in a static method where we used to have an
12588     // implicit member access, rewrite to a simple decl ref.
12589     if (MemExpr->isImplicitAccess()) {
12590       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12591         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12592                                                MemExpr->getQualifierLoc(),
12593                                                MemExpr->getTemplateKeywordLoc(),
12594                                                Fn,
12595                                                /*enclosing*/ false,
12596                                                MemExpr->getMemberLoc(),
12597                                                Fn->getType(),
12598                                                VK_LValue,
12599                                                Found.getDecl(),
12600                                                TemplateArgs);
12601         MarkDeclRefReferenced(DRE);
12602         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12603         return DRE;
12604       } else {
12605         SourceLocation Loc = MemExpr->getMemberLoc();
12606         if (MemExpr->getQualifier())
12607           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12608         CheckCXXThisCapture(Loc);
12609         Base = new (Context) CXXThisExpr(Loc,
12610                                          MemExpr->getBaseType(),
12611                                          /*isImplicit=*/true);
12612       }
12613     } else
12614       Base = MemExpr->getBase();
12615 
12616     ExprValueKind valueKind;
12617     QualType type;
12618     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12619       valueKind = VK_LValue;
12620       type = Fn->getType();
12621     } else {
12622       valueKind = VK_RValue;
12623       type = Context.BoundMemberTy;
12624     }
12625 
12626     MemberExpr *ME = MemberExpr::Create(
12627         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12628         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12629         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12630         OK_Ordinary);
12631     ME->setHadMultipleCandidates(true);
12632     MarkMemberReferenced(ME);
12633     return ME;
12634   }
12635 
12636   llvm_unreachable("Invalid reference to overloaded function");
12637 }
12638 
12639 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12640                                                 DeclAccessPair Found,
12641                                                 FunctionDecl *Fn) {
12642   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12643 }
12644