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 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42   return llvm::any_of(FD->parameters(),
43                       std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
44 }
45 
46 /// A convenience routine for creating a decayed reference to a function.
47 static ExprResult
48 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
49                       bool HadMultipleCandidates,
50                       SourceLocation Loc = SourceLocation(),
51                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
52   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
53     return ExprError();
54   // If FoundDecl is different from Fn (such as if one is a template
55   // and the other a specialization), make sure DiagnoseUseOfDecl is
56   // called on both.
57   // FIXME: This would be more comprehensively addressed by modifying
58   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
59   // being used.
60   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
61     return ExprError();
62   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
63                                                  VK_LValue, Loc, LocInfo);
64   if (HadMultipleCandidates)
65     DRE->setHadMultipleCandidates(true);
66 
67   S.MarkDeclRefReferenced(DRE);
68   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
69                              CK_FunctionToPointerDecay);
70 }
71 
72 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
73                                  bool InOverloadResolution,
74                                  StandardConversionSequence &SCS,
75                                  bool CStyle,
76                                  bool AllowObjCWritebackConversion);
77 
78 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79                                                  QualType &ToType,
80                                                  bool InOverloadResolution,
81                                                  StandardConversionSequence &SCS,
82                                                  bool CStyle);
83 static OverloadingResult
84 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
85                         UserDefinedConversionSequence& User,
86                         OverloadCandidateSet& Conversions,
87                         bool AllowExplicit,
88                         bool AllowObjCConversionOnExplicit);
89 
90 
91 static ImplicitConversionSequence::CompareKind
92 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
93                                    const StandardConversionSequence& SCS1,
94                                    const StandardConversionSequence& SCS2);
95 
96 static ImplicitConversionSequence::CompareKind
97 CompareQualificationConversions(Sema &S,
98                                 const StandardConversionSequence& SCS1,
99                                 const StandardConversionSequence& SCS2);
100 
101 static ImplicitConversionSequence::CompareKind
102 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
103                                 const StandardConversionSequence& SCS1,
104                                 const StandardConversionSequence& SCS2);
105 
106 /// GetConversionRank - Retrieve the implicit conversion rank
107 /// corresponding to the given implicit conversion kind.
108 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
109   static const ImplicitConversionRank
110     Rank[(int)ICK_Num_Conversion_Kinds] = {
111     ICR_Exact_Match,
112     ICR_Exact_Match,
113     ICR_Exact_Match,
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Promotion,
118     ICR_Promotion,
119     ICR_Promotion,
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_Conversion,
131     ICR_Complex_Real_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Writeback_Conversion,
135     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
136                      // it was omitted by the patch that added
137                      // ICK_Zero_Event_Conversion
138     ICR_C_Conversion
139   };
140   return Rank[(int)Kind];
141 }
142 
143 /// GetImplicitConversionName - Return the name of this kind of
144 /// implicit conversion.
145 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
146   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
147     "No conversion",
148     "Lvalue-to-rvalue",
149     "Array-to-pointer",
150     "Function-to-pointer",
151     "Noreturn adjustment",
152     "Qualification",
153     "Integral promotion",
154     "Floating point promotion",
155     "Complex promotion",
156     "Integral conversion",
157     "Floating conversion",
158     "Complex conversion",
159     "Floating-integral conversion",
160     "Pointer conversion",
161     "Pointer-to-member conversion",
162     "Boolean conversion",
163     "Compatible-types conversion",
164     "Derived-to-base conversion",
165     "Vector conversion",
166     "Vector splat",
167     "Complex-real conversion",
168     "Block Pointer conversion",
169     "Transparent Union Conversion",
170     "Writeback conversion",
171     "OpenCL Zero Event Conversion",
172     "C specific type conversion"
173   };
174   return Name[Kind];
175 }
176 
177 /// StandardConversionSequence - Set the standard conversion
178 /// sequence to the identity conversion.
179 void StandardConversionSequence::setAsIdentityConversion() {
180   First = ICK_Identity;
181   Second = ICK_Identity;
182   Third = ICK_Identity;
183   DeprecatedStringLiteralToCharPtr = false;
184   QualificationIncludesObjCLifetime = false;
185   ReferenceBinding = false;
186   DirectBinding = false;
187   IsLvalueReference = true;
188   BindsToFunctionLvalue = false;
189   BindsToRvalue = false;
190   BindsImplicitObjectArgumentWithoutRefQualifier = false;
191   ObjCLifetimeConversionBinding = false;
192   CopyConstructor = nullptr;
193 }
194 
195 /// getRank - Retrieve the rank of this standard conversion sequence
196 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
197 /// implicit conversions.
198 ImplicitConversionRank StandardConversionSequence::getRank() const {
199   ImplicitConversionRank Rank = ICR_Exact_Match;
200   if  (GetConversionRank(First) > Rank)
201     Rank = GetConversionRank(First);
202   if  (GetConversionRank(Second) > Rank)
203     Rank = GetConversionRank(Second);
204   if  (GetConversionRank(Third) > Rank)
205     Rank = GetConversionRank(Third);
206   return Rank;
207 }
208 
209 /// isPointerConversionToBool - Determines whether this conversion is
210 /// a conversion of a pointer or pointer-to-member to bool. This is
211 /// used as part of the ranking of standard conversion sequences
212 /// (C++ 13.3.3.2p4).
213 bool StandardConversionSequence::isPointerConversionToBool() const {
214   // Note that FromType has not necessarily been transformed by the
215   // array-to-pointer or function-to-pointer implicit conversions, so
216   // check for their presence as well as checking whether FromType is
217   // a pointer.
218   if (getToType(1)->isBooleanType() &&
219       (getFromType()->isPointerType() ||
220        getFromType()->isObjCObjectPointerType() ||
221        getFromType()->isBlockPointerType() ||
222        getFromType()->isNullPtrType() ||
223        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
224     return true;
225 
226   return false;
227 }
228 
229 /// isPointerConversionToVoidPointer - Determines whether this
230 /// conversion is a conversion of a pointer to a void pointer. This is
231 /// used as part of the ranking of standard conversion sequences (C++
232 /// 13.3.3.2p4).
233 bool
234 StandardConversionSequence::
235 isPointerConversionToVoidPointer(ASTContext& Context) const {
236   QualType FromType = getFromType();
237   QualType ToType = getToType(1);
238 
239   // Note that FromType has not necessarily been transformed by the
240   // array-to-pointer implicit conversion, so check for its presence
241   // and redo the conversion to get a pointer.
242   if (First == ICK_Array_To_Pointer)
243     FromType = Context.getArrayDecayedType(FromType);
244 
245   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
246     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
247       return ToPtrType->getPointeeType()->isVoidType();
248 
249   return false;
250 }
251 
252 /// Skip any implicit casts which could be either part of a narrowing conversion
253 /// or after one in an implicit conversion.
254 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
255   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
256     switch (ICE->getCastKind()) {
257     case CK_NoOp:
258     case CK_IntegralCast:
259     case CK_IntegralToBoolean:
260     case CK_IntegralToFloating:
261     case CK_BooleanToSignedIntegral:
262     case CK_FloatingToIntegral:
263     case CK_FloatingToBoolean:
264     case CK_FloatingCast:
265       Converted = ICE->getSubExpr();
266       continue;
267 
268     default:
269       return Converted;
270     }
271   }
272 
273   return Converted;
274 }
275 
276 /// Check if this standard conversion sequence represents a narrowing
277 /// conversion, according to C++11 [dcl.init.list]p7.
278 ///
279 /// \param Ctx  The AST context.
280 /// \param Converted  The result of applying this standard conversion sequence.
281 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
282 ///        value of the expression prior to the narrowing conversion.
283 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
284 ///        type of the expression prior to the narrowing conversion.
285 NarrowingKind
286 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
287                                              const Expr *Converted,
288                                              APValue &ConstantValue,
289                                              QualType &ConstantType) const {
290   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
291 
292   // C++11 [dcl.init.list]p7:
293   //   A narrowing conversion is an implicit conversion ...
294   QualType FromType = getToType(0);
295   QualType ToType = getToType(1);
296 
297   // A conversion to an enumeration type is narrowing if the conversion to
298   // the underlying type is narrowing. This only arises for expressions of
299   // the form 'Enum{init}'.
300   if (auto *ET = ToType->getAs<EnumType>())
301     ToType = ET->getDecl()->getIntegerType();
302 
303   switch (Second) {
304   // 'bool' is an integral type; dispatch to the right place to handle it.
305   case ICK_Boolean_Conversion:
306     if (FromType->isRealFloatingType())
307       goto FloatingIntegralConversion;
308     if (FromType->isIntegralOrUnscopedEnumerationType())
309       goto IntegralConversion;
310     // Boolean conversions can be from pointers and pointers to members
311     // [conv.bool], and those aren't considered narrowing conversions.
312     return NK_Not_Narrowing;
313 
314   // -- from a floating-point type to an integer type, or
315   //
316   // -- from an integer type or unscoped enumeration type to a floating-point
317   //    type, except where the source is a constant expression and the actual
318   //    value after conversion will fit into the target type and will produce
319   //    the original value when converted back to the original type, or
320   case ICK_Floating_Integral:
321   FloatingIntegralConversion:
322     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
323       return NK_Type_Narrowing;
324     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
325       llvm::APSInt IntConstantValue;
326       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
327       if (Initializer &&
328           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
329         // Convert the integer to the floating type.
330         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
331         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
332                                 llvm::APFloat::rmNearestTiesToEven);
333         // And back.
334         llvm::APSInt ConvertedValue = IntConstantValue;
335         bool ignored;
336         Result.convertToInteger(ConvertedValue,
337                                 llvm::APFloat::rmTowardZero, &ignored);
338         // If the resulting value is different, this was a narrowing conversion.
339         if (IntConstantValue != ConvertedValue) {
340           ConstantValue = APValue(IntConstantValue);
341           ConstantType = Initializer->getType();
342           return NK_Constant_Narrowing;
343         }
344       } else {
345         // Variables are always narrowings.
346         return NK_Variable_Narrowing;
347       }
348     }
349     return NK_Not_Narrowing;
350 
351   // -- from long double to double or float, or from double to float, except
352   //    where the source is a constant expression and the actual value after
353   //    conversion is within the range of values that can be represented (even
354   //    if it cannot be represented exactly), or
355   case ICK_Floating_Conversion:
356     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
357         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
358       // FromType is larger than ToType.
359       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
360       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
361         // Constant!
362         assert(ConstantValue.isFloat());
363         llvm::APFloat FloatVal = ConstantValue.getFloat();
364         // Convert the source value into the target type.
365         bool ignored;
366         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
367           Ctx.getFloatTypeSemantics(ToType),
368           llvm::APFloat::rmNearestTiesToEven, &ignored);
369         // If there was no overflow, the source value is within the range of
370         // values that can be represented.
371         if (ConvertStatus & llvm::APFloat::opOverflow) {
372           ConstantType = Initializer->getType();
373           return NK_Constant_Narrowing;
374         }
375       } else {
376         return NK_Variable_Narrowing;
377       }
378     }
379     return NK_Not_Narrowing;
380 
381   // -- from an integer type or unscoped enumeration type to an integer type
382   //    that cannot represent all the values of the original type, except where
383   //    the source is a constant expression and the actual value after
384   //    conversion will fit into the target type and will produce the original
385   //    value when converted back to the original type.
386   case ICK_Integral_Conversion:
387   IntegralConversion: {
388     assert(FromType->isIntegralOrUnscopedEnumerationType());
389     assert(ToType->isIntegralOrUnscopedEnumerationType());
390     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
391     const unsigned FromWidth = Ctx.getIntWidth(FromType);
392     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
393     const unsigned ToWidth = Ctx.getIntWidth(ToType);
394 
395     if (FromWidth > ToWidth ||
396         (FromWidth == ToWidth && FromSigned != ToSigned) ||
397         (FromSigned && !ToSigned)) {
398       // Not all values of FromType can be represented in ToType.
399       llvm::APSInt InitializerValue;
400       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
401       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
402         // Such conversions on variables are always narrowing.
403         return NK_Variable_Narrowing;
404       }
405       bool Narrowing = false;
406       if (FromWidth < ToWidth) {
407         // Negative -> unsigned is narrowing. Otherwise, more bits is never
408         // narrowing.
409         if (InitializerValue.isSigned() && InitializerValue.isNegative())
410           Narrowing = true;
411       } else {
412         // Add a bit to the InitializerValue so we don't have to worry about
413         // signed vs. unsigned comparisons.
414         InitializerValue = InitializerValue.extend(
415           InitializerValue.getBitWidth() + 1);
416         // Convert the initializer to and from the target width and signed-ness.
417         llvm::APSInt ConvertedValue = InitializerValue;
418         ConvertedValue = ConvertedValue.trunc(ToWidth);
419         ConvertedValue.setIsSigned(ToSigned);
420         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
421         ConvertedValue.setIsSigned(InitializerValue.isSigned());
422         // If the result is different, this was a narrowing conversion.
423         if (ConvertedValue != InitializerValue)
424           Narrowing = true;
425       }
426       if (Narrowing) {
427         ConstantType = Initializer->getType();
428         ConstantValue = APValue(InitializerValue);
429         return NK_Constant_Narrowing;
430       }
431     }
432     return NK_Not_Narrowing;
433   }
434 
435   default:
436     // Other kinds of conversions are not narrowings.
437     return NK_Not_Narrowing;
438   }
439 }
440 
441 /// dump - Print this standard conversion sequence to standard
442 /// error. Useful for debugging overloading issues.
443 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
444   raw_ostream &OS = llvm::errs();
445   bool PrintedSomething = false;
446   if (First != ICK_Identity) {
447     OS << GetImplicitConversionName(First);
448     PrintedSomething = true;
449   }
450 
451   if (Second != ICK_Identity) {
452     if (PrintedSomething) {
453       OS << " -> ";
454     }
455     OS << GetImplicitConversionName(Second);
456 
457     if (CopyConstructor) {
458       OS << " (by copy constructor)";
459     } else if (DirectBinding) {
460       OS << " (direct reference binding)";
461     } else if (ReferenceBinding) {
462       OS << " (reference binding)";
463     }
464     PrintedSomething = true;
465   }
466 
467   if (Third != ICK_Identity) {
468     if (PrintedSomething) {
469       OS << " -> ";
470     }
471     OS << GetImplicitConversionName(Third);
472     PrintedSomething = true;
473   }
474 
475   if (!PrintedSomething) {
476     OS << "No conversions required";
477   }
478 }
479 
480 /// dump - Print this user-defined conversion sequence to standard
481 /// error. Useful for debugging overloading issues.
482 void UserDefinedConversionSequence::dump() const {
483   raw_ostream &OS = llvm::errs();
484   if (Before.First || Before.Second || Before.Third) {
485     Before.dump();
486     OS << " -> ";
487   }
488   if (ConversionFunction)
489     OS << '\'' << *ConversionFunction << '\'';
490   else
491     OS << "aggregate initialization";
492   if (After.First || After.Second || After.Third) {
493     OS << " -> ";
494     After.dump();
495   }
496 }
497 
498 /// dump - Print this implicit conversion sequence to standard
499 /// error. Useful for debugging overloading issues.
500 void ImplicitConversionSequence::dump() const {
501   raw_ostream &OS = llvm::errs();
502   if (isStdInitializerListElement())
503     OS << "Worst std::initializer_list element conversion: ";
504   switch (ConversionKind) {
505   case StandardConversion:
506     OS << "Standard conversion: ";
507     Standard.dump();
508     break;
509   case UserDefinedConversion:
510     OS << "User-defined conversion: ";
511     UserDefined.dump();
512     break;
513   case EllipsisConversion:
514     OS << "Ellipsis conversion";
515     break;
516   case AmbiguousConversion:
517     OS << "Ambiguous conversion";
518     break;
519   case BadConversion:
520     OS << "Bad conversion";
521     break;
522   }
523 
524   OS << "\n";
525 }
526 
527 void AmbiguousConversionSequence::construct() {
528   new (&conversions()) ConversionSet();
529 }
530 
531 void AmbiguousConversionSequence::destruct() {
532   conversions().~ConversionSet();
533 }
534 
535 void
536 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
537   FromTypePtr = O.FromTypePtr;
538   ToTypePtr = O.ToTypePtr;
539   new (&conversions()) ConversionSet(O.conversions());
540 }
541 
542 namespace {
543   // Structure used by DeductionFailureInfo to store
544   // template argument information.
545   struct DFIArguments {
546     TemplateArgument FirstArg;
547     TemplateArgument SecondArg;
548   };
549   // Structure used by DeductionFailureInfo to store
550   // template parameter and template argument information.
551   struct DFIParamWithArguments : DFIArguments {
552     TemplateParameter Param;
553   };
554   // Structure used by DeductionFailureInfo to store template argument
555   // information and the index of the problematic call argument.
556   struct DFIDeducedMismatchArgs : DFIArguments {
557     TemplateArgumentList *TemplateArgs;
558     unsigned CallArgIndex;
559   };
560 }
561 
562 /// \brief Convert from Sema's representation of template deduction information
563 /// to the form used in overload-candidate information.
564 DeductionFailureInfo
565 clang::MakeDeductionFailureInfo(ASTContext &Context,
566                                 Sema::TemplateDeductionResult TDK,
567                                 TemplateDeductionInfo &Info) {
568   DeductionFailureInfo Result;
569   Result.Result = static_cast<unsigned>(TDK);
570   Result.HasDiagnostic = false;
571   switch (TDK) {
572   case Sema::TDK_Success:
573   case Sema::TDK_Invalid:
574   case Sema::TDK_InstantiationDepth:
575   case Sema::TDK_TooManyArguments:
576   case Sema::TDK_TooFewArguments:
577   case Sema::TDK_MiscellaneousDeductionFailure:
578     Result.Data = nullptr;
579     break;
580 
581   case Sema::TDK_Incomplete:
582   case Sema::TDK_InvalidExplicitArguments:
583     Result.Data = Info.Param.getOpaqueValue();
584     break;
585 
586   case Sema::TDK_DeducedMismatch: {
587     // FIXME: Should allocate from normal heap so that we can free this later.
588     auto *Saved = new (Context) DFIDeducedMismatchArgs;
589     Saved->FirstArg = Info.FirstArg;
590     Saved->SecondArg = Info.SecondArg;
591     Saved->TemplateArgs = Info.take();
592     Saved->CallArgIndex = Info.CallArgIndex;
593     Result.Data = Saved;
594     break;
595   }
596 
597   case Sema::TDK_NonDeducedMismatch: {
598     // FIXME: Should allocate from normal heap so that we can free this later.
599     DFIArguments *Saved = new (Context) DFIArguments;
600     Saved->FirstArg = Info.FirstArg;
601     Saved->SecondArg = Info.SecondArg;
602     Result.Data = Saved;
603     break;
604   }
605 
606   case Sema::TDK_Inconsistent:
607   case Sema::TDK_Underqualified: {
608     // FIXME: Should allocate from normal heap so that we can free this later.
609     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
610     Saved->Param = Info.Param;
611     Saved->FirstArg = Info.FirstArg;
612     Saved->SecondArg = Info.SecondArg;
613     Result.Data = Saved;
614     break;
615   }
616 
617   case Sema::TDK_SubstitutionFailure:
618     Result.Data = Info.take();
619     if (Info.hasSFINAEDiagnostic()) {
620       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
621           SourceLocation(), PartialDiagnostic::NullDiagnostic());
622       Info.takeSFINAEDiagnostic(*Diag);
623       Result.HasDiagnostic = true;
624     }
625     break;
626 
627   case Sema::TDK_FailedOverloadResolution:
628     Result.Data = Info.Expression;
629     break;
630   }
631 
632   return Result;
633 }
634 
635 void DeductionFailureInfo::Destroy() {
636   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
637   case Sema::TDK_Success:
638   case Sema::TDK_Invalid:
639   case Sema::TDK_InstantiationDepth:
640   case Sema::TDK_Incomplete:
641   case Sema::TDK_TooManyArguments:
642   case Sema::TDK_TooFewArguments:
643   case Sema::TDK_InvalidExplicitArguments:
644   case Sema::TDK_FailedOverloadResolution:
645     break;
646 
647   case Sema::TDK_Inconsistent:
648   case Sema::TDK_Underqualified:
649   case Sema::TDK_DeducedMismatch:
650   case Sema::TDK_NonDeducedMismatch:
651     // FIXME: Destroy the data?
652     Data = nullptr;
653     break;
654 
655   case Sema::TDK_SubstitutionFailure:
656     // FIXME: Destroy the template argument list?
657     Data = nullptr;
658     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
659       Diag->~PartialDiagnosticAt();
660       HasDiagnostic = false;
661     }
662     break;
663 
664   // Unhandled
665   case Sema::TDK_MiscellaneousDeductionFailure:
666     break;
667   }
668 }
669 
670 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
671   if (HasDiagnostic)
672     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
673   return nullptr;
674 }
675 
676 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
677   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
678   case Sema::TDK_Success:
679   case Sema::TDK_Invalid:
680   case Sema::TDK_InstantiationDepth:
681   case Sema::TDK_TooManyArguments:
682   case Sema::TDK_TooFewArguments:
683   case Sema::TDK_SubstitutionFailure:
684   case Sema::TDK_DeducedMismatch:
685   case Sema::TDK_NonDeducedMismatch:
686   case Sema::TDK_FailedOverloadResolution:
687     return TemplateParameter();
688 
689   case Sema::TDK_Incomplete:
690   case Sema::TDK_InvalidExplicitArguments:
691     return TemplateParameter::getFromOpaqueValue(Data);
692 
693   case Sema::TDK_Inconsistent:
694   case Sema::TDK_Underqualified:
695     return static_cast<DFIParamWithArguments*>(Data)->Param;
696 
697   // Unhandled
698   case Sema::TDK_MiscellaneousDeductionFailure:
699     break;
700   }
701 
702   return TemplateParameter();
703 }
704 
705 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
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_TooManyArguments:
711   case Sema::TDK_TooFewArguments:
712   case Sema::TDK_Incomplete:
713   case Sema::TDK_InvalidExplicitArguments:
714   case Sema::TDK_Inconsistent:
715   case Sema::TDK_Underqualified:
716   case Sema::TDK_NonDeducedMismatch:
717   case Sema::TDK_FailedOverloadResolution:
718     return nullptr;
719 
720   case Sema::TDK_DeducedMismatch:
721     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
722 
723   case Sema::TDK_SubstitutionFailure:
724     return static_cast<TemplateArgumentList*>(Data);
725 
726   // Unhandled
727   case Sema::TDK_MiscellaneousDeductionFailure:
728     break;
729   }
730 
731   return nullptr;
732 }
733 
734 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
735   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
736   case Sema::TDK_Success:
737   case Sema::TDK_Invalid:
738   case Sema::TDK_InstantiationDepth:
739   case Sema::TDK_Incomplete:
740   case Sema::TDK_TooManyArguments:
741   case Sema::TDK_TooFewArguments:
742   case Sema::TDK_InvalidExplicitArguments:
743   case Sema::TDK_SubstitutionFailure:
744   case Sema::TDK_FailedOverloadResolution:
745     return nullptr;
746 
747   case Sema::TDK_Inconsistent:
748   case Sema::TDK_Underqualified:
749   case Sema::TDK_DeducedMismatch:
750   case Sema::TDK_NonDeducedMismatch:
751     return &static_cast<DFIArguments*>(Data)->FirstArg;
752 
753   // Unhandled
754   case Sema::TDK_MiscellaneousDeductionFailure:
755     break;
756   }
757 
758   return nullptr;
759 }
760 
761 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
762   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
763   case Sema::TDK_Success:
764   case Sema::TDK_Invalid:
765   case Sema::TDK_InstantiationDepth:
766   case Sema::TDK_Incomplete:
767   case Sema::TDK_TooManyArguments:
768   case Sema::TDK_TooFewArguments:
769   case Sema::TDK_InvalidExplicitArguments:
770   case Sema::TDK_SubstitutionFailure:
771   case Sema::TDK_FailedOverloadResolution:
772     return nullptr;
773 
774   case Sema::TDK_Inconsistent:
775   case Sema::TDK_Underqualified:
776   case Sema::TDK_DeducedMismatch:
777   case Sema::TDK_NonDeducedMismatch:
778     return &static_cast<DFIArguments*>(Data)->SecondArg;
779 
780   // Unhandled
781   case Sema::TDK_MiscellaneousDeductionFailure:
782     break;
783   }
784 
785   return nullptr;
786 }
787 
788 Expr *DeductionFailureInfo::getExpr() {
789   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
790         Sema::TDK_FailedOverloadResolution)
791     return static_cast<Expr*>(Data);
792 
793   return nullptr;
794 }
795 
796 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
797   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
798         Sema::TDK_DeducedMismatch)
799     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
800 
801   return llvm::None;
802 }
803 
804 void OverloadCandidateSet::destroyCandidates() {
805   for (iterator i = begin(), e = end(); i != e; ++i) {
806     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
807       i->Conversions[ii].~ImplicitConversionSequence();
808     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
809       i->DeductionFailure.Destroy();
810   }
811 }
812 
813 void OverloadCandidateSet::clear() {
814   destroyCandidates();
815   NumInlineSequences = 0;
816   Candidates.clear();
817   Functions.clear();
818 }
819 
820 namespace {
821   class UnbridgedCastsSet {
822     struct Entry {
823       Expr **Addr;
824       Expr *Saved;
825     };
826     SmallVector<Entry, 2> Entries;
827 
828   public:
829     void save(Sema &S, Expr *&E) {
830       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
831       Entry entry = { &E, E };
832       Entries.push_back(entry);
833       E = S.stripARCUnbridgedCast(E);
834     }
835 
836     void restore() {
837       for (SmallVectorImpl<Entry>::iterator
838              i = Entries.begin(), e = Entries.end(); i != e; ++i)
839         *i->Addr = i->Saved;
840     }
841   };
842 }
843 
844 /// checkPlaceholderForOverload - Do any interesting placeholder-like
845 /// preprocessing on the given expression.
846 ///
847 /// \param unbridgedCasts a collection to which to add unbridged casts;
848 ///   without this, they will be immediately diagnosed as errors
849 ///
850 /// Return true on unrecoverable error.
851 static bool
852 checkPlaceholderForOverload(Sema &S, Expr *&E,
853                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
854   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
855     // We can't handle overloaded expressions here because overload
856     // resolution might reasonably tweak them.
857     if (placeholder->getKind() == BuiltinType::Overload) return false;
858 
859     // If the context potentially accepts unbridged ARC casts, strip
860     // the unbridged cast and add it to the collection for later restoration.
861     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
862         unbridgedCasts) {
863       unbridgedCasts->save(S, E);
864       return false;
865     }
866 
867     // Go ahead and check everything else.
868     ExprResult result = S.CheckPlaceholderExpr(E);
869     if (result.isInvalid())
870       return true;
871 
872     E = result.get();
873     return false;
874   }
875 
876   // Nothing to do.
877   return false;
878 }
879 
880 /// checkArgPlaceholdersForOverload - Check a set of call operands for
881 /// placeholders.
882 static bool checkArgPlaceholdersForOverload(Sema &S,
883                                             MultiExprArg Args,
884                                             UnbridgedCastsSet &unbridged) {
885   for (unsigned i = 0, e = Args.size(); i != e; ++i)
886     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
887       return true;
888 
889   return false;
890 }
891 
892 // IsOverload - Determine whether the given New declaration is an
893 // overload of the declarations in Old. This routine returns false if
894 // New and Old cannot be overloaded, e.g., if New has the same
895 // signature as some function in Old (C++ 1.3.10) or if the Old
896 // declarations aren't functions (or function templates) at all. When
897 // it does return false, MatchedDecl will point to the decl that New
898 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
899 // top of the underlying declaration.
900 //
901 // Example: Given the following input:
902 //
903 //   void f(int, float); // #1
904 //   void f(int, int); // #2
905 //   int f(int, int); // #3
906 //
907 // When we process #1, there is no previous declaration of "f",
908 // so IsOverload will not be used.
909 //
910 // When we process #2, Old contains only the FunctionDecl for #1.  By
911 // comparing the parameter types, we see that #1 and #2 are overloaded
912 // (since they have different signatures), so this routine returns
913 // false; MatchedDecl is unchanged.
914 //
915 // When we process #3, Old is an overload set containing #1 and #2. We
916 // compare the signatures of #3 to #1 (they're overloaded, so we do
917 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
918 // identical (return types of functions are not part of the
919 // signature), IsOverload returns false and MatchedDecl will be set to
920 // point to the FunctionDecl for #2.
921 //
922 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
923 // into a class by a using declaration.  The rules for whether to hide
924 // shadow declarations ignore some properties which otherwise figure
925 // into a function template's signature.
926 Sema::OverloadKind
927 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
928                     NamedDecl *&Match, bool NewIsUsingDecl) {
929   for (LookupResult::iterator I = Old.begin(), E = Old.end();
930          I != E; ++I) {
931     NamedDecl *OldD = *I;
932 
933     bool OldIsUsingDecl = false;
934     if (isa<UsingShadowDecl>(OldD)) {
935       OldIsUsingDecl = true;
936 
937       // We can always introduce two using declarations into the same
938       // context, even if they have identical signatures.
939       if (NewIsUsingDecl) continue;
940 
941       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
942     }
943 
944     // A using-declaration does not conflict with another declaration
945     // if one of them is hidden.
946     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
947       continue;
948 
949     // If either declaration was introduced by a using declaration,
950     // we'll need to use slightly different rules for matching.
951     // Essentially, these rules are the normal rules, except that
952     // function templates hide function templates with different
953     // return types or template parameter lists.
954     bool UseMemberUsingDeclRules =
955       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
956       !New->getFriendObjectKind();
957 
958     if (FunctionDecl *OldF = OldD->getAsFunction()) {
959       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
960         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
961           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
962           continue;
963         }
964 
965         if (!isa<FunctionTemplateDecl>(OldD) &&
966             !shouldLinkPossiblyHiddenDecl(*I, New))
967           continue;
968 
969         Match = *I;
970         return Ovl_Match;
971       }
972     } else if (isa<UsingDecl>(OldD)) {
973       // We can overload with these, which can show up when doing
974       // redeclaration checks for UsingDecls.
975       assert(Old.getLookupKind() == LookupUsingDeclName);
976     } else if (isa<TagDecl>(OldD)) {
977       // We can always overload with tags by hiding them.
978     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
979       // Optimistically assume that an unresolved using decl will
980       // overload; if it doesn't, we'll have to diagnose during
981       // template instantiation.
982     } else {
983       // (C++ 13p1):
984       //   Only function declarations can be overloaded; object and type
985       //   declarations cannot be overloaded.
986       Match = *I;
987       return Ovl_NonFunction;
988     }
989   }
990 
991   return Ovl_Overload;
992 }
993 
994 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
995                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
996   // C++ [basic.start.main]p2: This function shall not be overloaded.
997   if (New->isMain())
998     return false;
999 
1000   // MSVCRT user defined entry points cannot be overloaded.
1001   if (New->isMSVCRTEntryPoint())
1002     return false;
1003 
1004   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1005   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1006 
1007   // C++ [temp.fct]p2:
1008   //   A function template can be overloaded with other function templates
1009   //   and with normal (non-template) functions.
1010   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1011     return true;
1012 
1013   // Is the function New an overload of the function Old?
1014   QualType OldQType = Context.getCanonicalType(Old->getType());
1015   QualType NewQType = Context.getCanonicalType(New->getType());
1016 
1017   // Compare the signatures (C++ 1.3.10) of the two functions to
1018   // determine whether they are overloads. If we find any mismatch
1019   // in the signature, they are overloads.
1020 
1021   // If either of these functions is a K&R-style function (no
1022   // prototype), then we consider them to have matching signatures.
1023   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1024       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1025     return false;
1026 
1027   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1028   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1029 
1030   // The signature of a function includes the types of its
1031   // parameters (C++ 1.3.10), which includes the presence or absence
1032   // of the ellipsis; see C++ DR 357).
1033   if (OldQType != NewQType &&
1034       (OldType->getNumParams() != NewType->getNumParams() ||
1035        OldType->isVariadic() != NewType->isVariadic() ||
1036        !FunctionParamTypesAreEqual(OldType, NewType)))
1037     return true;
1038 
1039   // C++ [temp.over.link]p4:
1040   //   The signature of a function template consists of its function
1041   //   signature, its return type and its template parameter list. The names
1042   //   of the template parameters are significant only for establishing the
1043   //   relationship between the template parameters and the rest of the
1044   //   signature.
1045   //
1046   // We check the return type and template parameter lists for function
1047   // templates first; the remaining checks follow.
1048   //
1049   // However, we don't consider either of these when deciding whether
1050   // a member introduced by a shadow declaration is hidden.
1051   if (!UseMemberUsingDeclRules && NewTemplate &&
1052       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1053                                        OldTemplate->getTemplateParameters(),
1054                                        false, TPL_TemplateMatch) ||
1055        OldType->getReturnType() != NewType->getReturnType()))
1056     return true;
1057 
1058   // If the function is a class member, its signature includes the
1059   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1060   //
1061   // As part of this, also check whether one of the member functions
1062   // is static, in which case they are not overloads (C++
1063   // 13.1p2). While not part of the definition of the signature,
1064   // this check is important to determine whether these functions
1065   // can be overloaded.
1066   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1067   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1068   if (OldMethod && NewMethod &&
1069       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1070     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1071       if (!UseMemberUsingDeclRules &&
1072           (OldMethod->getRefQualifier() == RQ_None ||
1073            NewMethod->getRefQualifier() == RQ_None)) {
1074         // C++0x [over.load]p2:
1075         //   - Member function declarations with the same name and the same
1076         //     parameter-type-list as well as member function template
1077         //     declarations with the same name, the same parameter-type-list, and
1078         //     the same template parameter lists cannot be overloaded if any of
1079         //     them, but not all, have a ref-qualifier (8.3.5).
1080         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1081           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1082         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1083       }
1084       return true;
1085     }
1086 
1087     // We may not have applied the implicit const for a constexpr member
1088     // function yet (because we haven't yet resolved whether this is a static
1089     // or non-static member function). Add it now, on the assumption that this
1090     // is a redeclaration of OldMethod.
1091     unsigned OldQuals = OldMethod->getTypeQualifiers();
1092     unsigned NewQuals = NewMethod->getTypeQualifiers();
1093     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1094         !isa<CXXConstructorDecl>(NewMethod))
1095       NewQuals |= Qualifiers::Const;
1096 
1097     // We do not allow overloading based off of '__restrict'.
1098     OldQuals &= ~Qualifiers::Restrict;
1099     NewQuals &= ~Qualifiers::Restrict;
1100     if (OldQuals != NewQuals)
1101       return true;
1102   }
1103 
1104   // Though pass_object_size is placed on parameters and takes an argument, we
1105   // consider it to be a function-level modifier for the sake of function
1106   // identity. Either the function has one or more parameters with
1107   // pass_object_size or it doesn't.
1108   if (functionHasPassObjectSizeParams(New) !=
1109       functionHasPassObjectSizeParams(Old))
1110     return true;
1111 
1112   // enable_if attributes are an order-sensitive part of the signature.
1113   for (specific_attr_iterator<EnableIfAttr>
1114          NewI = New->specific_attr_begin<EnableIfAttr>(),
1115          NewE = New->specific_attr_end<EnableIfAttr>(),
1116          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1117          OldE = Old->specific_attr_end<EnableIfAttr>();
1118        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1119     if (NewI == NewE || OldI == OldE)
1120       return true;
1121     llvm::FoldingSetNodeID NewID, OldID;
1122     NewI->getCond()->Profile(NewID, Context, true);
1123     OldI->getCond()->Profile(OldID, Context, true);
1124     if (NewID != OldID)
1125       return true;
1126   }
1127 
1128   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1129     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1130                        OldTarget = IdentifyCUDATarget(Old);
1131     if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1132       return false;
1133 
1134     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1135 
1136     // Don't allow mixing of HD with other kinds. This guarantees that
1137     // we have only one viable function with this signature on any
1138     // side of CUDA compilation .
1139     // __global__ functions can't be overloaded based on attribute
1140     // difference because, like HD, they also exist on both sides.
1141     if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1142         (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
1143       return false;
1144 
1145     // Allow overloading of functions with same signature, but
1146     // different CUDA target attributes.
1147     return NewTarget != OldTarget;
1148   }
1149 
1150   // The signatures match; this is not an overload.
1151   return false;
1152 }
1153 
1154 /// \brief Checks availability of the function depending on the current
1155 /// function context. Inside an unavailable function, unavailability is ignored.
1156 ///
1157 /// \returns true if \arg FD is unavailable and current context is inside
1158 /// an available function, false otherwise.
1159 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1160   if (!FD->isUnavailable())
1161     return false;
1162 
1163   // Walk up the context of the caller.
1164   Decl *C = cast<Decl>(CurContext);
1165   do {
1166     if (C->isUnavailable())
1167       return false;
1168   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1169   return true;
1170 }
1171 
1172 /// \brief Tries a user-defined conversion from From to ToType.
1173 ///
1174 /// Produces an implicit conversion sequence for when a standard conversion
1175 /// is not an option. See TryImplicitConversion for more information.
1176 static ImplicitConversionSequence
1177 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1178                          bool SuppressUserConversions,
1179                          bool AllowExplicit,
1180                          bool InOverloadResolution,
1181                          bool CStyle,
1182                          bool AllowObjCWritebackConversion,
1183                          bool AllowObjCConversionOnExplicit) {
1184   ImplicitConversionSequence ICS;
1185 
1186   if (SuppressUserConversions) {
1187     // We're not in the case above, so there is no conversion that
1188     // we can perform.
1189     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1190     return ICS;
1191   }
1192 
1193   // Attempt user-defined conversion.
1194   OverloadCandidateSet Conversions(From->getExprLoc(),
1195                                    OverloadCandidateSet::CSK_Normal);
1196   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1197                                   Conversions, AllowExplicit,
1198                                   AllowObjCConversionOnExplicit)) {
1199   case OR_Success:
1200   case OR_Deleted:
1201     ICS.setUserDefined();
1202     // C++ [over.ics.user]p4:
1203     //   A conversion of an expression of class type to the same class
1204     //   type is given Exact Match rank, and a conversion of an
1205     //   expression of class type to a base class of that type is
1206     //   given Conversion rank, in spite of the fact that a copy
1207     //   constructor (i.e., a user-defined conversion function) is
1208     //   called for those cases.
1209     if (CXXConstructorDecl *Constructor
1210           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1211       QualType FromCanon
1212         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1213       QualType ToCanon
1214         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1215       if (Constructor->isCopyConstructor() &&
1216           (FromCanon == ToCanon ||
1217            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1218         // Turn this into a "standard" conversion sequence, so that it
1219         // gets ranked with standard conversion sequences.
1220         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1221         ICS.setStandard();
1222         ICS.Standard.setAsIdentityConversion();
1223         ICS.Standard.setFromType(From->getType());
1224         ICS.Standard.setAllToTypes(ToType);
1225         ICS.Standard.CopyConstructor = Constructor;
1226         ICS.Standard.FoundCopyConstructor = Found;
1227         if (ToCanon != FromCanon)
1228           ICS.Standard.Second = ICK_Derived_To_Base;
1229       }
1230     }
1231     break;
1232 
1233   case OR_Ambiguous:
1234     ICS.setAmbiguous();
1235     ICS.Ambiguous.setFromType(From->getType());
1236     ICS.Ambiguous.setToType(ToType);
1237     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1238          Cand != Conversions.end(); ++Cand)
1239       if (Cand->Viable)
1240         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1241     break;
1242 
1243     // Fall through.
1244   case OR_No_Viable_Function:
1245     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1246     break;
1247   }
1248 
1249   return ICS;
1250 }
1251 
1252 /// TryImplicitConversion - Attempt to perform an implicit conversion
1253 /// from the given expression (Expr) to the given type (ToType). This
1254 /// function returns an implicit conversion sequence that can be used
1255 /// to perform the initialization. Given
1256 ///
1257 ///   void f(float f);
1258 ///   void g(int i) { f(i); }
1259 ///
1260 /// this routine would produce an implicit conversion sequence to
1261 /// describe the initialization of f from i, which will be a standard
1262 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1263 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1264 //
1265 /// Note that this routine only determines how the conversion can be
1266 /// performed; it does not actually perform the conversion. As such,
1267 /// it will not produce any diagnostics if no conversion is available,
1268 /// but will instead return an implicit conversion sequence of kind
1269 /// "BadConversion".
1270 ///
1271 /// If @p SuppressUserConversions, then user-defined conversions are
1272 /// not permitted.
1273 /// If @p AllowExplicit, then explicit user-defined conversions are
1274 /// permitted.
1275 ///
1276 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1277 /// writeback conversion, which allows __autoreleasing id* parameters to
1278 /// be initialized with __strong id* or __weak id* arguments.
1279 static ImplicitConversionSequence
1280 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1281                       bool SuppressUserConversions,
1282                       bool AllowExplicit,
1283                       bool InOverloadResolution,
1284                       bool CStyle,
1285                       bool AllowObjCWritebackConversion,
1286                       bool AllowObjCConversionOnExplicit) {
1287   ImplicitConversionSequence ICS;
1288   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1289                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1290     ICS.setStandard();
1291     return ICS;
1292   }
1293 
1294   if (!S.getLangOpts().CPlusPlus) {
1295     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1296     return ICS;
1297   }
1298 
1299   // C++ [over.ics.user]p4:
1300   //   A conversion of an expression of class type to the same class
1301   //   type is given Exact Match rank, and a conversion of an
1302   //   expression of class type to a base class of that type is
1303   //   given Conversion rank, in spite of the fact that a copy/move
1304   //   constructor (i.e., a user-defined conversion function) is
1305   //   called for those cases.
1306   QualType FromType = From->getType();
1307   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1308       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1309        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1310     ICS.setStandard();
1311     ICS.Standard.setAsIdentityConversion();
1312     ICS.Standard.setFromType(FromType);
1313     ICS.Standard.setAllToTypes(ToType);
1314 
1315     // We don't actually check at this point whether there is a valid
1316     // copy/move constructor, since overloading just assumes that it
1317     // exists. When we actually perform initialization, we'll find the
1318     // appropriate constructor to copy the returned object, if needed.
1319     ICS.Standard.CopyConstructor = nullptr;
1320 
1321     // Determine whether this is considered a derived-to-base conversion.
1322     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1323       ICS.Standard.Second = ICK_Derived_To_Base;
1324 
1325     return ICS;
1326   }
1327 
1328   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1329                                   AllowExplicit, InOverloadResolution, CStyle,
1330                                   AllowObjCWritebackConversion,
1331                                   AllowObjCConversionOnExplicit);
1332 }
1333 
1334 ImplicitConversionSequence
1335 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1336                             bool SuppressUserConversions,
1337                             bool AllowExplicit,
1338                             bool InOverloadResolution,
1339                             bool CStyle,
1340                             bool AllowObjCWritebackConversion) {
1341   return ::TryImplicitConversion(*this, From, ToType,
1342                                  SuppressUserConversions, AllowExplicit,
1343                                  InOverloadResolution, CStyle,
1344                                  AllowObjCWritebackConversion,
1345                                  /*AllowObjCConversionOnExplicit=*/false);
1346 }
1347 
1348 /// PerformImplicitConversion - Perform an implicit conversion of the
1349 /// expression From to the type ToType. Returns the
1350 /// converted expression. Flavor is the kind of conversion we're
1351 /// performing, used in the error message. If @p AllowExplicit,
1352 /// explicit user-defined conversions are permitted.
1353 ExprResult
1354 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1355                                 AssignmentAction Action, bool AllowExplicit) {
1356   ImplicitConversionSequence ICS;
1357   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1358 }
1359 
1360 ExprResult
1361 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1362                                 AssignmentAction Action, bool AllowExplicit,
1363                                 ImplicitConversionSequence& ICS) {
1364   if (checkPlaceholderForOverload(*this, From))
1365     return ExprError();
1366 
1367   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1368   bool AllowObjCWritebackConversion
1369     = getLangOpts().ObjCAutoRefCount &&
1370       (Action == AA_Passing || Action == AA_Sending);
1371   if (getLangOpts().ObjC1)
1372     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1373                                       ToType, From->getType(), From);
1374   ICS = ::TryImplicitConversion(*this, From, ToType,
1375                                 /*SuppressUserConversions=*/false,
1376                                 AllowExplicit,
1377                                 /*InOverloadResolution=*/false,
1378                                 /*CStyle=*/false,
1379                                 AllowObjCWritebackConversion,
1380                                 /*AllowObjCConversionOnExplicit=*/false);
1381   return PerformImplicitConversion(From, ToType, ICS, Action);
1382 }
1383 
1384 /// \brief Determine whether the conversion from FromType to ToType is a valid
1385 /// conversion that strips "noreturn" off the nested function type.
1386 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1387                                 QualType &ResultTy) {
1388   if (Context.hasSameUnqualifiedType(FromType, ToType))
1389     return false;
1390 
1391   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1392   // where F adds one of the following at most once:
1393   //   - a pointer
1394   //   - a member pointer
1395   //   - a block pointer
1396   CanQualType CanTo = Context.getCanonicalType(ToType);
1397   CanQualType CanFrom = Context.getCanonicalType(FromType);
1398   Type::TypeClass TyClass = CanTo->getTypeClass();
1399   if (TyClass != CanFrom->getTypeClass()) return false;
1400   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1401     if (TyClass == Type::Pointer) {
1402       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1403       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1404     } else if (TyClass == Type::BlockPointer) {
1405       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1406       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1407     } else if (TyClass == Type::MemberPointer) {
1408       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1409       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1410     } else {
1411       return false;
1412     }
1413 
1414     TyClass = CanTo->getTypeClass();
1415     if (TyClass != CanFrom->getTypeClass()) return false;
1416     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1417       return false;
1418   }
1419 
1420   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1421   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1422   if (!EInfo.getNoReturn()) return false;
1423 
1424   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1425   assert(QualType(FromFn, 0).isCanonical());
1426   if (QualType(FromFn, 0) != CanTo) return false;
1427 
1428   ResultTy = ToType;
1429   return true;
1430 }
1431 
1432 /// \brief Determine whether the conversion from FromType to ToType is a valid
1433 /// vector conversion.
1434 ///
1435 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1436 /// conversion.
1437 static bool IsVectorConversion(Sema &S, QualType FromType,
1438                                QualType ToType, ImplicitConversionKind &ICK) {
1439   // We need at least one of these types to be a vector type to have a vector
1440   // conversion.
1441   if (!ToType->isVectorType() && !FromType->isVectorType())
1442     return false;
1443 
1444   // Identical types require no conversions.
1445   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1446     return false;
1447 
1448   // There are no conversions between extended vector types, only identity.
1449   if (ToType->isExtVectorType()) {
1450     // There are no conversions between extended vector types other than the
1451     // identity conversion.
1452     if (FromType->isExtVectorType())
1453       return false;
1454 
1455     // Vector splat from any arithmetic type to a vector.
1456     if (FromType->isArithmeticType()) {
1457       ICK = ICK_Vector_Splat;
1458       return true;
1459     }
1460   }
1461 
1462   // We can perform the conversion between vector types in the following cases:
1463   // 1)vector types are equivalent AltiVec and GCC vector types
1464   // 2)lax vector conversions are permitted and the vector types are of the
1465   //   same size
1466   if (ToType->isVectorType() && FromType->isVectorType()) {
1467     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1468         S.isLaxVectorConversion(FromType, ToType)) {
1469       ICK = ICK_Vector_Conversion;
1470       return true;
1471     }
1472   }
1473 
1474   return false;
1475 }
1476 
1477 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1478                                 bool InOverloadResolution,
1479                                 StandardConversionSequence &SCS,
1480                                 bool CStyle);
1481 
1482 /// IsStandardConversion - Determines whether there is a standard
1483 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1484 /// expression From to the type ToType. Standard conversion sequences
1485 /// only consider non-class types; for conversions that involve class
1486 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1487 /// contain the standard conversion sequence required to perform this
1488 /// conversion and this routine will return true. Otherwise, this
1489 /// routine will return false and the value of SCS is unspecified.
1490 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1491                                  bool InOverloadResolution,
1492                                  StandardConversionSequence &SCS,
1493                                  bool CStyle,
1494                                  bool AllowObjCWritebackConversion) {
1495   QualType FromType = From->getType();
1496 
1497   // Standard conversions (C++ [conv])
1498   SCS.setAsIdentityConversion();
1499   SCS.IncompatibleObjC = false;
1500   SCS.setFromType(FromType);
1501   SCS.CopyConstructor = nullptr;
1502 
1503   // There are no standard conversions for class types in C++, so
1504   // abort early. When overloading in C, however, we do permit them.
1505   if (S.getLangOpts().CPlusPlus &&
1506       (FromType->isRecordType() || ToType->isRecordType()))
1507     return false;
1508 
1509   // The first conversion can be an lvalue-to-rvalue conversion,
1510   // array-to-pointer conversion, or function-to-pointer conversion
1511   // (C++ 4p1).
1512 
1513   if (FromType == S.Context.OverloadTy) {
1514     DeclAccessPair AccessPair;
1515     if (FunctionDecl *Fn
1516           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1517                                                  AccessPair)) {
1518       // We were able to resolve the address of the overloaded function,
1519       // so we can convert to the type of that function.
1520       FromType = Fn->getType();
1521       SCS.setFromType(FromType);
1522 
1523       // we can sometimes resolve &foo<int> regardless of ToType, so check
1524       // if the type matches (identity) or we are converting to bool
1525       if (!S.Context.hasSameUnqualifiedType(
1526                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1527         QualType resultTy;
1528         // if the function type matches except for [[noreturn]], it's ok
1529         if (!S.IsNoReturnConversion(FromType,
1530               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1531           // otherwise, only a boolean conversion is standard
1532           if (!ToType->isBooleanType())
1533             return false;
1534       }
1535 
1536       // Check if the "from" expression is taking the address of an overloaded
1537       // function and recompute the FromType accordingly. Take advantage of the
1538       // fact that non-static member functions *must* have such an address-of
1539       // expression.
1540       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1541       if (Method && !Method->isStatic()) {
1542         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1543                "Non-unary operator on non-static member address");
1544         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1545                == UO_AddrOf &&
1546                "Non-address-of operator on non-static member address");
1547         const Type *ClassType
1548           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1549         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1550       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1551         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1552                UO_AddrOf &&
1553                "Non-address-of operator for overloaded function expression");
1554         FromType = S.Context.getPointerType(FromType);
1555       }
1556 
1557       // Check that we've computed the proper type after overload resolution.
1558       assert(S.Context.hasSameType(
1559         FromType,
1560         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1561     } else {
1562       return false;
1563     }
1564   }
1565   // Lvalue-to-rvalue conversion (C++11 4.1):
1566   //   A glvalue (3.10) of a non-function, non-array type T can
1567   //   be converted to a prvalue.
1568   bool argIsLValue = From->isGLValue();
1569   if (argIsLValue &&
1570       !FromType->isFunctionType() && !FromType->isArrayType() &&
1571       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1572     SCS.First = ICK_Lvalue_To_Rvalue;
1573 
1574     // C11 6.3.2.1p2:
1575     //   ... if the lvalue has atomic type, the value has the non-atomic version
1576     //   of the type of the lvalue ...
1577     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1578       FromType = Atomic->getValueType();
1579 
1580     // If T is a non-class type, the type of the rvalue is the
1581     // cv-unqualified version of T. Otherwise, the type of the rvalue
1582     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1583     // just strip the qualifiers because they don't matter.
1584     FromType = FromType.getUnqualifiedType();
1585   } else if (FromType->isArrayType()) {
1586     // Array-to-pointer conversion (C++ 4.2)
1587     SCS.First = ICK_Array_To_Pointer;
1588 
1589     // An lvalue or rvalue of type "array of N T" or "array of unknown
1590     // bound of T" can be converted to an rvalue of type "pointer to
1591     // T" (C++ 4.2p1).
1592     FromType = S.Context.getArrayDecayedType(FromType);
1593 
1594     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1595       // This conversion is deprecated in C++03 (D.4)
1596       SCS.DeprecatedStringLiteralToCharPtr = true;
1597 
1598       // For the purpose of ranking in overload resolution
1599       // (13.3.3.1.1), this conversion is considered an
1600       // array-to-pointer conversion followed by a qualification
1601       // conversion (4.4). (C++ 4.2p2)
1602       SCS.Second = ICK_Identity;
1603       SCS.Third = ICK_Qualification;
1604       SCS.QualificationIncludesObjCLifetime = false;
1605       SCS.setAllToTypes(FromType);
1606       return true;
1607     }
1608   } else if (FromType->isFunctionType() && argIsLValue) {
1609     // Function-to-pointer conversion (C++ 4.3).
1610     SCS.First = ICK_Function_To_Pointer;
1611 
1612     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1613       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1614         if (!S.checkAddressOfFunctionIsAvailable(FD))
1615           return false;
1616 
1617     // An lvalue of function type T can be converted to an rvalue of
1618     // type "pointer to T." The result is a pointer to the
1619     // function. (C++ 4.3p1).
1620     FromType = S.Context.getPointerType(FromType);
1621   } else {
1622     // We don't require any conversions for the first step.
1623     SCS.First = ICK_Identity;
1624   }
1625   SCS.setToType(0, FromType);
1626 
1627   // The second conversion can be an integral promotion, floating
1628   // point promotion, integral conversion, floating point conversion,
1629   // floating-integral conversion, pointer conversion,
1630   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1631   // For overloading in C, this can also be a "compatible-type"
1632   // conversion.
1633   bool IncompatibleObjC = false;
1634   ImplicitConversionKind SecondICK = ICK_Identity;
1635   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1636     // The unqualified versions of the types are the same: there's no
1637     // conversion to do.
1638     SCS.Second = ICK_Identity;
1639   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1640     // Integral promotion (C++ 4.5).
1641     SCS.Second = ICK_Integral_Promotion;
1642     FromType = ToType.getUnqualifiedType();
1643   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1644     // Floating point promotion (C++ 4.6).
1645     SCS.Second = ICK_Floating_Promotion;
1646     FromType = ToType.getUnqualifiedType();
1647   } else if (S.IsComplexPromotion(FromType, ToType)) {
1648     // Complex promotion (Clang extension)
1649     SCS.Second = ICK_Complex_Promotion;
1650     FromType = ToType.getUnqualifiedType();
1651   } else if (ToType->isBooleanType() &&
1652              (FromType->isArithmeticType() ||
1653               FromType->isAnyPointerType() ||
1654               FromType->isBlockPointerType() ||
1655               FromType->isMemberPointerType() ||
1656               FromType->isNullPtrType())) {
1657     // Boolean conversions (C++ 4.12).
1658     SCS.Second = ICK_Boolean_Conversion;
1659     FromType = S.Context.BoolTy;
1660   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1661              ToType->isIntegralType(S.Context)) {
1662     // Integral conversions (C++ 4.7).
1663     SCS.Second = ICK_Integral_Conversion;
1664     FromType = ToType.getUnqualifiedType();
1665   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1666     // Complex conversions (C99 6.3.1.6)
1667     SCS.Second = ICK_Complex_Conversion;
1668     FromType = ToType.getUnqualifiedType();
1669   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1670              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1671     // Complex-real conversions (C99 6.3.1.7)
1672     SCS.Second = ICK_Complex_Real;
1673     FromType = ToType.getUnqualifiedType();
1674   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1675     // FIXME: disable conversions between long double and __float128 if
1676     // their representation is different until there is back end support
1677     // We of course allow this conversion if long double is really double.
1678     if (&S.Context.getFloatTypeSemantics(FromType) !=
1679         &S.Context.getFloatTypeSemantics(ToType)) {
1680       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1681                                     ToType == S.Context.LongDoubleTy) ||
1682                                    (FromType == S.Context.LongDoubleTy &&
1683                                     ToType == S.Context.Float128Ty));
1684       if (Float128AndLongDouble &&
1685           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1686            &llvm::APFloat::IEEEdouble))
1687         return false;
1688     }
1689     // Floating point conversions (C++ 4.8).
1690     SCS.Second = ICK_Floating_Conversion;
1691     FromType = ToType.getUnqualifiedType();
1692   } else if ((FromType->isRealFloatingType() &&
1693               ToType->isIntegralType(S.Context)) ||
1694              (FromType->isIntegralOrUnscopedEnumerationType() &&
1695               ToType->isRealFloatingType())) {
1696     // Floating-integral conversions (C++ 4.9).
1697     SCS.Second = ICK_Floating_Integral;
1698     FromType = ToType.getUnqualifiedType();
1699   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1700     SCS.Second = ICK_Block_Pointer_Conversion;
1701   } else if (AllowObjCWritebackConversion &&
1702              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1703     SCS.Second = ICK_Writeback_Conversion;
1704   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1705                                    FromType, IncompatibleObjC)) {
1706     // Pointer conversions (C++ 4.10).
1707     SCS.Second = ICK_Pointer_Conversion;
1708     SCS.IncompatibleObjC = IncompatibleObjC;
1709     FromType = FromType.getUnqualifiedType();
1710   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1711                                          InOverloadResolution, FromType)) {
1712     // Pointer to member conversions (4.11).
1713     SCS.Second = ICK_Pointer_Member;
1714   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1715     SCS.Second = SecondICK;
1716     FromType = ToType.getUnqualifiedType();
1717   } else if (!S.getLangOpts().CPlusPlus &&
1718              S.Context.typesAreCompatible(ToType, FromType)) {
1719     // Compatible conversions (Clang extension for C function overloading)
1720     SCS.Second = ICK_Compatible_Conversion;
1721     FromType = ToType.getUnqualifiedType();
1722   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1723     // Treat a conversion that strips "noreturn" as an identity conversion.
1724     SCS.Second = ICK_NoReturn_Adjustment;
1725   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1726                                              InOverloadResolution,
1727                                              SCS, CStyle)) {
1728     SCS.Second = ICK_TransparentUnionConversion;
1729     FromType = ToType;
1730   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1731                                  CStyle)) {
1732     // tryAtomicConversion has updated the standard conversion sequence
1733     // appropriately.
1734     return true;
1735   } else if (ToType->isEventT() &&
1736              From->isIntegerConstantExpr(S.getASTContext()) &&
1737              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1738     SCS.Second = ICK_Zero_Event_Conversion;
1739     FromType = ToType;
1740   } else {
1741     // No second conversion required.
1742     SCS.Second = ICK_Identity;
1743   }
1744   SCS.setToType(1, FromType);
1745 
1746   QualType CanonFrom;
1747   QualType CanonTo;
1748   // The third conversion can be a qualification conversion (C++ 4p1).
1749   bool ObjCLifetimeConversion;
1750   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1751                                   ObjCLifetimeConversion)) {
1752     SCS.Third = ICK_Qualification;
1753     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1754     FromType = ToType;
1755     CanonFrom = S.Context.getCanonicalType(FromType);
1756     CanonTo = S.Context.getCanonicalType(ToType);
1757   } else {
1758     // No conversion required
1759     SCS.Third = ICK_Identity;
1760 
1761     // C++ [over.best.ics]p6:
1762     //   [...] Any difference in top-level cv-qualification is
1763     //   subsumed by the initialization itself and does not constitute
1764     //   a conversion. [...]
1765     CanonFrom = S.Context.getCanonicalType(FromType);
1766     CanonTo = S.Context.getCanonicalType(ToType);
1767     if (CanonFrom.getLocalUnqualifiedType()
1768                                        == CanonTo.getLocalUnqualifiedType() &&
1769         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1770       FromType = ToType;
1771       CanonFrom = CanonTo;
1772     }
1773   }
1774   SCS.setToType(2, FromType);
1775 
1776   if (CanonFrom == CanonTo)
1777     return true;
1778 
1779   // If we have not converted the argument type to the parameter type,
1780   // this is a bad conversion sequence, unless we're resolving an overload in C.
1781   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1782     return false;
1783 
1784   ExprResult ER = ExprResult{From};
1785   auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1786                                                  /*Diagnose=*/false,
1787                                                  /*DiagnoseCFAudited=*/false,
1788                                                  /*ConvertRHS=*/false);
1789   if (Conv != Sema::Compatible)
1790     return false;
1791 
1792   SCS.setAllToTypes(ToType);
1793   // We need to set all three because we want this conversion to rank terribly,
1794   // and we don't know what conversions it may overlap with.
1795   SCS.First = ICK_C_Only_Conversion;
1796   SCS.Second = ICK_C_Only_Conversion;
1797   SCS.Third = ICK_C_Only_Conversion;
1798   return true;
1799 }
1800 
1801 static bool
1802 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1803                                      QualType &ToType,
1804                                      bool InOverloadResolution,
1805                                      StandardConversionSequence &SCS,
1806                                      bool CStyle) {
1807 
1808   const RecordType *UT = ToType->getAsUnionType();
1809   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1810     return false;
1811   // The field to initialize within the transparent union.
1812   RecordDecl *UD = UT->getDecl();
1813   // It's compatible if the expression matches any of the fields.
1814   for (const auto *it : UD->fields()) {
1815     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1816                              CStyle, /*ObjCWritebackConversion=*/false)) {
1817       ToType = it->getType();
1818       return true;
1819     }
1820   }
1821   return false;
1822 }
1823 
1824 /// IsIntegralPromotion - Determines whether the conversion from the
1825 /// expression From (whose potentially-adjusted type is FromType) to
1826 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1827 /// sets PromotedType to the promoted type.
1828 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1829   const BuiltinType *To = ToType->getAs<BuiltinType>();
1830   // All integers are built-in.
1831   if (!To) {
1832     return false;
1833   }
1834 
1835   // An rvalue of type char, signed char, unsigned char, short int, or
1836   // unsigned short int can be converted to an rvalue of type int if
1837   // int can represent all the values of the source type; otherwise,
1838   // the source rvalue can be converted to an rvalue of type unsigned
1839   // int (C++ 4.5p1).
1840   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1841       !FromType->isEnumeralType()) {
1842     if (// We can promote any signed, promotable integer type to an int
1843         (FromType->isSignedIntegerType() ||
1844          // We can promote any unsigned integer type whose size is
1845          // less than int to an int.
1846          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1847       return To->getKind() == BuiltinType::Int;
1848     }
1849 
1850     return To->getKind() == BuiltinType::UInt;
1851   }
1852 
1853   // C++11 [conv.prom]p3:
1854   //   A prvalue of an unscoped enumeration type whose underlying type is not
1855   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1856   //   following types that can represent all the values of the enumeration
1857   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1858   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1859   //   long long int. If none of the types in that list can represent all the
1860   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1861   //   type can be converted to an rvalue a prvalue of the extended integer type
1862   //   with lowest integer conversion rank (4.13) greater than the rank of long
1863   //   long in which all the values of the enumeration can be represented. If
1864   //   there are two such extended types, the signed one is chosen.
1865   // C++11 [conv.prom]p4:
1866   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1867   //   can be converted to a prvalue of its underlying type. Moreover, if
1868   //   integral promotion can be applied to its underlying type, a prvalue of an
1869   //   unscoped enumeration type whose underlying type is fixed can also be
1870   //   converted to a prvalue of the promoted underlying type.
1871   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1872     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1873     // provided for a scoped enumeration.
1874     if (FromEnumType->getDecl()->isScoped())
1875       return false;
1876 
1877     // We can perform an integral promotion to the underlying type of the enum,
1878     // even if that's not the promoted type. Note that the check for promoting
1879     // the underlying type is based on the type alone, and does not consider
1880     // the bitfield-ness of the actual source expression.
1881     if (FromEnumType->getDecl()->isFixed()) {
1882       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1883       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1884              IsIntegralPromotion(nullptr, Underlying, ToType);
1885     }
1886 
1887     // We have already pre-calculated the promotion type, so this is trivial.
1888     if (ToType->isIntegerType() &&
1889         isCompleteType(From->getLocStart(), FromType))
1890       return Context.hasSameUnqualifiedType(
1891           ToType, FromEnumType->getDecl()->getPromotionType());
1892   }
1893 
1894   // C++0x [conv.prom]p2:
1895   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1896   //   to an rvalue a prvalue of the first of the following types that can
1897   //   represent all the values of its underlying type: int, unsigned int,
1898   //   long int, unsigned long int, long long int, or unsigned long long int.
1899   //   If none of the types in that list can represent all the values of its
1900   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1901   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1902   //   type.
1903   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1904       ToType->isIntegerType()) {
1905     // Determine whether the type we're converting from is signed or
1906     // unsigned.
1907     bool FromIsSigned = FromType->isSignedIntegerType();
1908     uint64_t FromSize = Context.getTypeSize(FromType);
1909 
1910     // The types we'll try to promote to, in the appropriate
1911     // order. Try each of these types.
1912     QualType PromoteTypes[6] = {
1913       Context.IntTy, Context.UnsignedIntTy,
1914       Context.LongTy, Context.UnsignedLongTy ,
1915       Context.LongLongTy, Context.UnsignedLongLongTy
1916     };
1917     for (int Idx = 0; Idx < 6; ++Idx) {
1918       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1919       if (FromSize < ToSize ||
1920           (FromSize == ToSize &&
1921            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1922         // We found the type that we can promote to. If this is the
1923         // type we wanted, we have a promotion. Otherwise, no
1924         // promotion.
1925         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1926       }
1927     }
1928   }
1929 
1930   // An rvalue for an integral bit-field (9.6) can be converted to an
1931   // rvalue of type int if int can represent all the values of the
1932   // bit-field; otherwise, it can be converted to unsigned int if
1933   // unsigned int can represent all the values of the bit-field. If
1934   // the bit-field is larger yet, no integral promotion applies to
1935   // it. If the bit-field has an enumerated type, it is treated as any
1936   // other value of that type for promotion purposes (C++ 4.5p3).
1937   // FIXME: We should delay checking of bit-fields until we actually perform the
1938   // conversion.
1939   if (From) {
1940     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1941       llvm::APSInt BitWidth;
1942       if (FromType->isIntegralType(Context) &&
1943           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1944         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1945         ToSize = Context.getTypeSize(ToType);
1946 
1947         // Are we promoting to an int from a bitfield that fits in an int?
1948         if (BitWidth < ToSize ||
1949             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1950           return To->getKind() == BuiltinType::Int;
1951         }
1952 
1953         // Are we promoting to an unsigned int from an unsigned bitfield
1954         // that fits into an unsigned int?
1955         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1956           return To->getKind() == BuiltinType::UInt;
1957         }
1958 
1959         return false;
1960       }
1961     }
1962   }
1963 
1964   // An rvalue of type bool can be converted to an rvalue of type int,
1965   // with false becoming zero and true becoming one (C++ 4.5p4).
1966   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1967     return true;
1968   }
1969 
1970   return false;
1971 }
1972 
1973 /// IsFloatingPointPromotion - Determines whether the conversion from
1974 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1975 /// returns true and sets PromotedType to the promoted type.
1976 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1977   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1978     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1979       /// An rvalue of type float can be converted to an rvalue of type
1980       /// double. (C++ 4.6p1).
1981       if (FromBuiltin->getKind() == BuiltinType::Float &&
1982           ToBuiltin->getKind() == BuiltinType::Double)
1983         return true;
1984 
1985       // C99 6.3.1.5p1:
1986       //   When a float is promoted to double or long double, or a
1987       //   double is promoted to long double [...].
1988       if (!getLangOpts().CPlusPlus &&
1989           (FromBuiltin->getKind() == BuiltinType::Float ||
1990            FromBuiltin->getKind() == BuiltinType::Double) &&
1991           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
1992            ToBuiltin->getKind() == BuiltinType::Float128))
1993         return true;
1994 
1995       // Half can be promoted to float.
1996       if (!getLangOpts().NativeHalfType &&
1997            FromBuiltin->getKind() == BuiltinType::Half &&
1998           ToBuiltin->getKind() == BuiltinType::Float)
1999         return true;
2000     }
2001 
2002   return false;
2003 }
2004 
2005 /// \brief Determine if a conversion is a complex promotion.
2006 ///
2007 /// A complex promotion is defined as a complex -> complex conversion
2008 /// where the conversion between the underlying real types is a
2009 /// floating-point or integral promotion.
2010 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2011   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2012   if (!FromComplex)
2013     return false;
2014 
2015   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2016   if (!ToComplex)
2017     return false;
2018 
2019   return IsFloatingPointPromotion(FromComplex->getElementType(),
2020                                   ToComplex->getElementType()) ||
2021     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2022                         ToComplex->getElementType());
2023 }
2024 
2025 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2026 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2027 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2028 /// if non-empty, will be a pointer to ToType that may or may not have
2029 /// the right set of qualifiers on its pointee.
2030 ///
2031 static QualType
2032 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2033                                    QualType ToPointee, QualType ToType,
2034                                    ASTContext &Context,
2035                                    bool StripObjCLifetime = false) {
2036   assert((FromPtr->getTypeClass() == Type::Pointer ||
2037           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2038          "Invalid similarly-qualified pointer type");
2039 
2040   /// Conversions to 'id' subsume cv-qualifier conversions.
2041   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2042     return ToType.getUnqualifiedType();
2043 
2044   QualType CanonFromPointee
2045     = Context.getCanonicalType(FromPtr->getPointeeType());
2046   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2047   Qualifiers Quals = CanonFromPointee.getQualifiers();
2048 
2049   if (StripObjCLifetime)
2050     Quals.removeObjCLifetime();
2051 
2052   // Exact qualifier match -> return the pointer type we're converting to.
2053   if (CanonToPointee.getLocalQualifiers() == Quals) {
2054     // ToType is exactly what we need. Return it.
2055     if (!ToType.isNull())
2056       return ToType.getUnqualifiedType();
2057 
2058     // Build a pointer to ToPointee. It has the right qualifiers
2059     // already.
2060     if (isa<ObjCObjectPointerType>(ToType))
2061       return Context.getObjCObjectPointerType(ToPointee);
2062     return Context.getPointerType(ToPointee);
2063   }
2064 
2065   // Just build a canonical type that has the right qualifiers.
2066   QualType QualifiedCanonToPointee
2067     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2068 
2069   if (isa<ObjCObjectPointerType>(ToType))
2070     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2071   return Context.getPointerType(QualifiedCanonToPointee);
2072 }
2073 
2074 static bool isNullPointerConstantForConversion(Expr *Expr,
2075                                                bool InOverloadResolution,
2076                                                ASTContext &Context) {
2077   // Handle value-dependent integral null pointer constants correctly.
2078   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2079   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2080       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2081     return !InOverloadResolution;
2082 
2083   return Expr->isNullPointerConstant(Context,
2084                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2085                                         : Expr::NPC_ValueDependentIsNull);
2086 }
2087 
2088 /// IsPointerConversion - Determines whether the conversion of the
2089 /// expression From, which has the (possibly adjusted) type FromType,
2090 /// can be converted to the type ToType via a pointer conversion (C++
2091 /// 4.10). If so, returns true and places the converted type (that
2092 /// might differ from ToType in its cv-qualifiers at some level) into
2093 /// ConvertedType.
2094 ///
2095 /// This routine also supports conversions to and from block pointers
2096 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2097 /// pointers to interfaces. FIXME: Once we've determined the
2098 /// appropriate overloading rules for Objective-C, we may want to
2099 /// split the Objective-C checks into a different routine; however,
2100 /// GCC seems to consider all of these conversions to be pointer
2101 /// conversions, so for now they live here. IncompatibleObjC will be
2102 /// set if the conversion is an allowed Objective-C conversion that
2103 /// should result in a warning.
2104 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2105                                bool InOverloadResolution,
2106                                QualType& ConvertedType,
2107                                bool &IncompatibleObjC) {
2108   IncompatibleObjC = false;
2109   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2110                               IncompatibleObjC))
2111     return true;
2112 
2113   // Conversion from a null pointer constant to any Objective-C pointer type.
2114   if (ToType->isObjCObjectPointerType() &&
2115       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2116     ConvertedType = ToType;
2117     return true;
2118   }
2119 
2120   // Blocks: Block pointers can be converted to void*.
2121   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2122       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2123     ConvertedType = ToType;
2124     return true;
2125   }
2126   // Blocks: A null pointer constant can be converted to a block
2127   // pointer type.
2128   if (ToType->isBlockPointerType() &&
2129       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2130     ConvertedType = ToType;
2131     return true;
2132   }
2133 
2134   // If the left-hand-side is nullptr_t, the right side can be a null
2135   // pointer constant.
2136   if (ToType->isNullPtrType() &&
2137       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2138     ConvertedType = ToType;
2139     return true;
2140   }
2141 
2142   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2143   if (!ToTypePtr)
2144     return false;
2145 
2146   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2147   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2148     ConvertedType = ToType;
2149     return true;
2150   }
2151 
2152   // Beyond this point, both types need to be pointers
2153   // , including objective-c pointers.
2154   QualType ToPointeeType = ToTypePtr->getPointeeType();
2155   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2156       !getLangOpts().ObjCAutoRefCount) {
2157     ConvertedType = BuildSimilarlyQualifiedPointerType(
2158                                       FromType->getAs<ObjCObjectPointerType>(),
2159                                                        ToPointeeType,
2160                                                        ToType, Context);
2161     return true;
2162   }
2163   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2164   if (!FromTypePtr)
2165     return false;
2166 
2167   QualType FromPointeeType = FromTypePtr->getPointeeType();
2168 
2169   // If the unqualified pointee types are the same, this can't be a
2170   // pointer conversion, so don't do all of the work below.
2171   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2172     return false;
2173 
2174   // An rvalue of type "pointer to cv T," where T is an object type,
2175   // can be converted to an rvalue of type "pointer to cv void" (C++
2176   // 4.10p2).
2177   if (FromPointeeType->isIncompleteOrObjectType() &&
2178       ToPointeeType->isVoidType()) {
2179     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2180                                                        ToPointeeType,
2181                                                        ToType, Context,
2182                                                    /*StripObjCLifetime=*/true);
2183     return true;
2184   }
2185 
2186   // MSVC allows implicit function to void* type conversion.
2187   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2188       ToPointeeType->isVoidType()) {
2189     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2190                                                        ToPointeeType,
2191                                                        ToType, Context);
2192     return true;
2193   }
2194 
2195   // When we're overloading in C, we allow a special kind of pointer
2196   // conversion for compatible-but-not-identical pointee types.
2197   if (!getLangOpts().CPlusPlus &&
2198       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2199     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2200                                                        ToPointeeType,
2201                                                        ToType, Context);
2202     return true;
2203   }
2204 
2205   // C++ [conv.ptr]p3:
2206   //
2207   //   An rvalue of type "pointer to cv D," where D is a class type,
2208   //   can be converted to an rvalue of type "pointer to cv B," where
2209   //   B is a base class (clause 10) of D. If B is an inaccessible
2210   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2211   //   necessitates this conversion is ill-formed. The result of the
2212   //   conversion is a pointer to the base class sub-object of the
2213   //   derived class object. The null pointer value is converted to
2214   //   the null pointer value of the destination type.
2215   //
2216   // Note that we do not check for ambiguity or inaccessibility
2217   // here. That is handled by CheckPointerConversion.
2218   if (getLangOpts().CPlusPlus &&
2219       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2220       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2221       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2222     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2223                                                        ToPointeeType,
2224                                                        ToType, Context);
2225     return true;
2226   }
2227 
2228   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2229       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2230     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2231                                                        ToPointeeType,
2232                                                        ToType, Context);
2233     return true;
2234   }
2235 
2236   return false;
2237 }
2238 
2239 /// \brief Adopt the given qualifiers for the given type.
2240 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2241   Qualifiers TQs = T.getQualifiers();
2242 
2243   // Check whether qualifiers already match.
2244   if (TQs == Qs)
2245     return T;
2246 
2247   if (Qs.compatiblyIncludes(TQs))
2248     return Context.getQualifiedType(T, Qs);
2249 
2250   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2251 }
2252 
2253 /// isObjCPointerConversion - Determines whether this is an
2254 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2255 /// with the same arguments and return values.
2256 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2257                                    QualType& ConvertedType,
2258                                    bool &IncompatibleObjC) {
2259   if (!getLangOpts().ObjC1)
2260     return false;
2261 
2262   // The set of qualifiers on the type we're converting from.
2263   Qualifiers FromQualifiers = FromType.getQualifiers();
2264 
2265   // First, we handle all conversions on ObjC object pointer types.
2266   const ObjCObjectPointerType* ToObjCPtr =
2267     ToType->getAs<ObjCObjectPointerType>();
2268   const ObjCObjectPointerType *FromObjCPtr =
2269     FromType->getAs<ObjCObjectPointerType>();
2270 
2271   if (ToObjCPtr && FromObjCPtr) {
2272     // If the pointee types are the same (ignoring qualifications),
2273     // then this is not a pointer conversion.
2274     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2275                                        FromObjCPtr->getPointeeType()))
2276       return false;
2277 
2278     // Conversion between Objective-C pointers.
2279     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2280       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2281       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2282       if (getLangOpts().CPlusPlus && LHS && RHS &&
2283           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2284                                                 FromObjCPtr->getPointeeType()))
2285         return false;
2286       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2287                                                    ToObjCPtr->getPointeeType(),
2288                                                          ToType, Context);
2289       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2290       return true;
2291     }
2292 
2293     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2294       // Okay: this is some kind of implicit downcast of Objective-C
2295       // interfaces, which is permitted. However, we're going to
2296       // complain about it.
2297       IncompatibleObjC = true;
2298       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2299                                                    ToObjCPtr->getPointeeType(),
2300                                                          ToType, Context);
2301       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2302       return true;
2303     }
2304   }
2305   // Beyond this point, both types need to be C pointers or block pointers.
2306   QualType ToPointeeType;
2307   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2308     ToPointeeType = ToCPtr->getPointeeType();
2309   else if (const BlockPointerType *ToBlockPtr =
2310             ToType->getAs<BlockPointerType>()) {
2311     // Objective C++: We're able to convert from a pointer to any object
2312     // to a block pointer type.
2313     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2314       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2315       return true;
2316     }
2317     ToPointeeType = ToBlockPtr->getPointeeType();
2318   }
2319   else if (FromType->getAs<BlockPointerType>() &&
2320            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2321     // Objective C++: We're able to convert from a block pointer type to a
2322     // pointer to any object.
2323     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2324     return true;
2325   }
2326   else
2327     return false;
2328 
2329   QualType FromPointeeType;
2330   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2331     FromPointeeType = FromCPtr->getPointeeType();
2332   else if (const BlockPointerType *FromBlockPtr =
2333            FromType->getAs<BlockPointerType>())
2334     FromPointeeType = FromBlockPtr->getPointeeType();
2335   else
2336     return false;
2337 
2338   // If we have pointers to pointers, recursively check whether this
2339   // is an Objective-C conversion.
2340   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2341       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2342                               IncompatibleObjC)) {
2343     // We always complain about this conversion.
2344     IncompatibleObjC = true;
2345     ConvertedType = Context.getPointerType(ConvertedType);
2346     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2347     return true;
2348   }
2349   // Allow conversion of pointee being objective-c pointer to another one;
2350   // as in I* to id.
2351   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2352       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2353       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2354                               IncompatibleObjC)) {
2355 
2356     ConvertedType = Context.getPointerType(ConvertedType);
2357     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2358     return true;
2359   }
2360 
2361   // If we have pointers to functions or blocks, check whether the only
2362   // differences in the argument and result types are in Objective-C
2363   // pointer conversions. If so, we permit the conversion (but
2364   // complain about it).
2365   const FunctionProtoType *FromFunctionType
2366     = FromPointeeType->getAs<FunctionProtoType>();
2367   const FunctionProtoType *ToFunctionType
2368     = ToPointeeType->getAs<FunctionProtoType>();
2369   if (FromFunctionType && ToFunctionType) {
2370     // If the function types are exactly the same, this isn't an
2371     // Objective-C pointer conversion.
2372     if (Context.getCanonicalType(FromPointeeType)
2373           == Context.getCanonicalType(ToPointeeType))
2374       return false;
2375 
2376     // Perform the quick checks that will tell us whether these
2377     // function types are obviously different.
2378     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2379         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2380         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2381       return false;
2382 
2383     bool HasObjCConversion = false;
2384     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2385         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2386       // Okay, the types match exactly. Nothing to do.
2387     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2388                                        ToFunctionType->getReturnType(),
2389                                        ConvertedType, IncompatibleObjC)) {
2390       // Okay, we have an Objective-C pointer conversion.
2391       HasObjCConversion = true;
2392     } else {
2393       // Function types are too different. Abort.
2394       return false;
2395     }
2396 
2397     // Check argument types.
2398     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2399          ArgIdx != NumArgs; ++ArgIdx) {
2400       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2401       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2402       if (Context.getCanonicalType(FromArgType)
2403             == Context.getCanonicalType(ToArgType)) {
2404         // Okay, the types match exactly. Nothing to do.
2405       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2406                                          ConvertedType, IncompatibleObjC)) {
2407         // Okay, we have an Objective-C pointer conversion.
2408         HasObjCConversion = true;
2409       } else {
2410         // Argument types are too different. Abort.
2411         return false;
2412       }
2413     }
2414 
2415     if (HasObjCConversion) {
2416       // We had an Objective-C conversion. Allow this pointer
2417       // conversion, but complain about it.
2418       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2419       IncompatibleObjC = true;
2420       return true;
2421     }
2422   }
2423 
2424   return false;
2425 }
2426 
2427 /// \brief Determine whether this is an Objective-C writeback conversion,
2428 /// used for parameter passing when performing automatic reference counting.
2429 ///
2430 /// \param FromType The type we're converting form.
2431 ///
2432 /// \param ToType The type we're converting to.
2433 ///
2434 /// \param ConvertedType The type that will be produced after applying
2435 /// this conversion.
2436 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2437                                      QualType &ConvertedType) {
2438   if (!getLangOpts().ObjCAutoRefCount ||
2439       Context.hasSameUnqualifiedType(FromType, ToType))
2440     return false;
2441 
2442   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2443   QualType ToPointee;
2444   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2445     ToPointee = ToPointer->getPointeeType();
2446   else
2447     return false;
2448 
2449   Qualifiers ToQuals = ToPointee.getQualifiers();
2450   if (!ToPointee->isObjCLifetimeType() ||
2451       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2452       !ToQuals.withoutObjCLifetime().empty())
2453     return false;
2454 
2455   // Argument must be a pointer to __strong to __weak.
2456   QualType FromPointee;
2457   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2458     FromPointee = FromPointer->getPointeeType();
2459   else
2460     return false;
2461 
2462   Qualifiers FromQuals = FromPointee.getQualifiers();
2463   if (!FromPointee->isObjCLifetimeType() ||
2464       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2465        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2466     return false;
2467 
2468   // Make sure that we have compatible qualifiers.
2469   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2470   if (!ToQuals.compatiblyIncludes(FromQuals))
2471     return false;
2472 
2473   // Remove qualifiers from the pointee type we're converting from; they
2474   // aren't used in the compatibility check belong, and we'll be adding back
2475   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2476   FromPointee = FromPointee.getUnqualifiedType();
2477 
2478   // The unqualified form of the pointee types must be compatible.
2479   ToPointee = ToPointee.getUnqualifiedType();
2480   bool IncompatibleObjC;
2481   if (Context.typesAreCompatible(FromPointee, ToPointee))
2482     FromPointee = ToPointee;
2483   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2484                                     IncompatibleObjC))
2485     return false;
2486 
2487   /// \brief Construct the type we're converting to, which is a pointer to
2488   /// __autoreleasing pointee.
2489   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2490   ConvertedType = Context.getPointerType(FromPointee);
2491   return true;
2492 }
2493 
2494 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2495                                     QualType& ConvertedType) {
2496   QualType ToPointeeType;
2497   if (const BlockPointerType *ToBlockPtr =
2498         ToType->getAs<BlockPointerType>())
2499     ToPointeeType = ToBlockPtr->getPointeeType();
2500   else
2501     return false;
2502 
2503   QualType FromPointeeType;
2504   if (const BlockPointerType *FromBlockPtr =
2505       FromType->getAs<BlockPointerType>())
2506     FromPointeeType = FromBlockPtr->getPointeeType();
2507   else
2508     return false;
2509   // We have pointer to blocks, check whether the only
2510   // differences in the argument and result types are in Objective-C
2511   // pointer conversions. If so, we permit the conversion.
2512 
2513   const FunctionProtoType *FromFunctionType
2514     = FromPointeeType->getAs<FunctionProtoType>();
2515   const FunctionProtoType *ToFunctionType
2516     = ToPointeeType->getAs<FunctionProtoType>();
2517 
2518   if (!FromFunctionType || !ToFunctionType)
2519     return false;
2520 
2521   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2522     return true;
2523 
2524   // Perform the quick checks that will tell us whether these
2525   // function types are obviously different.
2526   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2527       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2528     return false;
2529 
2530   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2531   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2532   if (FromEInfo != ToEInfo)
2533     return false;
2534 
2535   bool IncompatibleObjC = false;
2536   if (Context.hasSameType(FromFunctionType->getReturnType(),
2537                           ToFunctionType->getReturnType())) {
2538     // Okay, the types match exactly. Nothing to do.
2539   } else {
2540     QualType RHS = FromFunctionType->getReturnType();
2541     QualType LHS = ToFunctionType->getReturnType();
2542     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2543         !RHS.hasQualifiers() && LHS.hasQualifiers())
2544        LHS = LHS.getUnqualifiedType();
2545 
2546      if (Context.hasSameType(RHS,LHS)) {
2547        // OK exact match.
2548      } else if (isObjCPointerConversion(RHS, LHS,
2549                                         ConvertedType, IncompatibleObjC)) {
2550      if (IncompatibleObjC)
2551        return false;
2552      // Okay, we have an Objective-C pointer conversion.
2553      }
2554      else
2555        return false;
2556    }
2557 
2558    // Check argument types.
2559    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2560         ArgIdx != NumArgs; ++ArgIdx) {
2561      IncompatibleObjC = false;
2562      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2563      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2564      if (Context.hasSameType(FromArgType, ToArgType)) {
2565        // Okay, the types match exactly. Nothing to do.
2566      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2567                                         ConvertedType, IncompatibleObjC)) {
2568        if (IncompatibleObjC)
2569          return false;
2570        // Okay, we have an Objective-C pointer conversion.
2571      } else
2572        // Argument types are too different. Abort.
2573        return false;
2574    }
2575    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2576                                                         ToFunctionType))
2577      return false;
2578 
2579    ConvertedType = ToType;
2580    return true;
2581 }
2582 
2583 enum {
2584   ft_default,
2585   ft_different_class,
2586   ft_parameter_arity,
2587   ft_parameter_mismatch,
2588   ft_return_type,
2589   ft_qualifer_mismatch
2590 };
2591 
2592 /// Attempts to get the FunctionProtoType from a Type. Handles
2593 /// MemberFunctionPointers properly.
2594 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2595   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2596     return FPT;
2597 
2598   if (auto *MPT = FromType->getAs<MemberPointerType>())
2599     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2600 
2601   return nullptr;
2602 }
2603 
2604 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2605 /// function types.  Catches different number of parameter, mismatch in
2606 /// parameter types, and different return types.
2607 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2608                                       QualType FromType, QualType ToType) {
2609   // If either type is not valid, include no extra info.
2610   if (FromType.isNull() || ToType.isNull()) {
2611     PDiag << ft_default;
2612     return;
2613   }
2614 
2615   // Get the function type from the pointers.
2616   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2617     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2618                             *ToMember = ToType->getAs<MemberPointerType>();
2619     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2620       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2621             << QualType(FromMember->getClass(), 0);
2622       return;
2623     }
2624     FromType = FromMember->getPointeeType();
2625     ToType = ToMember->getPointeeType();
2626   }
2627 
2628   if (FromType->isPointerType())
2629     FromType = FromType->getPointeeType();
2630   if (ToType->isPointerType())
2631     ToType = ToType->getPointeeType();
2632 
2633   // Remove references.
2634   FromType = FromType.getNonReferenceType();
2635   ToType = ToType.getNonReferenceType();
2636 
2637   // Don't print extra info for non-specialized template functions.
2638   if (FromType->isInstantiationDependentType() &&
2639       !FromType->getAs<TemplateSpecializationType>()) {
2640     PDiag << ft_default;
2641     return;
2642   }
2643 
2644   // No extra info for same types.
2645   if (Context.hasSameType(FromType, ToType)) {
2646     PDiag << ft_default;
2647     return;
2648   }
2649 
2650   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2651                           *ToFunction = tryGetFunctionProtoType(ToType);
2652 
2653   // Both types need to be function types.
2654   if (!FromFunction || !ToFunction) {
2655     PDiag << ft_default;
2656     return;
2657   }
2658 
2659   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2660     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2661           << FromFunction->getNumParams();
2662     return;
2663   }
2664 
2665   // Handle different parameter types.
2666   unsigned ArgPos;
2667   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2668     PDiag << ft_parameter_mismatch << ArgPos + 1
2669           << ToFunction->getParamType(ArgPos)
2670           << FromFunction->getParamType(ArgPos);
2671     return;
2672   }
2673 
2674   // Handle different return type.
2675   if (!Context.hasSameType(FromFunction->getReturnType(),
2676                            ToFunction->getReturnType())) {
2677     PDiag << ft_return_type << ToFunction->getReturnType()
2678           << FromFunction->getReturnType();
2679     return;
2680   }
2681 
2682   unsigned FromQuals = FromFunction->getTypeQuals(),
2683            ToQuals = ToFunction->getTypeQuals();
2684   if (FromQuals != ToQuals) {
2685     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2686     return;
2687   }
2688 
2689   // Unable to find a difference, so add no extra info.
2690   PDiag << ft_default;
2691 }
2692 
2693 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2694 /// for equality of their argument types. Caller has already checked that
2695 /// they have same number of arguments.  If the parameters are different,
2696 /// ArgPos will have the parameter index of the first different parameter.
2697 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2698                                       const FunctionProtoType *NewType,
2699                                       unsigned *ArgPos) {
2700   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2701                                               N = NewType->param_type_begin(),
2702                                               E = OldType->param_type_end();
2703        O && (O != E); ++O, ++N) {
2704     if (!Context.hasSameType(O->getUnqualifiedType(),
2705                              N->getUnqualifiedType())) {
2706       if (ArgPos)
2707         *ArgPos = O - OldType->param_type_begin();
2708       return false;
2709     }
2710   }
2711   return true;
2712 }
2713 
2714 /// CheckPointerConversion - Check the pointer conversion from the
2715 /// expression From to the type ToType. This routine checks for
2716 /// ambiguous or inaccessible derived-to-base pointer
2717 /// conversions for which IsPointerConversion has already returned
2718 /// true. It returns true and produces a diagnostic if there was an
2719 /// error, or returns false otherwise.
2720 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2721                                   CastKind &Kind,
2722                                   CXXCastPath& BasePath,
2723                                   bool IgnoreBaseAccess,
2724                                   bool Diagnose) {
2725   QualType FromType = From->getType();
2726   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2727 
2728   Kind = CK_BitCast;
2729 
2730   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2731       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2732           Expr::NPCK_ZeroExpression) {
2733     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2734       DiagRuntimeBehavior(From->getExprLoc(), From,
2735                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2736                             << ToType << From->getSourceRange());
2737     else if (!isUnevaluatedContext())
2738       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2739         << ToType << From->getSourceRange();
2740   }
2741   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2742     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2743       QualType FromPointeeType = FromPtrType->getPointeeType(),
2744                ToPointeeType   = ToPtrType->getPointeeType();
2745 
2746       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2747           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2748         // We must have a derived-to-base conversion. Check an
2749         // ambiguous or inaccessible conversion.
2750         unsigned InaccessibleID = 0;
2751         unsigned AmbigiousID = 0;
2752         if (Diagnose) {
2753           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2754           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2755         }
2756         if (CheckDerivedToBaseConversion(
2757                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2758                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2759                 &BasePath, IgnoreBaseAccess))
2760           return true;
2761 
2762         // The conversion was successful.
2763         Kind = CK_DerivedToBase;
2764       }
2765 
2766       if (Diagnose && !IsCStyleOrFunctionalCast &&
2767           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2768         assert(getLangOpts().MSVCCompat &&
2769                "this should only be possible with MSVCCompat!");
2770         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2771             << From->getSourceRange();
2772       }
2773     }
2774   } else if (const ObjCObjectPointerType *ToPtrType =
2775                ToType->getAs<ObjCObjectPointerType>()) {
2776     if (const ObjCObjectPointerType *FromPtrType =
2777           FromType->getAs<ObjCObjectPointerType>()) {
2778       // Objective-C++ conversions are always okay.
2779       // FIXME: We should have a different class of conversions for the
2780       // Objective-C++ implicit conversions.
2781       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2782         return false;
2783     } else if (FromType->isBlockPointerType()) {
2784       Kind = CK_BlockPointerToObjCPointerCast;
2785     } else {
2786       Kind = CK_CPointerToObjCPointerCast;
2787     }
2788   } else if (ToType->isBlockPointerType()) {
2789     if (!FromType->isBlockPointerType())
2790       Kind = CK_AnyPointerToBlockPointerCast;
2791   }
2792 
2793   // We shouldn't fall into this case unless it's valid for other
2794   // reasons.
2795   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2796     Kind = CK_NullToPointer;
2797 
2798   return false;
2799 }
2800 
2801 /// IsMemberPointerConversion - Determines whether the conversion of the
2802 /// expression From, which has the (possibly adjusted) type FromType, can be
2803 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2804 /// If so, returns true and places the converted type (that might differ from
2805 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2806 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2807                                      QualType ToType,
2808                                      bool InOverloadResolution,
2809                                      QualType &ConvertedType) {
2810   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2811   if (!ToTypePtr)
2812     return false;
2813 
2814   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2815   if (From->isNullPointerConstant(Context,
2816                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2817                                         : Expr::NPC_ValueDependentIsNull)) {
2818     ConvertedType = ToType;
2819     return true;
2820   }
2821 
2822   // Otherwise, both types have to be member pointers.
2823   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2824   if (!FromTypePtr)
2825     return false;
2826 
2827   // A pointer to member of B can be converted to a pointer to member of D,
2828   // where D is derived from B (C++ 4.11p2).
2829   QualType FromClass(FromTypePtr->getClass(), 0);
2830   QualType ToClass(ToTypePtr->getClass(), 0);
2831 
2832   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2833       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2834     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2835                                                  ToClass.getTypePtr());
2836     return true;
2837   }
2838 
2839   return false;
2840 }
2841 
2842 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2843 /// expression From to the type ToType. This routine checks for ambiguous or
2844 /// virtual or inaccessible base-to-derived member pointer conversions
2845 /// for which IsMemberPointerConversion has already returned true. It returns
2846 /// true and produces a diagnostic if there was an error, or returns false
2847 /// otherwise.
2848 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2849                                         CastKind &Kind,
2850                                         CXXCastPath &BasePath,
2851                                         bool IgnoreBaseAccess) {
2852   QualType FromType = From->getType();
2853   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2854   if (!FromPtrType) {
2855     // This must be a null pointer to member pointer conversion
2856     assert(From->isNullPointerConstant(Context,
2857                                        Expr::NPC_ValueDependentIsNull) &&
2858            "Expr must be null pointer constant!");
2859     Kind = CK_NullToMemberPointer;
2860     return false;
2861   }
2862 
2863   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2864   assert(ToPtrType && "No member pointer cast has a target type "
2865                       "that is not a member pointer.");
2866 
2867   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2868   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2869 
2870   // FIXME: What about dependent types?
2871   assert(FromClass->isRecordType() && "Pointer into non-class.");
2872   assert(ToClass->isRecordType() && "Pointer into non-class.");
2873 
2874   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2875                      /*DetectVirtual=*/true);
2876   bool DerivationOkay =
2877       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2878   assert(DerivationOkay &&
2879          "Should not have been called if derivation isn't OK.");
2880   (void)DerivationOkay;
2881 
2882   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2883                                   getUnqualifiedType())) {
2884     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2885     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2886       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2887     return true;
2888   }
2889 
2890   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2891     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2892       << FromClass << ToClass << QualType(VBase, 0)
2893       << From->getSourceRange();
2894     return true;
2895   }
2896 
2897   if (!IgnoreBaseAccess)
2898     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2899                          Paths.front(),
2900                          diag::err_downcast_from_inaccessible_base);
2901 
2902   // Must be a base to derived member conversion.
2903   BuildBasePathArray(Paths, BasePath);
2904   Kind = CK_BaseToDerivedMemberPointer;
2905   return false;
2906 }
2907 
2908 /// Determine whether the lifetime conversion between the two given
2909 /// qualifiers sets is nontrivial.
2910 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2911                                                Qualifiers ToQuals) {
2912   // Converting anything to const __unsafe_unretained is trivial.
2913   if (ToQuals.hasConst() &&
2914       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2915     return false;
2916 
2917   return true;
2918 }
2919 
2920 /// IsQualificationConversion - Determines whether the conversion from
2921 /// an rvalue of type FromType to ToType is a qualification conversion
2922 /// (C++ 4.4).
2923 ///
2924 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2925 /// when the qualification conversion involves a change in the Objective-C
2926 /// object lifetime.
2927 bool
2928 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2929                                 bool CStyle, bool &ObjCLifetimeConversion) {
2930   FromType = Context.getCanonicalType(FromType);
2931   ToType = Context.getCanonicalType(ToType);
2932   ObjCLifetimeConversion = false;
2933 
2934   // If FromType and ToType are the same type, this is not a
2935   // qualification conversion.
2936   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2937     return false;
2938 
2939   // (C++ 4.4p4):
2940   //   A conversion can add cv-qualifiers at levels other than the first
2941   //   in multi-level pointers, subject to the following rules: [...]
2942   bool PreviousToQualsIncludeConst = true;
2943   bool UnwrappedAnyPointer = false;
2944   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2945     // Within each iteration of the loop, we check the qualifiers to
2946     // determine if this still looks like a qualification
2947     // conversion. Then, if all is well, we unwrap one more level of
2948     // pointers or pointers-to-members and do it all again
2949     // until there are no more pointers or pointers-to-members left to
2950     // unwrap.
2951     UnwrappedAnyPointer = true;
2952 
2953     Qualifiers FromQuals = FromType.getQualifiers();
2954     Qualifiers ToQuals = ToType.getQualifiers();
2955 
2956     // Ignore __unaligned qualifier if this type is void.
2957     if (ToType.getUnqualifiedType()->isVoidType())
2958       FromQuals.removeUnaligned();
2959 
2960     // Objective-C ARC:
2961     //   Check Objective-C lifetime conversions.
2962     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2963         UnwrappedAnyPointer) {
2964       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2965         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2966           ObjCLifetimeConversion = true;
2967         FromQuals.removeObjCLifetime();
2968         ToQuals.removeObjCLifetime();
2969       } else {
2970         // Qualification conversions cannot cast between different
2971         // Objective-C lifetime qualifiers.
2972         return false;
2973       }
2974     }
2975 
2976     // Allow addition/removal of GC attributes but not changing GC attributes.
2977     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2978         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2979       FromQuals.removeObjCGCAttr();
2980       ToQuals.removeObjCGCAttr();
2981     }
2982 
2983     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2984     //      2,j, and similarly for volatile.
2985     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2986       return false;
2987 
2988     //   -- if the cv 1,j and cv 2,j are different, then const is in
2989     //      every cv for 0 < k < j.
2990     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2991         && !PreviousToQualsIncludeConst)
2992       return false;
2993 
2994     // Keep track of whether all prior cv-qualifiers in the "to" type
2995     // include const.
2996     PreviousToQualsIncludeConst
2997       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2998   }
2999 
3000   // We are left with FromType and ToType being the pointee types
3001   // after unwrapping the original FromType and ToType the same number
3002   // of types. If we unwrapped any pointers, and if FromType and
3003   // ToType have the same unqualified type (since we checked
3004   // qualifiers above), then this is a qualification conversion.
3005   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3006 }
3007 
3008 /// \brief - Determine whether this is a conversion from a scalar type to an
3009 /// atomic type.
3010 ///
3011 /// If successful, updates \c SCS's second and third steps in the conversion
3012 /// sequence to finish the conversion.
3013 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3014                                 bool InOverloadResolution,
3015                                 StandardConversionSequence &SCS,
3016                                 bool CStyle) {
3017   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3018   if (!ToAtomic)
3019     return false;
3020 
3021   StandardConversionSequence InnerSCS;
3022   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3023                             InOverloadResolution, InnerSCS,
3024                             CStyle, /*AllowObjCWritebackConversion=*/false))
3025     return false;
3026 
3027   SCS.Second = InnerSCS.Second;
3028   SCS.setToType(1, InnerSCS.getToType(1));
3029   SCS.Third = InnerSCS.Third;
3030   SCS.QualificationIncludesObjCLifetime
3031     = InnerSCS.QualificationIncludesObjCLifetime;
3032   SCS.setToType(2, InnerSCS.getToType(2));
3033   return true;
3034 }
3035 
3036 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3037                                               CXXConstructorDecl *Constructor,
3038                                               QualType Type) {
3039   const FunctionProtoType *CtorType =
3040       Constructor->getType()->getAs<FunctionProtoType>();
3041   if (CtorType->getNumParams() > 0) {
3042     QualType FirstArg = CtorType->getParamType(0);
3043     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3044       return true;
3045   }
3046   return false;
3047 }
3048 
3049 static OverloadingResult
3050 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3051                                        CXXRecordDecl *To,
3052                                        UserDefinedConversionSequence &User,
3053                                        OverloadCandidateSet &CandidateSet,
3054                                        bool AllowExplicit) {
3055   for (auto *D : S.LookupConstructors(To)) {
3056     auto Info = getConstructorInfo(D);
3057     if (!Info)
3058       continue;
3059 
3060     bool Usable = !Info.Constructor->isInvalidDecl() &&
3061                   S.isInitListConstructor(Info.Constructor) &&
3062                   (AllowExplicit || !Info.Constructor->isExplicit());
3063     if (Usable) {
3064       // If the first argument is (a reference to) the target type,
3065       // suppress conversions.
3066       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3067           S.Context, Info.Constructor, ToType);
3068       if (Info.ConstructorTmpl)
3069         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3070                                        /*ExplicitArgs*/ nullptr, From,
3071                                        CandidateSet, SuppressUserConversions);
3072       else
3073         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3074                                CandidateSet, SuppressUserConversions);
3075     }
3076   }
3077 
3078   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3079 
3080   OverloadCandidateSet::iterator Best;
3081   switch (auto Result =
3082             CandidateSet.BestViableFunction(S, From->getLocStart(),
3083                                             Best, true)) {
3084   case OR_Deleted:
3085   case OR_Success: {
3086     // Record the standard conversion we used and the conversion function.
3087     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3088     QualType ThisType = Constructor->getThisType(S.Context);
3089     // Initializer lists don't have conversions as such.
3090     User.Before.setAsIdentityConversion();
3091     User.HadMultipleCandidates = HadMultipleCandidates;
3092     User.ConversionFunction = Constructor;
3093     User.FoundConversionFunction = Best->FoundDecl;
3094     User.After.setAsIdentityConversion();
3095     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3096     User.After.setAllToTypes(ToType);
3097     return Result;
3098   }
3099 
3100   case OR_No_Viable_Function:
3101     return OR_No_Viable_Function;
3102   case OR_Ambiguous:
3103     return OR_Ambiguous;
3104   }
3105 
3106   llvm_unreachable("Invalid OverloadResult!");
3107 }
3108 
3109 /// Determines whether there is a user-defined conversion sequence
3110 /// (C++ [over.ics.user]) that converts expression From to the type
3111 /// ToType. If such a conversion exists, User will contain the
3112 /// user-defined conversion sequence that performs such a conversion
3113 /// and this routine will return true. Otherwise, this routine returns
3114 /// false and User is unspecified.
3115 ///
3116 /// \param AllowExplicit  true if the conversion should consider C++0x
3117 /// "explicit" conversion functions as well as non-explicit conversion
3118 /// functions (C++0x [class.conv.fct]p2).
3119 ///
3120 /// \param AllowObjCConversionOnExplicit true if the conversion should
3121 /// allow an extra Objective-C pointer conversion on uses of explicit
3122 /// constructors. Requires \c AllowExplicit to also be set.
3123 static OverloadingResult
3124 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3125                         UserDefinedConversionSequence &User,
3126                         OverloadCandidateSet &CandidateSet,
3127                         bool AllowExplicit,
3128                         bool AllowObjCConversionOnExplicit) {
3129   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3130 
3131   // Whether we will only visit constructors.
3132   bool ConstructorsOnly = false;
3133 
3134   // If the type we are conversion to is a class type, enumerate its
3135   // constructors.
3136   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3137     // C++ [over.match.ctor]p1:
3138     //   When objects of class type are direct-initialized (8.5), or
3139     //   copy-initialized from an expression of the same or a
3140     //   derived class type (8.5), overload resolution selects the
3141     //   constructor. [...] For copy-initialization, the candidate
3142     //   functions are all the converting constructors (12.3.1) of
3143     //   that class. The argument list is the expression-list within
3144     //   the parentheses of the initializer.
3145     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3146         (From->getType()->getAs<RecordType>() &&
3147          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3148       ConstructorsOnly = true;
3149 
3150     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3151       // We're not going to find any constructors.
3152     } else if (CXXRecordDecl *ToRecordDecl
3153                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3154 
3155       Expr **Args = &From;
3156       unsigned NumArgs = 1;
3157       bool ListInitializing = false;
3158       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3159         // But first, see if there is an init-list-constructor that will work.
3160         OverloadingResult Result = IsInitializerListConstructorConversion(
3161             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3162         if (Result != OR_No_Viable_Function)
3163           return Result;
3164         // Never mind.
3165         CandidateSet.clear();
3166 
3167         // If we're list-initializing, we pass the individual elements as
3168         // arguments, not the entire list.
3169         Args = InitList->getInits();
3170         NumArgs = InitList->getNumInits();
3171         ListInitializing = true;
3172       }
3173 
3174       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3175         auto Info = getConstructorInfo(D);
3176         if (!Info)
3177           continue;
3178 
3179         bool Usable = !Info.Constructor->isInvalidDecl();
3180         if (ListInitializing)
3181           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3182         else
3183           Usable = Usable &&
3184                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3185         if (Usable) {
3186           bool SuppressUserConversions = !ConstructorsOnly;
3187           if (SuppressUserConversions && ListInitializing) {
3188             SuppressUserConversions = false;
3189             if (NumArgs == 1) {
3190               // If the first argument is (a reference to) the target type,
3191               // suppress conversions.
3192               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3193                   S.Context, Info.Constructor, ToType);
3194             }
3195           }
3196           if (Info.ConstructorTmpl)
3197             S.AddTemplateOverloadCandidate(
3198                 Info.ConstructorTmpl, Info.FoundDecl,
3199                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3200                 CandidateSet, SuppressUserConversions);
3201           else
3202             // Allow one user-defined conversion when user specifies a
3203             // From->ToType conversion via an static cast (c-style, etc).
3204             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3205                                    llvm::makeArrayRef(Args, NumArgs),
3206                                    CandidateSet, SuppressUserConversions);
3207         }
3208       }
3209     }
3210   }
3211 
3212   // Enumerate conversion functions, if we're allowed to.
3213   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3214   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3215     // No conversion functions from incomplete types.
3216   } else if (const RecordType *FromRecordType
3217                                    = From->getType()->getAs<RecordType>()) {
3218     if (CXXRecordDecl *FromRecordDecl
3219          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3220       // Add all of the conversion functions as candidates.
3221       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3222       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3223         DeclAccessPair FoundDecl = I.getPair();
3224         NamedDecl *D = FoundDecl.getDecl();
3225         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3226         if (isa<UsingShadowDecl>(D))
3227           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3228 
3229         CXXConversionDecl *Conv;
3230         FunctionTemplateDecl *ConvTemplate;
3231         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3232           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3233         else
3234           Conv = cast<CXXConversionDecl>(D);
3235 
3236         if (AllowExplicit || !Conv->isExplicit()) {
3237           if (ConvTemplate)
3238             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3239                                              ActingContext, From, ToType,
3240                                              CandidateSet,
3241                                              AllowObjCConversionOnExplicit);
3242           else
3243             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3244                                      From, ToType, CandidateSet,
3245                                      AllowObjCConversionOnExplicit);
3246         }
3247       }
3248     }
3249   }
3250 
3251   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3252 
3253   OverloadCandidateSet::iterator Best;
3254   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3255                                                         Best, true)) {
3256   case OR_Success:
3257   case OR_Deleted:
3258     // Record the standard conversion we used and the conversion function.
3259     if (CXXConstructorDecl *Constructor
3260           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3261       // C++ [over.ics.user]p1:
3262       //   If the user-defined conversion is specified by a
3263       //   constructor (12.3.1), the initial standard conversion
3264       //   sequence converts the source type to the type required by
3265       //   the argument of the constructor.
3266       //
3267       QualType ThisType = Constructor->getThisType(S.Context);
3268       if (isa<InitListExpr>(From)) {
3269         // Initializer lists don't have conversions as such.
3270         User.Before.setAsIdentityConversion();
3271       } else {
3272         if (Best->Conversions[0].isEllipsis())
3273           User.EllipsisConversion = true;
3274         else {
3275           User.Before = Best->Conversions[0].Standard;
3276           User.EllipsisConversion = false;
3277         }
3278       }
3279       User.HadMultipleCandidates = HadMultipleCandidates;
3280       User.ConversionFunction = Constructor;
3281       User.FoundConversionFunction = Best->FoundDecl;
3282       User.After.setAsIdentityConversion();
3283       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3284       User.After.setAllToTypes(ToType);
3285       return Result;
3286     }
3287     if (CXXConversionDecl *Conversion
3288                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3289       // C++ [over.ics.user]p1:
3290       //
3291       //   [...] If the user-defined conversion is specified by a
3292       //   conversion function (12.3.2), the initial standard
3293       //   conversion sequence converts the source type to the
3294       //   implicit object parameter of the conversion function.
3295       User.Before = Best->Conversions[0].Standard;
3296       User.HadMultipleCandidates = HadMultipleCandidates;
3297       User.ConversionFunction = Conversion;
3298       User.FoundConversionFunction = Best->FoundDecl;
3299       User.EllipsisConversion = false;
3300 
3301       // C++ [over.ics.user]p2:
3302       //   The second standard conversion sequence converts the
3303       //   result of the user-defined conversion to the target type
3304       //   for the sequence. Since an implicit conversion sequence
3305       //   is an initialization, the special rules for
3306       //   initialization by user-defined conversion apply when
3307       //   selecting the best user-defined conversion for a
3308       //   user-defined conversion sequence (see 13.3.3 and
3309       //   13.3.3.1).
3310       User.After = Best->FinalConversion;
3311       return Result;
3312     }
3313     llvm_unreachable("Not a constructor or conversion function?");
3314 
3315   case OR_No_Viable_Function:
3316     return OR_No_Viable_Function;
3317 
3318   case OR_Ambiguous:
3319     return OR_Ambiguous;
3320   }
3321 
3322   llvm_unreachable("Invalid OverloadResult!");
3323 }
3324 
3325 bool
3326 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3327   ImplicitConversionSequence ICS;
3328   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3329                                     OverloadCandidateSet::CSK_Normal);
3330   OverloadingResult OvResult =
3331     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3332                             CandidateSet, false, false);
3333   if (OvResult == OR_Ambiguous)
3334     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3335         << From->getType() << ToType << From->getSourceRange();
3336   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3337     if (!RequireCompleteType(From->getLocStart(), ToType,
3338                              diag::err_typecheck_nonviable_condition_incomplete,
3339                              From->getType(), From->getSourceRange()))
3340       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3341           << false << From->getType() << From->getSourceRange() << ToType;
3342   } else
3343     return false;
3344   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3345   return true;
3346 }
3347 
3348 /// \brief Compare the user-defined conversion functions or constructors
3349 /// of two user-defined conversion sequences to determine whether any ordering
3350 /// is possible.
3351 static ImplicitConversionSequence::CompareKind
3352 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3353                            FunctionDecl *Function2) {
3354   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3355     return ImplicitConversionSequence::Indistinguishable;
3356 
3357   // Objective-C++:
3358   //   If both conversion functions are implicitly-declared conversions from
3359   //   a lambda closure type to a function pointer and a block pointer,
3360   //   respectively, always prefer the conversion to a function pointer,
3361   //   because the function pointer is more lightweight and is more likely
3362   //   to keep code working.
3363   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3364   if (!Conv1)
3365     return ImplicitConversionSequence::Indistinguishable;
3366 
3367   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3368   if (!Conv2)
3369     return ImplicitConversionSequence::Indistinguishable;
3370 
3371   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3372     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3373     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3374     if (Block1 != Block2)
3375       return Block1 ? ImplicitConversionSequence::Worse
3376                     : ImplicitConversionSequence::Better;
3377   }
3378 
3379   return ImplicitConversionSequence::Indistinguishable;
3380 }
3381 
3382 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3383     const ImplicitConversionSequence &ICS) {
3384   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3385          (ICS.isUserDefined() &&
3386           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3387 }
3388 
3389 /// CompareImplicitConversionSequences - Compare two implicit
3390 /// conversion sequences to determine whether one is better than the
3391 /// other or if they are indistinguishable (C++ 13.3.3.2).
3392 static ImplicitConversionSequence::CompareKind
3393 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3394                                    const ImplicitConversionSequence& ICS1,
3395                                    const ImplicitConversionSequence& ICS2)
3396 {
3397   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3398   // conversion sequences (as defined in 13.3.3.1)
3399   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3400   //      conversion sequence than a user-defined conversion sequence or
3401   //      an ellipsis conversion sequence, and
3402   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3403   //      conversion sequence than an ellipsis conversion sequence
3404   //      (13.3.3.1.3).
3405   //
3406   // C++0x [over.best.ics]p10:
3407   //   For the purpose of ranking implicit conversion sequences as
3408   //   described in 13.3.3.2, the ambiguous conversion sequence is
3409   //   treated as a user-defined sequence that is indistinguishable
3410   //   from any other user-defined conversion sequence.
3411 
3412   // String literal to 'char *' conversion has been deprecated in C++03. It has
3413   // been removed from C++11. We still accept this conversion, if it happens at
3414   // the best viable function. Otherwise, this conversion is considered worse
3415   // than ellipsis conversion. Consider this as an extension; this is not in the
3416   // standard. For example:
3417   //
3418   // int &f(...);    // #1
3419   // void f(char*);  // #2
3420   // void g() { int &r = f("foo"); }
3421   //
3422   // In C++03, we pick #2 as the best viable function.
3423   // In C++11, we pick #1 as the best viable function, because ellipsis
3424   // conversion is better than string-literal to char* conversion (since there
3425   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3426   // convert arguments, #2 would be the best viable function in C++11.
3427   // If the best viable function has this conversion, a warning will be issued
3428   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3429 
3430   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3431       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3432       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3433     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3434                ? ImplicitConversionSequence::Worse
3435                : ImplicitConversionSequence::Better;
3436 
3437   if (ICS1.getKindRank() < ICS2.getKindRank())
3438     return ImplicitConversionSequence::Better;
3439   if (ICS2.getKindRank() < ICS1.getKindRank())
3440     return ImplicitConversionSequence::Worse;
3441 
3442   // The following checks require both conversion sequences to be of
3443   // the same kind.
3444   if (ICS1.getKind() != ICS2.getKind())
3445     return ImplicitConversionSequence::Indistinguishable;
3446 
3447   ImplicitConversionSequence::CompareKind Result =
3448       ImplicitConversionSequence::Indistinguishable;
3449 
3450   // Two implicit conversion sequences of the same form are
3451   // indistinguishable conversion sequences unless one of the
3452   // following rules apply: (C++ 13.3.3.2p3):
3453 
3454   // List-initialization sequence L1 is a better conversion sequence than
3455   // list-initialization sequence L2 if:
3456   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3457   //   if not that,
3458   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3459   //   and N1 is smaller than N2.,
3460   // even if one of the other rules in this paragraph would otherwise apply.
3461   if (!ICS1.isBad()) {
3462     if (ICS1.isStdInitializerListElement() &&
3463         !ICS2.isStdInitializerListElement())
3464       return ImplicitConversionSequence::Better;
3465     if (!ICS1.isStdInitializerListElement() &&
3466         ICS2.isStdInitializerListElement())
3467       return ImplicitConversionSequence::Worse;
3468   }
3469 
3470   if (ICS1.isStandard())
3471     // Standard conversion sequence S1 is a better conversion sequence than
3472     // standard conversion sequence S2 if [...]
3473     Result = CompareStandardConversionSequences(S, Loc,
3474                                                 ICS1.Standard, ICS2.Standard);
3475   else if (ICS1.isUserDefined()) {
3476     // User-defined conversion sequence U1 is a better conversion
3477     // sequence than another user-defined conversion sequence U2 if
3478     // they contain the same user-defined conversion function or
3479     // constructor and if the second standard conversion sequence of
3480     // U1 is better than the second standard conversion sequence of
3481     // U2 (C++ 13.3.3.2p3).
3482     if (ICS1.UserDefined.ConversionFunction ==
3483           ICS2.UserDefined.ConversionFunction)
3484       Result = CompareStandardConversionSequences(S, Loc,
3485                                                   ICS1.UserDefined.After,
3486                                                   ICS2.UserDefined.After);
3487     else
3488       Result = compareConversionFunctions(S,
3489                                           ICS1.UserDefined.ConversionFunction,
3490                                           ICS2.UserDefined.ConversionFunction);
3491   }
3492 
3493   return Result;
3494 }
3495 
3496 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3497   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3498     Qualifiers Quals;
3499     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3500     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3501   }
3502 
3503   return Context.hasSameUnqualifiedType(T1, T2);
3504 }
3505 
3506 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3507 // determine if one is a proper subset of the other.
3508 static ImplicitConversionSequence::CompareKind
3509 compareStandardConversionSubsets(ASTContext &Context,
3510                                  const StandardConversionSequence& SCS1,
3511                                  const StandardConversionSequence& SCS2) {
3512   ImplicitConversionSequence::CompareKind Result
3513     = ImplicitConversionSequence::Indistinguishable;
3514 
3515   // the identity conversion sequence is considered to be a subsequence of
3516   // any non-identity conversion sequence
3517   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3518     return ImplicitConversionSequence::Better;
3519   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3520     return ImplicitConversionSequence::Worse;
3521 
3522   if (SCS1.Second != SCS2.Second) {
3523     if (SCS1.Second == ICK_Identity)
3524       Result = ImplicitConversionSequence::Better;
3525     else if (SCS2.Second == ICK_Identity)
3526       Result = ImplicitConversionSequence::Worse;
3527     else
3528       return ImplicitConversionSequence::Indistinguishable;
3529   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3530     return ImplicitConversionSequence::Indistinguishable;
3531 
3532   if (SCS1.Third == SCS2.Third) {
3533     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3534                              : ImplicitConversionSequence::Indistinguishable;
3535   }
3536 
3537   if (SCS1.Third == ICK_Identity)
3538     return Result == ImplicitConversionSequence::Worse
3539              ? ImplicitConversionSequence::Indistinguishable
3540              : ImplicitConversionSequence::Better;
3541 
3542   if (SCS2.Third == ICK_Identity)
3543     return Result == ImplicitConversionSequence::Better
3544              ? ImplicitConversionSequence::Indistinguishable
3545              : ImplicitConversionSequence::Worse;
3546 
3547   return ImplicitConversionSequence::Indistinguishable;
3548 }
3549 
3550 /// \brief Determine whether one of the given reference bindings is better
3551 /// than the other based on what kind of bindings they are.
3552 static bool
3553 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3554                              const StandardConversionSequence &SCS2) {
3555   // C++0x [over.ics.rank]p3b4:
3556   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3557   //      implicit object parameter of a non-static member function declared
3558   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3559   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3560   //      lvalue reference to a function lvalue and S2 binds an rvalue
3561   //      reference*.
3562   //
3563   // FIXME: Rvalue references. We're going rogue with the above edits,
3564   // because the semantics in the current C++0x working paper (N3225 at the
3565   // time of this writing) break the standard definition of std::forward
3566   // and std::reference_wrapper when dealing with references to functions.
3567   // Proposed wording changes submitted to CWG for consideration.
3568   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3569       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3570     return false;
3571 
3572   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3573           SCS2.IsLvalueReference) ||
3574          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3575           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3576 }
3577 
3578 /// CompareStandardConversionSequences - Compare two standard
3579 /// conversion sequences to determine whether one is better than the
3580 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3581 static ImplicitConversionSequence::CompareKind
3582 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3583                                    const StandardConversionSequence& SCS1,
3584                                    const StandardConversionSequence& SCS2)
3585 {
3586   // Standard conversion sequence S1 is a better conversion sequence
3587   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3588 
3589   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3590   //     sequences in the canonical form defined by 13.3.3.1.1,
3591   //     excluding any Lvalue Transformation; the identity conversion
3592   //     sequence is considered to be a subsequence of any
3593   //     non-identity conversion sequence) or, if not that,
3594   if (ImplicitConversionSequence::CompareKind CK
3595         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3596     return CK;
3597 
3598   //  -- the rank of S1 is better than the rank of S2 (by the rules
3599   //     defined below), or, if not that,
3600   ImplicitConversionRank Rank1 = SCS1.getRank();
3601   ImplicitConversionRank Rank2 = SCS2.getRank();
3602   if (Rank1 < Rank2)
3603     return ImplicitConversionSequence::Better;
3604   else if (Rank2 < Rank1)
3605     return ImplicitConversionSequence::Worse;
3606 
3607   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3608   // are indistinguishable unless one of the following rules
3609   // applies:
3610 
3611   //   A conversion that is not a conversion of a pointer, or
3612   //   pointer to member, to bool is better than another conversion
3613   //   that is such a conversion.
3614   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3615     return SCS2.isPointerConversionToBool()
3616              ? ImplicitConversionSequence::Better
3617              : ImplicitConversionSequence::Worse;
3618 
3619   // C++ [over.ics.rank]p4b2:
3620   //
3621   //   If class B is derived directly or indirectly from class A,
3622   //   conversion of B* to A* is better than conversion of B* to
3623   //   void*, and conversion of A* to void* is better than conversion
3624   //   of B* to void*.
3625   bool SCS1ConvertsToVoid
3626     = SCS1.isPointerConversionToVoidPointer(S.Context);
3627   bool SCS2ConvertsToVoid
3628     = SCS2.isPointerConversionToVoidPointer(S.Context);
3629   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3630     // Exactly one of the conversion sequences is a conversion to
3631     // a void pointer; it's the worse conversion.
3632     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3633                               : ImplicitConversionSequence::Worse;
3634   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3635     // Neither conversion sequence converts to a void pointer; compare
3636     // their derived-to-base conversions.
3637     if (ImplicitConversionSequence::CompareKind DerivedCK
3638           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3639       return DerivedCK;
3640   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3641              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3642     // Both conversion sequences are conversions to void
3643     // pointers. Compare the source types to determine if there's an
3644     // inheritance relationship in their sources.
3645     QualType FromType1 = SCS1.getFromType();
3646     QualType FromType2 = SCS2.getFromType();
3647 
3648     // Adjust the types we're converting from via the array-to-pointer
3649     // conversion, if we need to.
3650     if (SCS1.First == ICK_Array_To_Pointer)
3651       FromType1 = S.Context.getArrayDecayedType(FromType1);
3652     if (SCS2.First == ICK_Array_To_Pointer)
3653       FromType2 = S.Context.getArrayDecayedType(FromType2);
3654 
3655     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3656     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3657 
3658     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3659       return ImplicitConversionSequence::Better;
3660     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3661       return ImplicitConversionSequence::Worse;
3662 
3663     // Objective-C++: If one interface is more specific than the
3664     // other, it is the better one.
3665     const ObjCObjectPointerType* FromObjCPtr1
3666       = FromType1->getAs<ObjCObjectPointerType>();
3667     const ObjCObjectPointerType* FromObjCPtr2
3668       = FromType2->getAs<ObjCObjectPointerType>();
3669     if (FromObjCPtr1 && FromObjCPtr2) {
3670       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3671                                                           FromObjCPtr2);
3672       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3673                                                            FromObjCPtr1);
3674       if (AssignLeft != AssignRight) {
3675         return AssignLeft? ImplicitConversionSequence::Better
3676                          : ImplicitConversionSequence::Worse;
3677       }
3678     }
3679   }
3680 
3681   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3682   // bullet 3).
3683   if (ImplicitConversionSequence::CompareKind QualCK
3684         = CompareQualificationConversions(S, SCS1, SCS2))
3685     return QualCK;
3686 
3687   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3688     // Check for a better reference binding based on the kind of bindings.
3689     if (isBetterReferenceBindingKind(SCS1, SCS2))
3690       return ImplicitConversionSequence::Better;
3691     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3692       return ImplicitConversionSequence::Worse;
3693 
3694     // C++ [over.ics.rank]p3b4:
3695     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3696     //      which the references refer are the same type except for
3697     //      top-level cv-qualifiers, and the type to which the reference
3698     //      initialized by S2 refers is more cv-qualified than the type
3699     //      to which the reference initialized by S1 refers.
3700     QualType T1 = SCS1.getToType(2);
3701     QualType T2 = SCS2.getToType(2);
3702     T1 = S.Context.getCanonicalType(T1);
3703     T2 = S.Context.getCanonicalType(T2);
3704     Qualifiers T1Quals, T2Quals;
3705     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3706     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3707     if (UnqualT1 == UnqualT2) {
3708       // Objective-C++ ARC: If the references refer to objects with different
3709       // lifetimes, prefer bindings that don't change lifetime.
3710       if (SCS1.ObjCLifetimeConversionBinding !=
3711                                           SCS2.ObjCLifetimeConversionBinding) {
3712         return SCS1.ObjCLifetimeConversionBinding
3713                                            ? ImplicitConversionSequence::Worse
3714                                            : ImplicitConversionSequence::Better;
3715       }
3716 
3717       // If the type is an array type, promote the element qualifiers to the
3718       // type for comparison.
3719       if (isa<ArrayType>(T1) && T1Quals)
3720         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3721       if (isa<ArrayType>(T2) && T2Quals)
3722         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3723       if (T2.isMoreQualifiedThan(T1))
3724         return ImplicitConversionSequence::Better;
3725       else if (T1.isMoreQualifiedThan(T2))
3726         return ImplicitConversionSequence::Worse;
3727     }
3728   }
3729 
3730   // In Microsoft mode, prefer an integral conversion to a
3731   // floating-to-integral conversion if the integral conversion
3732   // is between types of the same size.
3733   // For example:
3734   // void f(float);
3735   // void f(int);
3736   // int main {
3737   //    long a;
3738   //    f(a);
3739   // }
3740   // Here, MSVC will call f(int) instead of generating a compile error
3741   // as clang will do in standard mode.
3742   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3743       SCS2.Second == ICK_Floating_Integral &&
3744       S.Context.getTypeSize(SCS1.getFromType()) ==
3745           S.Context.getTypeSize(SCS1.getToType(2)))
3746     return ImplicitConversionSequence::Better;
3747 
3748   return ImplicitConversionSequence::Indistinguishable;
3749 }
3750 
3751 /// CompareQualificationConversions - Compares two standard conversion
3752 /// sequences to determine whether they can be ranked based on their
3753 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3754 static ImplicitConversionSequence::CompareKind
3755 CompareQualificationConversions(Sema &S,
3756                                 const StandardConversionSequence& SCS1,
3757                                 const StandardConversionSequence& SCS2) {
3758   // C++ 13.3.3.2p3:
3759   //  -- S1 and S2 differ only in their qualification conversion and
3760   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3761   //     cv-qualification signature of type T1 is a proper subset of
3762   //     the cv-qualification signature of type T2, and S1 is not the
3763   //     deprecated string literal array-to-pointer conversion (4.2).
3764   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3765       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3766     return ImplicitConversionSequence::Indistinguishable;
3767 
3768   // FIXME: the example in the standard doesn't use a qualification
3769   // conversion (!)
3770   QualType T1 = SCS1.getToType(2);
3771   QualType T2 = SCS2.getToType(2);
3772   T1 = S.Context.getCanonicalType(T1);
3773   T2 = S.Context.getCanonicalType(T2);
3774   Qualifiers T1Quals, T2Quals;
3775   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3776   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3777 
3778   // If the types are the same, we won't learn anything by unwrapped
3779   // them.
3780   if (UnqualT1 == UnqualT2)
3781     return ImplicitConversionSequence::Indistinguishable;
3782 
3783   // If the type is an array type, promote the element qualifiers to the type
3784   // for comparison.
3785   if (isa<ArrayType>(T1) && T1Quals)
3786     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3787   if (isa<ArrayType>(T2) && T2Quals)
3788     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3789 
3790   ImplicitConversionSequence::CompareKind Result
3791     = ImplicitConversionSequence::Indistinguishable;
3792 
3793   // Objective-C++ ARC:
3794   //   Prefer qualification conversions not involving a change in lifetime
3795   //   to qualification conversions that do not change lifetime.
3796   if (SCS1.QualificationIncludesObjCLifetime !=
3797                                       SCS2.QualificationIncludesObjCLifetime) {
3798     Result = SCS1.QualificationIncludesObjCLifetime
3799                ? ImplicitConversionSequence::Worse
3800                : ImplicitConversionSequence::Better;
3801   }
3802 
3803   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3804     // Within each iteration of the loop, we check the qualifiers to
3805     // determine if this still looks like a qualification
3806     // conversion. Then, if all is well, we unwrap one more level of
3807     // pointers or pointers-to-members and do it all again
3808     // until there are no more pointers or pointers-to-members left
3809     // to unwrap. This essentially mimics what
3810     // IsQualificationConversion does, but here we're checking for a
3811     // strict subset of qualifiers.
3812     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3813       // The qualifiers are the same, so this doesn't tell us anything
3814       // about how the sequences rank.
3815       ;
3816     else if (T2.isMoreQualifiedThan(T1)) {
3817       // T1 has fewer qualifiers, so it could be the better sequence.
3818       if (Result == ImplicitConversionSequence::Worse)
3819         // Neither has qualifiers that are a subset of the other's
3820         // qualifiers.
3821         return ImplicitConversionSequence::Indistinguishable;
3822 
3823       Result = ImplicitConversionSequence::Better;
3824     } else if (T1.isMoreQualifiedThan(T2)) {
3825       // T2 has fewer qualifiers, so it could be the better sequence.
3826       if (Result == ImplicitConversionSequence::Better)
3827         // Neither has qualifiers that are a subset of the other's
3828         // qualifiers.
3829         return ImplicitConversionSequence::Indistinguishable;
3830 
3831       Result = ImplicitConversionSequence::Worse;
3832     } else {
3833       // Qualifiers are disjoint.
3834       return ImplicitConversionSequence::Indistinguishable;
3835     }
3836 
3837     // If the types after this point are equivalent, we're done.
3838     if (S.Context.hasSameUnqualifiedType(T1, T2))
3839       break;
3840   }
3841 
3842   // Check that the winning standard conversion sequence isn't using
3843   // the deprecated string literal array to pointer conversion.
3844   switch (Result) {
3845   case ImplicitConversionSequence::Better:
3846     if (SCS1.DeprecatedStringLiteralToCharPtr)
3847       Result = ImplicitConversionSequence::Indistinguishable;
3848     break;
3849 
3850   case ImplicitConversionSequence::Indistinguishable:
3851     break;
3852 
3853   case ImplicitConversionSequence::Worse:
3854     if (SCS2.DeprecatedStringLiteralToCharPtr)
3855       Result = ImplicitConversionSequence::Indistinguishable;
3856     break;
3857   }
3858 
3859   return Result;
3860 }
3861 
3862 /// CompareDerivedToBaseConversions - Compares two standard conversion
3863 /// sequences to determine whether they can be ranked based on their
3864 /// various kinds of derived-to-base conversions (C++
3865 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3866 /// conversions between Objective-C interface types.
3867 static ImplicitConversionSequence::CompareKind
3868 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3869                                 const StandardConversionSequence& SCS1,
3870                                 const StandardConversionSequence& SCS2) {
3871   QualType FromType1 = SCS1.getFromType();
3872   QualType ToType1 = SCS1.getToType(1);
3873   QualType FromType2 = SCS2.getFromType();
3874   QualType ToType2 = SCS2.getToType(1);
3875 
3876   // Adjust the types we're converting from via the array-to-pointer
3877   // conversion, if we need to.
3878   if (SCS1.First == ICK_Array_To_Pointer)
3879     FromType1 = S.Context.getArrayDecayedType(FromType1);
3880   if (SCS2.First == ICK_Array_To_Pointer)
3881     FromType2 = S.Context.getArrayDecayedType(FromType2);
3882 
3883   // Canonicalize all of the types.
3884   FromType1 = S.Context.getCanonicalType(FromType1);
3885   ToType1 = S.Context.getCanonicalType(ToType1);
3886   FromType2 = S.Context.getCanonicalType(FromType2);
3887   ToType2 = S.Context.getCanonicalType(ToType2);
3888 
3889   // C++ [over.ics.rank]p4b3:
3890   //
3891   //   If class B is derived directly or indirectly from class A and
3892   //   class C is derived directly or indirectly from B,
3893   //
3894   // Compare based on pointer conversions.
3895   if (SCS1.Second == ICK_Pointer_Conversion &&
3896       SCS2.Second == ICK_Pointer_Conversion &&
3897       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3898       FromType1->isPointerType() && FromType2->isPointerType() &&
3899       ToType1->isPointerType() && ToType2->isPointerType()) {
3900     QualType FromPointee1
3901       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3902     QualType ToPointee1
3903       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3904     QualType FromPointee2
3905       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3906     QualType ToPointee2
3907       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3908 
3909     //   -- conversion of C* to B* is better than conversion of C* to A*,
3910     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3911       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3912         return ImplicitConversionSequence::Better;
3913       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3914         return ImplicitConversionSequence::Worse;
3915     }
3916 
3917     //   -- conversion of B* to A* is better than conversion of C* to A*,
3918     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3919       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3920         return ImplicitConversionSequence::Better;
3921       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3922         return ImplicitConversionSequence::Worse;
3923     }
3924   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3925              SCS2.Second == ICK_Pointer_Conversion) {
3926     const ObjCObjectPointerType *FromPtr1
3927       = FromType1->getAs<ObjCObjectPointerType>();
3928     const ObjCObjectPointerType *FromPtr2
3929       = FromType2->getAs<ObjCObjectPointerType>();
3930     const ObjCObjectPointerType *ToPtr1
3931       = ToType1->getAs<ObjCObjectPointerType>();
3932     const ObjCObjectPointerType *ToPtr2
3933       = ToType2->getAs<ObjCObjectPointerType>();
3934 
3935     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3936       // Apply the same conversion ranking rules for Objective-C pointer types
3937       // that we do for C++ pointers to class types. However, we employ the
3938       // Objective-C pseudo-subtyping relationship used for assignment of
3939       // Objective-C pointer types.
3940       bool FromAssignLeft
3941         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3942       bool FromAssignRight
3943         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3944       bool ToAssignLeft
3945         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3946       bool ToAssignRight
3947         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3948 
3949       // A conversion to an a non-id object pointer type or qualified 'id'
3950       // type is better than a conversion to 'id'.
3951       if (ToPtr1->isObjCIdType() &&
3952           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3953         return ImplicitConversionSequence::Worse;
3954       if (ToPtr2->isObjCIdType() &&
3955           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3956         return ImplicitConversionSequence::Better;
3957 
3958       // A conversion to a non-id object pointer type is better than a
3959       // conversion to a qualified 'id' type
3960       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3961         return ImplicitConversionSequence::Worse;
3962       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3963         return ImplicitConversionSequence::Better;
3964 
3965       // A conversion to an a non-Class object pointer type or qualified 'Class'
3966       // type is better than a conversion to 'Class'.
3967       if (ToPtr1->isObjCClassType() &&
3968           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3969         return ImplicitConversionSequence::Worse;
3970       if (ToPtr2->isObjCClassType() &&
3971           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3972         return ImplicitConversionSequence::Better;
3973 
3974       // A conversion to a non-Class object pointer type is better than a
3975       // conversion to a qualified 'Class' type.
3976       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3977         return ImplicitConversionSequence::Worse;
3978       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3979         return ImplicitConversionSequence::Better;
3980 
3981       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3982       if (S.Context.hasSameType(FromType1, FromType2) &&
3983           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3984           (ToAssignLeft != ToAssignRight))
3985         return ToAssignLeft? ImplicitConversionSequence::Worse
3986                            : ImplicitConversionSequence::Better;
3987 
3988       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3989       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3990           (FromAssignLeft != FromAssignRight))
3991         return FromAssignLeft? ImplicitConversionSequence::Better
3992         : ImplicitConversionSequence::Worse;
3993     }
3994   }
3995 
3996   // Ranking of member-pointer types.
3997   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3998       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3999       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4000     const MemberPointerType * FromMemPointer1 =
4001                                         FromType1->getAs<MemberPointerType>();
4002     const MemberPointerType * ToMemPointer1 =
4003                                           ToType1->getAs<MemberPointerType>();
4004     const MemberPointerType * FromMemPointer2 =
4005                                           FromType2->getAs<MemberPointerType>();
4006     const MemberPointerType * ToMemPointer2 =
4007                                           ToType2->getAs<MemberPointerType>();
4008     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4009     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4010     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4011     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4012     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4013     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4014     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4015     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4016     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4017     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4018       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4019         return ImplicitConversionSequence::Worse;
4020       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4021         return ImplicitConversionSequence::Better;
4022     }
4023     // conversion of B::* to C::* is better than conversion of A::* to C::*
4024     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4025       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4026         return ImplicitConversionSequence::Better;
4027       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4028         return ImplicitConversionSequence::Worse;
4029     }
4030   }
4031 
4032   if (SCS1.Second == ICK_Derived_To_Base) {
4033     //   -- conversion of C to B is better than conversion of C to A,
4034     //   -- binding of an expression of type C to a reference of type
4035     //      B& is better than binding an expression of type C to a
4036     //      reference of type A&,
4037     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4038         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4039       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4040         return ImplicitConversionSequence::Better;
4041       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4042         return ImplicitConversionSequence::Worse;
4043     }
4044 
4045     //   -- conversion of B to A is better than conversion of C to A.
4046     //   -- binding of an expression of type B to a reference of type
4047     //      A& is better than binding an expression of type C to a
4048     //      reference of type A&,
4049     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4050         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4051       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4052         return ImplicitConversionSequence::Better;
4053       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4054         return ImplicitConversionSequence::Worse;
4055     }
4056   }
4057 
4058   return ImplicitConversionSequence::Indistinguishable;
4059 }
4060 
4061 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4062 /// C++ class.
4063 static bool isTypeValid(QualType T) {
4064   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4065     return !Record->isInvalidDecl();
4066 
4067   return true;
4068 }
4069 
4070 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4071 /// determine whether they are reference-related,
4072 /// reference-compatible, reference-compatible with added
4073 /// qualification, or incompatible, for use in C++ initialization by
4074 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4075 /// type, and the first type (T1) is the pointee type of the reference
4076 /// type being initialized.
4077 Sema::ReferenceCompareResult
4078 Sema::CompareReferenceRelationship(SourceLocation Loc,
4079                                    QualType OrigT1, QualType OrigT2,
4080                                    bool &DerivedToBase,
4081                                    bool &ObjCConversion,
4082                                    bool &ObjCLifetimeConversion) {
4083   assert(!OrigT1->isReferenceType() &&
4084     "T1 must be the pointee type of the reference type");
4085   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4086 
4087   QualType T1 = Context.getCanonicalType(OrigT1);
4088   QualType T2 = Context.getCanonicalType(OrigT2);
4089   Qualifiers T1Quals, T2Quals;
4090   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4091   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4092 
4093   // C++ [dcl.init.ref]p4:
4094   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4095   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4096   //   T1 is a base class of T2.
4097   DerivedToBase = false;
4098   ObjCConversion = false;
4099   ObjCLifetimeConversion = false;
4100   if (UnqualT1 == UnqualT2) {
4101     // Nothing to do.
4102   } else if (isCompleteType(Loc, OrigT2) &&
4103              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4104              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4105     DerivedToBase = true;
4106   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4107            UnqualT2->isObjCObjectOrInterfaceType() &&
4108            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4109     ObjCConversion = true;
4110   else
4111     return Ref_Incompatible;
4112 
4113   // At this point, we know that T1 and T2 are reference-related (at
4114   // least).
4115 
4116   // If the type is an array type, promote the element qualifiers to the type
4117   // for comparison.
4118   if (isa<ArrayType>(T1) && T1Quals)
4119     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4120   if (isa<ArrayType>(T2) && T2Quals)
4121     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4122 
4123   // C++ [dcl.init.ref]p4:
4124   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4125   //   reference-related to T2 and cv1 is the same cv-qualification
4126   //   as, or greater cv-qualification than, cv2. For purposes of
4127   //   overload resolution, cases for which cv1 is greater
4128   //   cv-qualification than cv2 are identified as
4129   //   reference-compatible with added qualification (see 13.3.3.2).
4130   //
4131   // Note that we also require equivalence of Objective-C GC and address-space
4132   // qualifiers when performing these computations, so that e.g., an int in
4133   // address space 1 is not reference-compatible with an int in address
4134   // space 2.
4135   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4136       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4137     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4138       ObjCLifetimeConversion = true;
4139 
4140     T1Quals.removeObjCLifetime();
4141     T2Quals.removeObjCLifetime();
4142   }
4143 
4144   // MS compiler ignores __unaligned qualifier for references; do the same.
4145   T1Quals.removeUnaligned();
4146   T2Quals.removeUnaligned();
4147 
4148   if (T1Quals == T2Quals)
4149     return Ref_Compatible;
4150   else if (T1Quals.compatiblyIncludes(T2Quals))
4151     return Ref_Compatible_With_Added_Qualification;
4152   else
4153     return Ref_Related;
4154 }
4155 
4156 /// \brief Look for a user-defined conversion to an value reference-compatible
4157 ///        with DeclType. Return true if something definite is found.
4158 static bool
4159 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4160                          QualType DeclType, SourceLocation DeclLoc,
4161                          Expr *Init, QualType T2, bool AllowRvalues,
4162                          bool AllowExplicit) {
4163   assert(T2->isRecordType() && "Can only find conversions of record types.");
4164   CXXRecordDecl *T2RecordDecl
4165     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4166 
4167   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4168   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4169   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4170     NamedDecl *D = *I;
4171     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4172     if (isa<UsingShadowDecl>(D))
4173       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4174 
4175     FunctionTemplateDecl *ConvTemplate
4176       = dyn_cast<FunctionTemplateDecl>(D);
4177     CXXConversionDecl *Conv;
4178     if (ConvTemplate)
4179       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4180     else
4181       Conv = cast<CXXConversionDecl>(D);
4182 
4183     // If this is an explicit conversion, and we're not allowed to consider
4184     // explicit conversions, skip it.
4185     if (!AllowExplicit && Conv->isExplicit())
4186       continue;
4187 
4188     if (AllowRvalues) {
4189       bool DerivedToBase = false;
4190       bool ObjCConversion = false;
4191       bool ObjCLifetimeConversion = false;
4192 
4193       // If we are initializing an rvalue reference, don't permit conversion
4194       // functions that return lvalues.
4195       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4196         const ReferenceType *RefType
4197           = Conv->getConversionType()->getAs<LValueReferenceType>();
4198         if (RefType && !RefType->getPointeeType()->isFunctionType())
4199           continue;
4200       }
4201 
4202       if (!ConvTemplate &&
4203           S.CompareReferenceRelationship(
4204             DeclLoc,
4205             Conv->getConversionType().getNonReferenceType()
4206               .getUnqualifiedType(),
4207             DeclType.getNonReferenceType().getUnqualifiedType(),
4208             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4209           Sema::Ref_Incompatible)
4210         continue;
4211     } else {
4212       // If the conversion function doesn't return a reference type,
4213       // it can't be considered for this conversion. An rvalue reference
4214       // is only acceptable if its referencee is a function type.
4215 
4216       const ReferenceType *RefType =
4217         Conv->getConversionType()->getAs<ReferenceType>();
4218       if (!RefType ||
4219           (!RefType->isLValueReferenceType() &&
4220            !RefType->getPointeeType()->isFunctionType()))
4221         continue;
4222     }
4223 
4224     if (ConvTemplate)
4225       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4226                                        Init, DeclType, CandidateSet,
4227                                        /*AllowObjCConversionOnExplicit=*/false);
4228     else
4229       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4230                                DeclType, CandidateSet,
4231                                /*AllowObjCConversionOnExplicit=*/false);
4232   }
4233 
4234   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4235 
4236   OverloadCandidateSet::iterator Best;
4237   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4238   case OR_Success:
4239     // C++ [over.ics.ref]p1:
4240     //
4241     //   [...] If the parameter binds directly to the result of
4242     //   applying a conversion function to the argument
4243     //   expression, the implicit conversion sequence is a
4244     //   user-defined conversion sequence (13.3.3.1.2), with the
4245     //   second standard conversion sequence either an identity
4246     //   conversion or, if the conversion function returns an
4247     //   entity of a type that is a derived class of the parameter
4248     //   type, a derived-to-base Conversion.
4249     if (!Best->FinalConversion.DirectBinding)
4250       return false;
4251 
4252     ICS.setUserDefined();
4253     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4254     ICS.UserDefined.After = Best->FinalConversion;
4255     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4256     ICS.UserDefined.ConversionFunction = Best->Function;
4257     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4258     ICS.UserDefined.EllipsisConversion = false;
4259     assert(ICS.UserDefined.After.ReferenceBinding &&
4260            ICS.UserDefined.After.DirectBinding &&
4261            "Expected a direct reference binding!");
4262     return true;
4263 
4264   case OR_Ambiguous:
4265     ICS.setAmbiguous();
4266     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4267          Cand != CandidateSet.end(); ++Cand)
4268       if (Cand->Viable)
4269         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4270     return true;
4271 
4272   case OR_No_Viable_Function:
4273   case OR_Deleted:
4274     // There was no suitable conversion, or we found a deleted
4275     // conversion; continue with other checks.
4276     return false;
4277   }
4278 
4279   llvm_unreachable("Invalid OverloadResult!");
4280 }
4281 
4282 /// \brief Compute an implicit conversion sequence for reference
4283 /// initialization.
4284 static ImplicitConversionSequence
4285 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4286                  SourceLocation DeclLoc,
4287                  bool SuppressUserConversions,
4288                  bool AllowExplicit) {
4289   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4290 
4291   // Most paths end in a failed conversion.
4292   ImplicitConversionSequence ICS;
4293   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4294 
4295   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4296   QualType T2 = Init->getType();
4297 
4298   // If the initializer is the address of an overloaded function, try
4299   // to resolve the overloaded function. If all goes well, T2 is the
4300   // type of the resulting function.
4301   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4302     DeclAccessPair Found;
4303     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4304                                                                 false, Found))
4305       T2 = Fn->getType();
4306   }
4307 
4308   // Compute some basic properties of the types and the initializer.
4309   bool isRValRef = DeclType->isRValueReferenceType();
4310   bool DerivedToBase = false;
4311   bool ObjCConversion = false;
4312   bool ObjCLifetimeConversion = false;
4313   Expr::Classification InitCategory = Init->Classify(S.Context);
4314   Sema::ReferenceCompareResult RefRelationship
4315     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4316                                      ObjCConversion, ObjCLifetimeConversion);
4317 
4318 
4319   // C++0x [dcl.init.ref]p5:
4320   //   A reference to type "cv1 T1" is initialized by an expression
4321   //   of type "cv2 T2" as follows:
4322 
4323   //     -- If reference is an lvalue reference and the initializer expression
4324   if (!isRValRef) {
4325     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4326     //        reference-compatible with "cv2 T2," or
4327     //
4328     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4329     if (InitCategory.isLValue() &&
4330         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4331       // C++ [over.ics.ref]p1:
4332       //   When a parameter of reference type binds directly (8.5.3)
4333       //   to an argument expression, the implicit conversion sequence
4334       //   is the identity conversion, unless the argument expression
4335       //   has a type that is a derived class of the parameter type,
4336       //   in which case the implicit conversion sequence is a
4337       //   derived-to-base Conversion (13.3.3.1).
4338       ICS.setStandard();
4339       ICS.Standard.First = ICK_Identity;
4340       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4341                          : ObjCConversion? ICK_Compatible_Conversion
4342                          : ICK_Identity;
4343       ICS.Standard.Third = ICK_Identity;
4344       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4345       ICS.Standard.setToType(0, T2);
4346       ICS.Standard.setToType(1, T1);
4347       ICS.Standard.setToType(2, T1);
4348       ICS.Standard.ReferenceBinding = true;
4349       ICS.Standard.DirectBinding = true;
4350       ICS.Standard.IsLvalueReference = !isRValRef;
4351       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4352       ICS.Standard.BindsToRvalue = false;
4353       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4354       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4355       ICS.Standard.CopyConstructor = nullptr;
4356       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4357 
4358       // Nothing more to do: the inaccessibility/ambiguity check for
4359       // derived-to-base conversions is suppressed when we're
4360       // computing the implicit conversion sequence (C++
4361       // [over.best.ics]p2).
4362       return ICS;
4363     }
4364 
4365     //       -- has a class type (i.e., T2 is a class type), where T1 is
4366     //          not reference-related to T2, and can be implicitly
4367     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4368     //          is reference-compatible with "cv3 T3" 92) (this
4369     //          conversion is selected by enumerating the applicable
4370     //          conversion functions (13.3.1.6) and choosing the best
4371     //          one through overload resolution (13.3)),
4372     if (!SuppressUserConversions && T2->isRecordType() &&
4373         S.isCompleteType(DeclLoc, T2) &&
4374         RefRelationship == Sema::Ref_Incompatible) {
4375       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4376                                    Init, T2, /*AllowRvalues=*/false,
4377                                    AllowExplicit))
4378         return ICS;
4379     }
4380   }
4381 
4382   //     -- Otherwise, the reference shall be an lvalue reference to a
4383   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4384   //        shall be an rvalue reference.
4385   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4386     return ICS;
4387 
4388   //       -- If the initializer expression
4389   //
4390   //            -- is an xvalue, class prvalue, array prvalue or function
4391   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4392   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4393       (InitCategory.isXValue() ||
4394       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4395       (InitCategory.isLValue() && T2->isFunctionType()))) {
4396     ICS.setStandard();
4397     ICS.Standard.First = ICK_Identity;
4398     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4399                       : ObjCConversion? ICK_Compatible_Conversion
4400                       : ICK_Identity;
4401     ICS.Standard.Third = ICK_Identity;
4402     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4403     ICS.Standard.setToType(0, T2);
4404     ICS.Standard.setToType(1, T1);
4405     ICS.Standard.setToType(2, T1);
4406     ICS.Standard.ReferenceBinding = true;
4407     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4408     // binding unless we're binding to a class prvalue.
4409     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4410     // allow the use of rvalue references in C++98/03 for the benefit of
4411     // standard library implementors; therefore, we need the xvalue check here.
4412     ICS.Standard.DirectBinding =
4413       S.getLangOpts().CPlusPlus11 ||
4414       !(InitCategory.isPRValue() || T2->isRecordType());
4415     ICS.Standard.IsLvalueReference = !isRValRef;
4416     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4417     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4418     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4419     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4420     ICS.Standard.CopyConstructor = nullptr;
4421     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4422     return ICS;
4423   }
4424 
4425   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4426   //               reference-related to T2, and can be implicitly converted to
4427   //               an xvalue, class prvalue, or function lvalue of type
4428   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4429   //               "cv3 T3",
4430   //
4431   //          then the reference is bound to the value of the initializer
4432   //          expression in the first case and to the result of the conversion
4433   //          in the second case (or, in either case, to an appropriate base
4434   //          class subobject).
4435   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4436       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4437       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4438                                Init, T2, /*AllowRvalues=*/true,
4439                                AllowExplicit)) {
4440     // In the second case, if the reference is an rvalue reference
4441     // and the second standard conversion sequence of the
4442     // user-defined conversion sequence includes an lvalue-to-rvalue
4443     // conversion, the program is ill-formed.
4444     if (ICS.isUserDefined() && isRValRef &&
4445         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4446       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4447 
4448     return ICS;
4449   }
4450 
4451   // A temporary of function type cannot be created; don't even try.
4452   if (T1->isFunctionType())
4453     return ICS;
4454 
4455   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4456   //          initialized from the initializer expression using the
4457   //          rules for a non-reference copy initialization (8.5). The
4458   //          reference is then bound to the temporary. If T1 is
4459   //          reference-related to T2, cv1 must be the same
4460   //          cv-qualification as, or greater cv-qualification than,
4461   //          cv2; otherwise, the program is ill-formed.
4462   if (RefRelationship == Sema::Ref_Related) {
4463     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4464     // we would be reference-compatible or reference-compatible with
4465     // added qualification. But that wasn't the case, so the reference
4466     // initialization fails.
4467     //
4468     // Note that we only want to check address spaces and cvr-qualifiers here.
4469     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4470     Qualifiers T1Quals = T1.getQualifiers();
4471     Qualifiers T2Quals = T2.getQualifiers();
4472     T1Quals.removeObjCGCAttr();
4473     T1Quals.removeObjCLifetime();
4474     T2Quals.removeObjCGCAttr();
4475     T2Quals.removeObjCLifetime();
4476     // MS compiler ignores __unaligned qualifier for references; do the same.
4477     T1Quals.removeUnaligned();
4478     T2Quals.removeUnaligned();
4479     if (!T1Quals.compatiblyIncludes(T2Quals))
4480       return ICS;
4481   }
4482 
4483   // If at least one of the types is a class type, the types are not
4484   // related, and we aren't allowed any user conversions, the
4485   // reference binding fails. This case is important for breaking
4486   // recursion, since TryImplicitConversion below will attempt to
4487   // create a temporary through the use of a copy constructor.
4488   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4489       (T1->isRecordType() || T2->isRecordType()))
4490     return ICS;
4491 
4492   // If T1 is reference-related to T2 and the reference is an rvalue
4493   // reference, the initializer expression shall not be an lvalue.
4494   if (RefRelationship >= Sema::Ref_Related &&
4495       isRValRef && Init->Classify(S.Context).isLValue())
4496     return ICS;
4497 
4498   // C++ [over.ics.ref]p2:
4499   //   When a parameter of reference type is not bound directly to
4500   //   an argument expression, the conversion sequence is the one
4501   //   required to convert the argument expression to the
4502   //   underlying type of the reference according to
4503   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4504   //   to copy-initializing a temporary of the underlying type with
4505   //   the argument expression. Any difference in top-level
4506   //   cv-qualification is subsumed by the initialization itself
4507   //   and does not constitute a conversion.
4508   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4509                               /*AllowExplicit=*/false,
4510                               /*InOverloadResolution=*/false,
4511                               /*CStyle=*/false,
4512                               /*AllowObjCWritebackConversion=*/false,
4513                               /*AllowObjCConversionOnExplicit=*/false);
4514 
4515   // Of course, that's still a reference binding.
4516   if (ICS.isStandard()) {
4517     ICS.Standard.ReferenceBinding = true;
4518     ICS.Standard.IsLvalueReference = !isRValRef;
4519     ICS.Standard.BindsToFunctionLvalue = false;
4520     ICS.Standard.BindsToRvalue = true;
4521     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4522     ICS.Standard.ObjCLifetimeConversionBinding = false;
4523   } else if (ICS.isUserDefined()) {
4524     const ReferenceType *LValRefType =
4525         ICS.UserDefined.ConversionFunction->getReturnType()
4526             ->getAs<LValueReferenceType>();
4527 
4528     // C++ [over.ics.ref]p3:
4529     //   Except for an implicit object parameter, for which see 13.3.1, a
4530     //   standard conversion sequence cannot be formed if it requires [...]
4531     //   binding an rvalue reference to an lvalue other than a function
4532     //   lvalue.
4533     // Note that the function case is not possible here.
4534     if (DeclType->isRValueReferenceType() && LValRefType) {
4535       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4536       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4537       // reference to an rvalue!
4538       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4539       return ICS;
4540     }
4541 
4542     ICS.UserDefined.After.ReferenceBinding = true;
4543     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4544     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4545     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4546     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4547     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4548   }
4549 
4550   return ICS;
4551 }
4552 
4553 static ImplicitConversionSequence
4554 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4555                       bool SuppressUserConversions,
4556                       bool InOverloadResolution,
4557                       bool AllowObjCWritebackConversion,
4558                       bool AllowExplicit = false);
4559 
4560 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4561 /// initializer list From.
4562 static ImplicitConversionSequence
4563 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4564                   bool SuppressUserConversions,
4565                   bool InOverloadResolution,
4566                   bool AllowObjCWritebackConversion) {
4567   // C++11 [over.ics.list]p1:
4568   //   When an argument is an initializer list, it is not an expression and
4569   //   special rules apply for converting it to a parameter type.
4570 
4571   ImplicitConversionSequence Result;
4572   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4573 
4574   // We need a complete type for what follows. Incomplete types can never be
4575   // initialized from init lists.
4576   if (!S.isCompleteType(From->getLocStart(), ToType))
4577     return Result;
4578 
4579   // Per DR1467:
4580   //   If the parameter type is a class X and the initializer list has a single
4581   //   element of type cv U, where U is X or a class derived from X, the
4582   //   implicit conversion sequence is the one required to convert the element
4583   //   to the parameter type.
4584   //
4585   //   Otherwise, if the parameter type is a character array [... ]
4586   //   and the initializer list has a single element that is an
4587   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4588   //   implicit conversion sequence is the identity conversion.
4589   if (From->getNumInits() == 1) {
4590     if (ToType->isRecordType()) {
4591       QualType InitType = From->getInit(0)->getType();
4592       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4593           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4594         return TryCopyInitialization(S, From->getInit(0), ToType,
4595                                      SuppressUserConversions,
4596                                      InOverloadResolution,
4597                                      AllowObjCWritebackConversion);
4598     }
4599     // FIXME: Check the other conditions here: array of character type,
4600     // initializer is a string literal.
4601     if (ToType->isArrayType()) {
4602       InitializedEntity Entity =
4603         InitializedEntity::InitializeParameter(S.Context, ToType,
4604                                                /*Consumed=*/false);
4605       if (S.CanPerformCopyInitialization(Entity, From)) {
4606         Result.setStandard();
4607         Result.Standard.setAsIdentityConversion();
4608         Result.Standard.setFromType(ToType);
4609         Result.Standard.setAllToTypes(ToType);
4610         return Result;
4611       }
4612     }
4613   }
4614 
4615   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4616   // C++11 [over.ics.list]p2:
4617   //   If the parameter type is std::initializer_list<X> or "array of X" and
4618   //   all the elements can be implicitly converted to X, the implicit
4619   //   conversion sequence is the worst conversion necessary to convert an
4620   //   element of the list to X.
4621   //
4622   // C++14 [over.ics.list]p3:
4623   //   Otherwise, if the parameter type is "array of N X", if the initializer
4624   //   list has exactly N elements or if it has fewer than N elements and X is
4625   //   default-constructible, and if all the elements of the initializer list
4626   //   can be implicitly converted to X, the implicit conversion sequence is
4627   //   the worst conversion necessary to convert an element of the list to X.
4628   //
4629   // FIXME: We're missing a lot of these checks.
4630   bool toStdInitializerList = false;
4631   QualType X;
4632   if (ToType->isArrayType())
4633     X = S.Context.getAsArrayType(ToType)->getElementType();
4634   else
4635     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4636   if (!X.isNull()) {
4637     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4638       Expr *Init = From->getInit(i);
4639       ImplicitConversionSequence ICS =
4640           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4641                                 InOverloadResolution,
4642                                 AllowObjCWritebackConversion);
4643       // If a single element isn't convertible, fail.
4644       if (ICS.isBad()) {
4645         Result = ICS;
4646         break;
4647       }
4648       // Otherwise, look for the worst conversion.
4649       if (Result.isBad() ||
4650           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4651                                              Result) ==
4652               ImplicitConversionSequence::Worse)
4653         Result = ICS;
4654     }
4655 
4656     // For an empty list, we won't have computed any conversion sequence.
4657     // Introduce the identity conversion sequence.
4658     if (From->getNumInits() == 0) {
4659       Result.setStandard();
4660       Result.Standard.setAsIdentityConversion();
4661       Result.Standard.setFromType(ToType);
4662       Result.Standard.setAllToTypes(ToType);
4663     }
4664 
4665     Result.setStdInitializerListElement(toStdInitializerList);
4666     return Result;
4667   }
4668 
4669   // C++14 [over.ics.list]p4:
4670   // C++11 [over.ics.list]p3:
4671   //   Otherwise, if the parameter is a non-aggregate class X and overload
4672   //   resolution chooses a single best constructor [...] the implicit
4673   //   conversion sequence is a user-defined conversion sequence. If multiple
4674   //   constructors are viable but none is better than the others, the
4675   //   implicit conversion sequence is a user-defined conversion sequence.
4676   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4677     // This function can deal with initializer lists.
4678     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4679                                     /*AllowExplicit=*/false,
4680                                     InOverloadResolution, /*CStyle=*/false,
4681                                     AllowObjCWritebackConversion,
4682                                     /*AllowObjCConversionOnExplicit=*/false);
4683   }
4684 
4685   // C++14 [over.ics.list]p5:
4686   // C++11 [over.ics.list]p4:
4687   //   Otherwise, if the parameter has an aggregate type which can be
4688   //   initialized from the initializer list [...] the implicit conversion
4689   //   sequence is a user-defined conversion sequence.
4690   if (ToType->isAggregateType()) {
4691     // Type is an aggregate, argument is an init list. At this point it comes
4692     // down to checking whether the initialization works.
4693     // FIXME: Find out whether this parameter is consumed or not.
4694     InitializedEntity Entity =
4695         InitializedEntity::InitializeParameter(S.Context, ToType,
4696                                                /*Consumed=*/false);
4697     if (S.CanPerformCopyInitialization(Entity, From)) {
4698       Result.setUserDefined();
4699       Result.UserDefined.Before.setAsIdentityConversion();
4700       // Initializer lists don't have a type.
4701       Result.UserDefined.Before.setFromType(QualType());
4702       Result.UserDefined.Before.setAllToTypes(QualType());
4703 
4704       Result.UserDefined.After.setAsIdentityConversion();
4705       Result.UserDefined.After.setFromType(ToType);
4706       Result.UserDefined.After.setAllToTypes(ToType);
4707       Result.UserDefined.ConversionFunction = nullptr;
4708     }
4709     return Result;
4710   }
4711 
4712   // C++14 [over.ics.list]p6:
4713   // C++11 [over.ics.list]p5:
4714   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4715   if (ToType->isReferenceType()) {
4716     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4717     // mention initializer lists in any way. So we go by what list-
4718     // initialization would do and try to extrapolate from that.
4719 
4720     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4721 
4722     // If the initializer list has a single element that is reference-related
4723     // to the parameter type, we initialize the reference from that.
4724     if (From->getNumInits() == 1) {
4725       Expr *Init = From->getInit(0);
4726 
4727       QualType T2 = Init->getType();
4728 
4729       // If the initializer is the address of an overloaded function, try
4730       // to resolve the overloaded function. If all goes well, T2 is the
4731       // type of the resulting function.
4732       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4733         DeclAccessPair Found;
4734         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4735                                    Init, ToType, false, Found))
4736           T2 = Fn->getType();
4737       }
4738 
4739       // Compute some basic properties of the types and the initializer.
4740       bool dummy1 = false;
4741       bool dummy2 = false;
4742       bool dummy3 = false;
4743       Sema::ReferenceCompareResult RefRelationship
4744         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4745                                          dummy2, dummy3);
4746 
4747       if (RefRelationship >= Sema::Ref_Related) {
4748         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4749                                 SuppressUserConversions,
4750                                 /*AllowExplicit=*/false);
4751       }
4752     }
4753 
4754     // Otherwise, we bind the reference to a temporary created from the
4755     // initializer list.
4756     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4757                                InOverloadResolution,
4758                                AllowObjCWritebackConversion);
4759     if (Result.isFailure())
4760       return Result;
4761     assert(!Result.isEllipsis() &&
4762            "Sub-initialization cannot result in ellipsis conversion.");
4763 
4764     // Can we even bind to a temporary?
4765     if (ToType->isRValueReferenceType() ||
4766         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4767       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4768                                             Result.UserDefined.After;
4769       SCS.ReferenceBinding = true;
4770       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4771       SCS.BindsToRvalue = true;
4772       SCS.BindsToFunctionLvalue = false;
4773       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4774       SCS.ObjCLifetimeConversionBinding = false;
4775     } else
4776       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4777                     From, ToType);
4778     return Result;
4779   }
4780 
4781   // C++14 [over.ics.list]p7:
4782   // C++11 [over.ics.list]p6:
4783   //   Otherwise, if the parameter type is not a class:
4784   if (!ToType->isRecordType()) {
4785     //    - if the initializer list has one element that is not itself an
4786     //      initializer list, the implicit conversion sequence is the one
4787     //      required to convert the element to the parameter type.
4788     unsigned NumInits = From->getNumInits();
4789     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4790       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4791                                      SuppressUserConversions,
4792                                      InOverloadResolution,
4793                                      AllowObjCWritebackConversion);
4794     //    - if the initializer list has no elements, the implicit conversion
4795     //      sequence is the identity conversion.
4796     else if (NumInits == 0) {
4797       Result.setStandard();
4798       Result.Standard.setAsIdentityConversion();
4799       Result.Standard.setFromType(ToType);
4800       Result.Standard.setAllToTypes(ToType);
4801     }
4802     return Result;
4803   }
4804 
4805   // C++14 [over.ics.list]p8:
4806   // C++11 [over.ics.list]p7:
4807   //   In all cases other than those enumerated above, no conversion is possible
4808   return Result;
4809 }
4810 
4811 /// TryCopyInitialization - Try to copy-initialize a value of type
4812 /// ToType from the expression From. Return the implicit conversion
4813 /// sequence required to pass this argument, which may be a bad
4814 /// conversion sequence (meaning that the argument cannot be passed to
4815 /// a parameter of this type). If @p SuppressUserConversions, then we
4816 /// do not permit any user-defined conversion sequences.
4817 static ImplicitConversionSequence
4818 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4819                       bool SuppressUserConversions,
4820                       bool InOverloadResolution,
4821                       bool AllowObjCWritebackConversion,
4822                       bool AllowExplicit) {
4823   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4824     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4825                              InOverloadResolution,AllowObjCWritebackConversion);
4826 
4827   if (ToType->isReferenceType())
4828     return TryReferenceInit(S, From, ToType,
4829                             /*FIXME:*/From->getLocStart(),
4830                             SuppressUserConversions,
4831                             AllowExplicit);
4832 
4833   return TryImplicitConversion(S, From, ToType,
4834                                SuppressUserConversions,
4835                                /*AllowExplicit=*/false,
4836                                InOverloadResolution,
4837                                /*CStyle=*/false,
4838                                AllowObjCWritebackConversion,
4839                                /*AllowObjCConversionOnExplicit=*/false);
4840 }
4841 
4842 static bool TryCopyInitialization(const CanQualType FromQTy,
4843                                   const CanQualType ToQTy,
4844                                   Sema &S,
4845                                   SourceLocation Loc,
4846                                   ExprValueKind FromVK) {
4847   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4848   ImplicitConversionSequence ICS =
4849     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4850 
4851   return !ICS.isBad();
4852 }
4853 
4854 /// TryObjectArgumentInitialization - Try to initialize the object
4855 /// parameter of the given member function (@c Method) from the
4856 /// expression @p From.
4857 static ImplicitConversionSequence
4858 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4859                                 Expr::Classification FromClassification,
4860                                 CXXMethodDecl *Method,
4861                                 CXXRecordDecl *ActingContext) {
4862   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4863   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4864   //                 const volatile object.
4865   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4866     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4867   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4868 
4869   // Set up the conversion sequence as a "bad" conversion, to allow us
4870   // to exit early.
4871   ImplicitConversionSequence ICS;
4872 
4873   // We need to have an object of class type.
4874   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4875     FromType = PT->getPointeeType();
4876 
4877     // When we had a pointer, it's implicitly dereferenced, so we
4878     // better have an lvalue.
4879     assert(FromClassification.isLValue());
4880   }
4881 
4882   assert(FromType->isRecordType());
4883 
4884   // C++0x [over.match.funcs]p4:
4885   //   For non-static member functions, the type of the implicit object
4886   //   parameter is
4887   //
4888   //     - "lvalue reference to cv X" for functions declared without a
4889   //        ref-qualifier or with the & ref-qualifier
4890   //     - "rvalue reference to cv X" for functions declared with the &&
4891   //        ref-qualifier
4892   //
4893   // where X is the class of which the function is a member and cv is the
4894   // cv-qualification on the member function declaration.
4895   //
4896   // However, when finding an implicit conversion sequence for the argument, we
4897   // are not allowed to create temporaries or perform user-defined conversions
4898   // (C++ [over.match.funcs]p5). We perform a simplified version of
4899   // reference binding here, that allows class rvalues to bind to
4900   // non-constant references.
4901 
4902   // First check the qualifiers.
4903   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4904   if (ImplicitParamType.getCVRQualifiers()
4905                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4906       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4907     ICS.setBad(BadConversionSequence::bad_qualifiers,
4908                FromType, ImplicitParamType);
4909     return ICS;
4910   }
4911 
4912   // Check that we have either the same type or a derived type. It
4913   // affects the conversion rank.
4914   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4915   ImplicitConversionKind SecondKind;
4916   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4917     SecondKind = ICK_Identity;
4918   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
4919     SecondKind = ICK_Derived_To_Base;
4920   else {
4921     ICS.setBad(BadConversionSequence::unrelated_class,
4922                FromType, ImplicitParamType);
4923     return ICS;
4924   }
4925 
4926   // Check the ref-qualifier.
4927   switch (Method->getRefQualifier()) {
4928   case RQ_None:
4929     // Do nothing; we don't care about lvalueness or rvalueness.
4930     break;
4931 
4932   case RQ_LValue:
4933     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4934       // non-const lvalue reference cannot bind to an rvalue
4935       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4936                  ImplicitParamType);
4937       return ICS;
4938     }
4939     break;
4940 
4941   case RQ_RValue:
4942     if (!FromClassification.isRValue()) {
4943       // rvalue reference cannot bind to an lvalue
4944       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4945                  ImplicitParamType);
4946       return ICS;
4947     }
4948     break;
4949   }
4950 
4951   // Success. Mark this as a reference binding.
4952   ICS.setStandard();
4953   ICS.Standard.setAsIdentityConversion();
4954   ICS.Standard.Second = SecondKind;
4955   ICS.Standard.setFromType(FromType);
4956   ICS.Standard.setAllToTypes(ImplicitParamType);
4957   ICS.Standard.ReferenceBinding = true;
4958   ICS.Standard.DirectBinding = true;
4959   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4960   ICS.Standard.BindsToFunctionLvalue = false;
4961   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4962   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4963     = (Method->getRefQualifier() == RQ_None);
4964   return ICS;
4965 }
4966 
4967 /// PerformObjectArgumentInitialization - Perform initialization of
4968 /// the implicit object parameter for the given Method with the given
4969 /// expression.
4970 ExprResult
4971 Sema::PerformObjectArgumentInitialization(Expr *From,
4972                                           NestedNameSpecifier *Qualifier,
4973                                           NamedDecl *FoundDecl,
4974                                           CXXMethodDecl *Method) {
4975   QualType FromRecordType, DestType;
4976   QualType ImplicitParamRecordType  =
4977     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4978 
4979   Expr::Classification FromClassification;
4980   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4981     FromRecordType = PT->getPointeeType();
4982     DestType = Method->getThisType(Context);
4983     FromClassification = Expr::Classification::makeSimpleLValue();
4984   } else {
4985     FromRecordType = From->getType();
4986     DestType = ImplicitParamRecordType;
4987     FromClassification = From->Classify(Context);
4988   }
4989 
4990   // Note that we always use the true parent context when performing
4991   // the actual argument initialization.
4992   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4993       *this, From->getLocStart(), From->getType(), FromClassification, Method,
4994       Method->getParent());
4995   if (ICS.isBad()) {
4996     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4997       Qualifiers FromQs = FromRecordType.getQualifiers();
4998       Qualifiers ToQs = DestType.getQualifiers();
4999       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5000       if (CVR) {
5001         Diag(From->getLocStart(),
5002              diag::err_member_function_call_bad_cvr)
5003           << Method->getDeclName() << FromRecordType << (CVR - 1)
5004           << From->getSourceRange();
5005         Diag(Method->getLocation(), diag::note_previous_decl)
5006           << Method->getDeclName();
5007         return ExprError();
5008       }
5009     }
5010 
5011     return Diag(From->getLocStart(),
5012                 diag::err_implicit_object_parameter_init)
5013        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5014   }
5015 
5016   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5017     ExprResult FromRes =
5018       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5019     if (FromRes.isInvalid())
5020       return ExprError();
5021     From = FromRes.get();
5022   }
5023 
5024   if (!Context.hasSameType(From->getType(), DestType))
5025     From = ImpCastExprToType(From, DestType, CK_NoOp,
5026                              From->getValueKind()).get();
5027   return From;
5028 }
5029 
5030 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5031 /// expression From to bool (C++0x [conv]p3).
5032 static ImplicitConversionSequence
5033 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5034   return TryImplicitConversion(S, From, S.Context.BoolTy,
5035                                /*SuppressUserConversions=*/false,
5036                                /*AllowExplicit=*/true,
5037                                /*InOverloadResolution=*/false,
5038                                /*CStyle=*/false,
5039                                /*AllowObjCWritebackConversion=*/false,
5040                                /*AllowObjCConversionOnExplicit=*/false);
5041 }
5042 
5043 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5044 /// of the expression From to bool (C++0x [conv]p3).
5045 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5046   if (checkPlaceholderForOverload(*this, From))
5047     return ExprError();
5048 
5049   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5050   if (!ICS.isBad())
5051     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5052 
5053   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5054     return Diag(From->getLocStart(),
5055                 diag::err_typecheck_bool_condition)
5056                   << From->getType() << From->getSourceRange();
5057   return ExprError();
5058 }
5059 
5060 /// Check that the specified conversion is permitted in a converted constant
5061 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5062 /// is acceptable.
5063 static bool CheckConvertedConstantConversions(Sema &S,
5064                                               StandardConversionSequence &SCS) {
5065   // Since we know that the target type is an integral or unscoped enumeration
5066   // type, most conversion kinds are impossible. All possible First and Third
5067   // conversions are fine.
5068   switch (SCS.Second) {
5069   case ICK_Identity:
5070   case ICK_NoReturn_Adjustment:
5071   case ICK_Integral_Promotion:
5072   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5073     return true;
5074 
5075   case ICK_Boolean_Conversion:
5076     // Conversion from an integral or unscoped enumeration type to bool is
5077     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5078     // conversion, so we allow it in a converted constant expression.
5079     //
5080     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5081     // a lot of popular code. We should at least add a warning for this
5082     // (non-conforming) extension.
5083     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5084            SCS.getToType(2)->isBooleanType();
5085 
5086   case ICK_Pointer_Conversion:
5087   case ICK_Pointer_Member:
5088     // C++1z: null pointer conversions and null member pointer conversions are
5089     // only permitted if the source type is std::nullptr_t.
5090     return SCS.getFromType()->isNullPtrType();
5091 
5092   case ICK_Floating_Promotion:
5093   case ICK_Complex_Promotion:
5094   case ICK_Floating_Conversion:
5095   case ICK_Complex_Conversion:
5096   case ICK_Floating_Integral:
5097   case ICK_Compatible_Conversion:
5098   case ICK_Derived_To_Base:
5099   case ICK_Vector_Conversion:
5100   case ICK_Vector_Splat:
5101   case ICK_Complex_Real:
5102   case ICK_Block_Pointer_Conversion:
5103   case ICK_TransparentUnionConversion:
5104   case ICK_Writeback_Conversion:
5105   case ICK_Zero_Event_Conversion:
5106   case ICK_C_Only_Conversion:
5107     return false;
5108 
5109   case ICK_Lvalue_To_Rvalue:
5110   case ICK_Array_To_Pointer:
5111   case ICK_Function_To_Pointer:
5112     llvm_unreachable("found a first conversion kind in Second");
5113 
5114   case ICK_Qualification:
5115     llvm_unreachable("found a third conversion kind in Second");
5116 
5117   case ICK_Num_Conversion_Kinds:
5118     break;
5119   }
5120 
5121   llvm_unreachable("unknown conversion kind");
5122 }
5123 
5124 /// CheckConvertedConstantExpression - Check that the expression From is a
5125 /// converted constant expression of type T, perform the conversion and produce
5126 /// the converted expression, per C++11 [expr.const]p3.
5127 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5128                                                    QualType T, APValue &Value,
5129                                                    Sema::CCEKind CCE,
5130                                                    bool RequireInt) {
5131   assert(S.getLangOpts().CPlusPlus11 &&
5132          "converted constant expression outside C++11");
5133 
5134   if (checkPlaceholderForOverload(S, From))
5135     return ExprError();
5136 
5137   // C++1z [expr.const]p3:
5138   //  A converted constant expression of type T is an expression,
5139   //  implicitly converted to type T, where the converted
5140   //  expression is a constant expression and the implicit conversion
5141   //  sequence contains only [... list of conversions ...].
5142   ImplicitConversionSequence ICS =
5143     TryCopyInitialization(S, From, T,
5144                           /*SuppressUserConversions=*/false,
5145                           /*InOverloadResolution=*/false,
5146                           /*AllowObjcWritebackConversion=*/false,
5147                           /*AllowExplicit=*/false);
5148   StandardConversionSequence *SCS = nullptr;
5149   switch (ICS.getKind()) {
5150   case ImplicitConversionSequence::StandardConversion:
5151     SCS = &ICS.Standard;
5152     break;
5153   case ImplicitConversionSequence::UserDefinedConversion:
5154     // We are converting to a non-class type, so the Before sequence
5155     // must be trivial.
5156     SCS = &ICS.UserDefined.After;
5157     break;
5158   case ImplicitConversionSequence::AmbiguousConversion:
5159   case ImplicitConversionSequence::BadConversion:
5160     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5161       return S.Diag(From->getLocStart(),
5162                     diag::err_typecheck_converted_constant_expression)
5163                 << From->getType() << From->getSourceRange() << T;
5164     return ExprError();
5165 
5166   case ImplicitConversionSequence::EllipsisConversion:
5167     llvm_unreachable("ellipsis conversion in converted constant expression");
5168   }
5169 
5170   // Check that we would only use permitted conversions.
5171   if (!CheckConvertedConstantConversions(S, *SCS)) {
5172     return S.Diag(From->getLocStart(),
5173                   diag::err_typecheck_converted_constant_expression_disallowed)
5174              << From->getType() << From->getSourceRange() << T;
5175   }
5176   // [...] and where the reference binding (if any) binds directly.
5177   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5178     return S.Diag(From->getLocStart(),
5179                   diag::err_typecheck_converted_constant_expression_indirect)
5180              << From->getType() << From->getSourceRange() << T;
5181   }
5182 
5183   ExprResult Result =
5184       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5185   if (Result.isInvalid())
5186     return Result;
5187 
5188   // Check for a narrowing implicit conversion.
5189   APValue PreNarrowingValue;
5190   QualType PreNarrowingType;
5191   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5192                                 PreNarrowingType)) {
5193   case NK_Variable_Narrowing:
5194     // Implicit conversion to a narrower type, and the value is not a constant
5195     // expression. We'll diagnose this in a moment.
5196   case NK_Not_Narrowing:
5197     break;
5198 
5199   case NK_Constant_Narrowing:
5200     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5201       << CCE << /*Constant*/1
5202       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5203     break;
5204 
5205   case NK_Type_Narrowing:
5206     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5207       << CCE << /*Constant*/0 << From->getType() << T;
5208     break;
5209   }
5210 
5211   // Check the expression is a constant expression.
5212   SmallVector<PartialDiagnosticAt, 8> Notes;
5213   Expr::EvalResult Eval;
5214   Eval.Diag = &Notes;
5215 
5216   if ((T->isReferenceType()
5217            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5218            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5219       (RequireInt && !Eval.Val.isInt())) {
5220     // The expression can't be folded, so we can't keep it at this position in
5221     // the AST.
5222     Result = ExprError();
5223   } else {
5224     Value = Eval.Val;
5225 
5226     if (Notes.empty()) {
5227       // It's a constant expression.
5228       return Result;
5229     }
5230   }
5231 
5232   // It's not a constant expression. Produce an appropriate diagnostic.
5233   if (Notes.size() == 1 &&
5234       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5235     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5236   else {
5237     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5238       << CCE << From->getSourceRange();
5239     for (unsigned I = 0; I < Notes.size(); ++I)
5240       S.Diag(Notes[I].first, Notes[I].second);
5241   }
5242   return ExprError();
5243 }
5244 
5245 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5246                                                   APValue &Value, CCEKind CCE) {
5247   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5248 }
5249 
5250 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5251                                                   llvm::APSInt &Value,
5252                                                   CCEKind CCE) {
5253   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5254 
5255   APValue V;
5256   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5257   if (!R.isInvalid())
5258     Value = V.getInt();
5259   return R;
5260 }
5261 
5262 
5263 /// dropPointerConversions - If the given standard conversion sequence
5264 /// involves any pointer conversions, remove them.  This may change
5265 /// the result type of the conversion sequence.
5266 static void dropPointerConversion(StandardConversionSequence &SCS) {
5267   if (SCS.Second == ICK_Pointer_Conversion) {
5268     SCS.Second = ICK_Identity;
5269     SCS.Third = ICK_Identity;
5270     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5271   }
5272 }
5273 
5274 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5275 /// convert the expression From to an Objective-C pointer type.
5276 static ImplicitConversionSequence
5277 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5278   // Do an implicit conversion to 'id'.
5279   QualType Ty = S.Context.getObjCIdType();
5280   ImplicitConversionSequence ICS
5281     = TryImplicitConversion(S, From, Ty,
5282                             // FIXME: Are these flags correct?
5283                             /*SuppressUserConversions=*/false,
5284                             /*AllowExplicit=*/true,
5285                             /*InOverloadResolution=*/false,
5286                             /*CStyle=*/false,
5287                             /*AllowObjCWritebackConversion=*/false,
5288                             /*AllowObjCConversionOnExplicit=*/true);
5289 
5290   // Strip off any final conversions to 'id'.
5291   switch (ICS.getKind()) {
5292   case ImplicitConversionSequence::BadConversion:
5293   case ImplicitConversionSequence::AmbiguousConversion:
5294   case ImplicitConversionSequence::EllipsisConversion:
5295     break;
5296 
5297   case ImplicitConversionSequence::UserDefinedConversion:
5298     dropPointerConversion(ICS.UserDefined.After);
5299     break;
5300 
5301   case ImplicitConversionSequence::StandardConversion:
5302     dropPointerConversion(ICS.Standard);
5303     break;
5304   }
5305 
5306   return ICS;
5307 }
5308 
5309 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5310 /// conversion of the expression From to an Objective-C pointer type.
5311 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5312   if (checkPlaceholderForOverload(*this, From))
5313     return ExprError();
5314 
5315   QualType Ty = Context.getObjCIdType();
5316   ImplicitConversionSequence ICS =
5317     TryContextuallyConvertToObjCPointer(*this, From);
5318   if (!ICS.isBad())
5319     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5320   return ExprError();
5321 }
5322 
5323 /// Determine whether the provided type is an integral type, or an enumeration
5324 /// type of a permitted flavor.
5325 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5326   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5327                                  : T->isIntegralOrUnscopedEnumerationType();
5328 }
5329 
5330 static ExprResult
5331 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5332                             Sema::ContextualImplicitConverter &Converter,
5333                             QualType T, UnresolvedSetImpl &ViableConversions) {
5334 
5335   if (Converter.Suppress)
5336     return ExprError();
5337 
5338   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5339   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5340     CXXConversionDecl *Conv =
5341         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5342     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5343     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5344   }
5345   return From;
5346 }
5347 
5348 static bool
5349 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5350                            Sema::ContextualImplicitConverter &Converter,
5351                            QualType T, bool HadMultipleCandidates,
5352                            UnresolvedSetImpl &ExplicitConversions) {
5353   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5354     DeclAccessPair Found = ExplicitConversions[0];
5355     CXXConversionDecl *Conversion =
5356         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5357 
5358     // The user probably meant to invoke the given explicit
5359     // conversion; use it.
5360     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5361     std::string TypeStr;
5362     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5363 
5364     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5365         << FixItHint::CreateInsertion(From->getLocStart(),
5366                                       "static_cast<" + TypeStr + ">(")
5367         << FixItHint::CreateInsertion(
5368                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5369     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5370 
5371     // If we aren't in a SFINAE context, build a call to the
5372     // explicit conversion function.
5373     if (SemaRef.isSFINAEContext())
5374       return true;
5375 
5376     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5377     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5378                                                        HadMultipleCandidates);
5379     if (Result.isInvalid())
5380       return true;
5381     // Record usage of conversion in an implicit cast.
5382     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5383                                     CK_UserDefinedConversion, Result.get(),
5384                                     nullptr, Result.get()->getValueKind());
5385   }
5386   return false;
5387 }
5388 
5389 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5390                              Sema::ContextualImplicitConverter &Converter,
5391                              QualType T, bool HadMultipleCandidates,
5392                              DeclAccessPair &Found) {
5393   CXXConversionDecl *Conversion =
5394       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5395   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5396 
5397   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5398   if (!Converter.SuppressConversion) {
5399     if (SemaRef.isSFINAEContext())
5400       return true;
5401 
5402     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5403         << From->getSourceRange();
5404   }
5405 
5406   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5407                                                      HadMultipleCandidates);
5408   if (Result.isInvalid())
5409     return true;
5410   // Record usage of conversion in an implicit cast.
5411   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5412                                   CK_UserDefinedConversion, Result.get(),
5413                                   nullptr, Result.get()->getValueKind());
5414   return false;
5415 }
5416 
5417 static ExprResult finishContextualImplicitConversion(
5418     Sema &SemaRef, SourceLocation Loc, Expr *From,
5419     Sema::ContextualImplicitConverter &Converter) {
5420   if (!Converter.match(From->getType()) && !Converter.Suppress)
5421     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5422         << From->getSourceRange();
5423 
5424   return SemaRef.DefaultLvalueConversion(From);
5425 }
5426 
5427 static void
5428 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5429                                   UnresolvedSetImpl &ViableConversions,
5430                                   OverloadCandidateSet &CandidateSet) {
5431   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5432     DeclAccessPair FoundDecl = ViableConversions[I];
5433     NamedDecl *D = FoundDecl.getDecl();
5434     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5435     if (isa<UsingShadowDecl>(D))
5436       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5437 
5438     CXXConversionDecl *Conv;
5439     FunctionTemplateDecl *ConvTemplate;
5440     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5441       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5442     else
5443       Conv = cast<CXXConversionDecl>(D);
5444 
5445     if (ConvTemplate)
5446       SemaRef.AddTemplateConversionCandidate(
5447         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5448         /*AllowObjCConversionOnExplicit=*/false);
5449     else
5450       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5451                                      ToType, CandidateSet,
5452                                      /*AllowObjCConversionOnExplicit=*/false);
5453   }
5454 }
5455 
5456 /// \brief Attempt to convert the given expression to a type which is accepted
5457 /// by the given converter.
5458 ///
5459 /// This routine will attempt to convert an expression of class type to a
5460 /// type accepted by the specified converter. In C++11 and before, the class
5461 /// must have a single non-explicit conversion function converting to a matching
5462 /// type. In C++1y, there can be multiple such conversion functions, but only
5463 /// one target type.
5464 ///
5465 /// \param Loc The source location of the construct that requires the
5466 /// conversion.
5467 ///
5468 /// \param From The expression we're converting from.
5469 ///
5470 /// \param Converter Used to control and diagnose the conversion process.
5471 ///
5472 /// \returns The expression, converted to an integral or enumeration type if
5473 /// successful.
5474 ExprResult Sema::PerformContextualImplicitConversion(
5475     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5476   // We can't perform any more checking for type-dependent expressions.
5477   if (From->isTypeDependent())
5478     return From;
5479 
5480   // Process placeholders immediately.
5481   if (From->hasPlaceholderType()) {
5482     ExprResult result = CheckPlaceholderExpr(From);
5483     if (result.isInvalid())
5484       return result;
5485     From = result.get();
5486   }
5487 
5488   // If the expression already has a matching type, we're golden.
5489   QualType T = From->getType();
5490   if (Converter.match(T))
5491     return DefaultLvalueConversion(From);
5492 
5493   // FIXME: Check for missing '()' if T is a function type?
5494 
5495   // We can only perform contextual implicit conversions on objects of class
5496   // type.
5497   const RecordType *RecordTy = T->getAs<RecordType>();
5498   if (!RecordTy || !getLangOpts().CPlusPlus) {
5499     if (!Converter.Suppress)
5500       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5501     return From;
5502   }
5503 
5504   // We must have a complete class type.
5505   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5506     ContextualImplicitConverter &Converter;
5507     Expr *From;
5508 
5509     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5510         : Converter(Converter), From(From) {}
5511 
5512     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5513       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5514     }
5515   } IncompleteDiagnoser(Converter, From);
5516 
5517   if (Converter.Suppress ? !isCompleteType(Loc, T)
5518                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5519     return From;
5520 
5521   // Look for a conversion to an integral or enumeration type.
5522   UnresolvedSet<4>
5523       ViableConversions; // These are *potentially* viable in C++1y.
5524   UnresolvedSet<4> ExplicitConversions;
5525   const auto &Conversions =
5526       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5527 
5528   bool HadMultipleCandidates =
5529       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5530 
5531   // To check that there is only one target type, in C++1y:
5532   QualType ToType;
5533   bool HasUniqueTargetType = true;
5534 
5535   // Collect explicit or viable (potentially in C++1y) conversions.
5536   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5537     NamedDecl *D = (*I)->getUnderlyingDecl();
5538     CXXConversionDecl *Conversion;
5539     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5540     if (ConvTemplate) {
5541       if (getLangOpts().CPlusPlus14)
5542         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5543       else
5544         continue; // C++11 does not consider conversion operator templates(?).
5545     } else
5546       Conversion = cast<CXXConversionDecl>(D);
5547 
5548     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5549            "Conversion operator templates are considered potentially "
5550            "viable in C++1y");
5551 
5552     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5553     if (Converter.match(CurToType) || ConvTemplate) {
5554 
5555       if (Conversion->isExplicit()) {
5556         // FIXME: For C++1y, do we need this restriction?
5557         // cf. diagnoseNoViableConversion()
5558         if (!ConvTemplate)
5559           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5560       } else {
5561         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5562           if (ToType.isNull())
5563             ToType = CurToType.getUnqualifiedType();
5564           else if (HasUniqueTargetType &&
5565                    (CurToType.getUnqualifiedType() != ToType))
5566             HasUniqueTargetType = false;
5567         }
5568         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5569       }
5570     }
5571   }
5572 
5573   if (getLangOpts().CPlusPlus14) {
5574     // C++1y [conv]p6:
5575     // ... An expression e of class type E appearing in such a context
5576     // is said to be contextually implicitly converted to a specified
5577     // type T and is well-formed if and only if e can be implicitly
5578     // converted to a type T that is determined as follows: E is searched
5579     // for conversion functions whose return type is cv T or reference to
5580     // cv T such that T is allowed by the context. There shall be
5581     // exactly one such T.
5582 
5583     // If no unique T is found:
5584     if (ToType.isNull()) {
5585       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5586                                      HadMultipleCandidates,
5587                                      ExplicitConversions))
5588         return ExprError();
5589       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5590     }
5591 
5592     // If more than one unique Ts are found:
5593     if (!HasUniqueTargetType)
5594       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5595                                          ViableConversions);
5596 
5597     // If one unique T is found:
5598     // First, build a candidate set from the previously recorded
5599     // potentially viable conversions.
5600     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5601     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5602                                       CandidateSet);
5603 
5604     // Then, perform overload resolution over the candidate set.
5605     OverloadCandidateSet::iterator Best;
5606     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5607     case OR_Success: {
5608       // Apply this conversion.
5609       DeclAccessPair Found =
5610           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5611       if (recordConversion(*this, Loc, From, Converter, T,
5612                            HadMultipleCandidates, Found))
5613         return ExprError();
5614       break;
5615     }
5616     case OR_Ambiguous:
5617       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5618                                          ViableConversions);
5619     case OR_No_Viable_Function:
5620       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5621                                      HadMultipleCandidates,
5622                                      ExplicitConversions))
5623         return ExprError();
5624     // fall through 'OR_Deleted' case.
5625     case OR_Deleted:
5626       // We'll complain below about a non-integral condition type.
5627       break;
5628     }
5629   } else {
5630     switch (ViableConversions.size()) {
5631     case 0: {
5632       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5633                                      HadMultipleCandidates,
5634                                      ExplicitConversions))
5635         return ExprError();
5636 
5637       // We'll complain below about a non-integral condition type.
5638       break;
5639     }
5640     case 1: {
5641       // Apply this conversion.
5642       DeclAccessPair Found = ViableConversions[0];
5643       if (recordConversion(*this, Loc, From, Converter, T,
5644                            HadMultipleCandidates, Found))
5645         return ExprError();
5646       break;
5647     }
5648     default:
5649       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5650                                          ViableConversions);
5651     }
5652   }
5653 
5654   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5655 }
5656 
5657 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5658 /// an acceptable non-member overloaded operator for a call whose
5659 /// arguments have types T1 (and, if non-empty, T2). This routine
5660 /// implements the check in C++ [over.match.oper]p3b2 concerning
5661 /// enumeration types.
5662 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5663                                                    FunctionDecl *Fn,
5664                                                    ArrayRef<Expr *> Args) {
5665   QualType T1 = Args[0]->getType();
5666   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5667 
5668   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5669     return true;
5670 
5671   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5672     return true;
5673 
5674   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5675   if (Proto->getNumParams() < 1)
5676     return false;
5677 
5678   if (T1->isEnumeralType()) {
5679     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5680     if (Context.hasSameUnqualifiedType(T1, ArgType))
5681       return true;
5682   }
5683 
5684   if (Proto->getNumParams() < 2)
5685     return false;
5686 
5687   if (!T2.isNull() && T2->isEnumeralType()) {
5688     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5689     if (Context.hasSameUnqualifiedType(T2, ArgType))
5690       return true;
5691   }
5692 
5693   return false;
5694 }
5695 
5696 /// AddOverloadCandidate - Adds the given function to the set of
5697 /// candidate functions, using the given function call arguments.  If
5698 /// @p SuppressUserConversions, then don't allow user-defined
5699 /// conversions via constructors or conversion operators.
5700 ///
5701 /// \param PartialOverloading true if we are performing "partial" overloading
5702 /// based on an incomplete set of function arguments. This feature is used by
5703 /// code completion.
5704 void
5705 Sema::AddOverloadCandidate(FunctionDecl *Function,
5706                            DeclAccessPair FoundDecl,
5707                            ArrayRef<Expr *> Args,
5708                            OverloadCandidateSet &CandidateSet,
5709                            bool SuppressUserConversions,
5710                            bool PartialOverloading,
5711                            bool AllowExplicit) {
5712   const FunctionProtoType *Proto
5713     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5714   assert(Proto && "Functions without a prototype cannot be overloaded");
5715   assert(!Function->getDescribedFunctionTemplate() &&
5716          "Use AddTemplateOverloadCandidate for function templates");
5717 
5718   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5719     if (!isa<CXXConstructorDecl>(Method)) {
5720       // If we get here, it's because we're calling a member function
5721       // that is named without a member access expression (e.g.,
5722       // "this->f") that was either written explicitly or created
5723       // implicitly. This can happen with a qualified call to a member
5724       // function, e.g., X::f(). We use an empty type for the implied
5725       // object argument (C++ [over.call.func]p3), and the acting context
5726       // is irrelevant.
5727       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5728                          QualType(), Expr::Classification::makeSimpleLValue(),
5729                          Args, CandidateSet, SuppressUserConversions,
5730                          PartialOverloading);
5731       return;
5732     }
5733     // We treat a constructor like a non-member function, since its object
5734     // argument doesn't participate in overload resolution.
5735   }
5736 
5737   if (!CandidateSet.isNewCandidate(Function))
5738     return;
5739 
5740   // C++ [over.match.oper]p3:
5741   //   if no operand has a class type, only those non-member functions in the
5742   //   lookup set that have a first parameter of type T1 or "reference to
5743   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5744   //   is a right operand) a second parameter of type T2 or "reference to
5745   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5746   //   candidate functions.
5747   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5748       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5749     return;
5750 
5751   // C++11 [class.copy]p11: [DR1402]
5752   //   A defaulted move constructor that is defined as deleted is ignored by
5753   //   overload resolution.
5754   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5755   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5756       Constructor->isMoveConstructor())
5757     return;
5758 
5759   // Overload resolution is always an unevaluated context.
5760   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5761 
5762   // Add this candidate
5763   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5764   Candidate.FoundDecl = FoundDecl;
5765   Candidate.Function = Function;
5766   Candidate.Viable = true;
5767   Candidate.IsSurrogate = false;
5768   Candidate.IgnoreObjectArgument = false;
5769   Candidate.ExplicitCallArguments = Args.size();
5770 
5771   if (Constructor) {
5772     // C++ [class.copy]p3:
5773     //   A member function template is never instantiated to perform the copy
5774     //   of a class object to an object of its class type.
5775     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5776     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5777         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5778          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5779                        ClassType))) {
5780       Candidate.Viable = false;
5781       Candidate.FailureKind = ovl_fail_illegal_constructor;
5782       return;
5783     }
5784   }
5785 
5786   unsigned NumParams = Proto->getNumParams();
5787 
5788   // (C++ 13.3.2p2): A candidate function having fewer than m
5789   // parameters is viable only if it has an ellipsis in its parameter
5790   // list (8.3.5).
5791   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5792       !Proto->isVariadic()) {
5793     Candidate.Viable = false;
5794     Candidate.FailureKind = ovl_fail_too_many_arguments;
5795     return;
5796   }
5797 
5798   // (C++ 13.3.2p2): A candidate function having more than m parameters
5799   // is viable only if the (m+1)st parameter has a default argument
5800   // (8.3.6). For the purposes of overload resolution, the
5801   // parameter list is truncated on the right, so that there are
5802   // exactly m parameters.
5803   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5804   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5805     // Not enough arguments.
5806     Candidate.Viable = false;
5807     Candidate.FailureKind = ovl_fail_too_few_arguments;
5808     return;
5809   }
5810 
5811   // (CUDA B.1): Check for invalid calls between targets.
5812   if (getLangOpts().CUDA)
5813     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5814       // Skip the check for callers that are implicit members, because in this
5815       // case we may not yet know what the member's target is; the target is
5816       // inferred for the member automatically, based on the bases and fields of
5817       // the class.
5818       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5819         Candidate.Viable = false;
5820         Candidate.FailureKind = ovl_fail_bad_target;
5821         return;
5822       }
5823 
5824   // Determine the implicit conversion sequences for each of the
5825   // arguments.
5826   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5827     if (ArgIdx < NumParams) {
5828       // (C++ 13.3.2p3): for F to be a viable function, there shall
5829       // exist for each argument an implicit conversion sequence
5830       // (13.3.3.1) that converts that argument to the corresponding
5831       // parameter of F.
5832       QualType ParamType = Proto->getParamType(ArgIdx);
5833       Candidate.Conversions[ArgIdx]
5834         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5835                                 SuppressUserConversions,
5836                                 /*InOverloadResolution=*/true,
5837                                 /*AllowObjCWritebackConversion=*/
5838                                   getLangOpts().ObjCAutoRefCount,
5839                                 AllowExplicit);
5840       if (Candidate.Conversions[ArgIdx].isBad()) {
5841         Candidate.Viable = false;
5842         Candidate.FailureKind = ovl_fail_bad_conversion;
5843         return;
5844       }
5845     } else {
5846       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5847       // argument for which there is no corresponding parameter is
5848       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5849       Candidate.Conversions[ArgIdx].setEllipsis();
5850     }
5851   }
5852 
5853   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5854     Candidate.Viable = false;
5855     Candidate.FailureKind = ovl_fail_enable_if;
5856     Candidate.DeductionFailure.Data = FailedAttr;
5857     return;
5858   }
5859 }
5860 
5861 ObjCMethodDecl *
5862 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5863                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5864   if (Methods.size() <= 1)
5865     return nullptr;
5866 
5867   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5868     bool Match = true;
5869     ObjCMethodDecl *Method = Methods[b];
5870     unsigned NumNamedArgs = Sel.getNumArgs();
5871     // Method might have more arguments than selector indicates. This is due
5872     // to addition of c-style arguments in method.
5873     if (Method->param_size() > NumNamedArgs)
5874       NumNamedArgs = Method->param_size();
5875     if (Args.size() < NumNamedArgs)
5876       continue;
5877 
5878     for (unsigned i = 0; i < NumNamedArgs; i++) {
5879       // We can't do any type-checking on a type-dependent argument.
5880       if (Args[i]->isTypeDependent()) {
5881         Match = false;
5882         break;
5883       }
5884 
5885       ParmVarDecl *param = Method->parameters()[i];
5886       Expr *argExpr = Args[i];
5887       assert(argExpr && "SelectBestMethod(): missing expression");
5888 
5889       // Strip the unbridged-cast placeholder expression off unless it's
5890       // a consumed argument.
5891       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5892           !param->hasAttr<CFConsumedAttr>())
5893         argExpr = stripARCUnbridgedCast(argExpr);
5894 
5895       // If the parameter is __unknown_anytype, move on to the next method.
5896       if (param->getType() == Context.UnknownAnyTy) {
5897         Match = false;
5898         break;
5899       }
5900 
5901       ImplicitConversionSequence ConversionState
5902         = TryCopyInitialization(*this, argExpr, param->getType(),
5903                                 /*SuppressUserConversions*/false,
5904                                 /*InOverloadResolution=*/true,
5905                                 /*AllowObjCWritebackConversion=*/
5906                                 getLangOpts().ObjCAutoRefCount,
5907                                 /*AllowExplicit*/false);
5908         if (ConversionState.isBad()) {
5909           Match = false;
5910           break;
5911         }
5912     }
5913     // Promote additional arguments to variadic methods.
5914     if (Match && Method->isVariadic()) {
5915       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5916         if (Args[i]->isTypeDependent()) {
5917           Match = false;
5918           break;
5919         }
5920         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5921                                                           nullptr);
5922         if (Arg.isInvalid()) {
5923           Match = false;
5924           break;
5925         }
5926       }
5927     } else {
5928       // Check for extra arguments to non-variadic methods.
5929       if (Args.size() != NumNamedArgs)
5930         Match = false;
5931       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5932         // Special case when selectors have no argument. In this case, select
5933         // one with the most general result type of 'id'.
5934         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5935           QualType ReturnT = Methods[b]->getReturnType();
5936           if (ReturnT->isObjCIdType())
5937             return Methods[b];
5938         }
5939       }
5940     }
5941 
5942     if (Match)
5943       return Method;
5944   }
5945   return nullptr;
5946 }
5947 
5948 // specific_attr_iterator iterates over enable_if attributes in reverse, and
5949 // enable_if is order-sensitive. As a result, we need to reverse things
5950 // sometimes. Size of 4 elements is arbitrary.
5951 static SmallVector<EnableIfAttr *, 4>
5952 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5953   SmallVector<EnableIfAttr *, 4> Result;
5954   if (!Function->hasAttrs())
5955     return Result;
5956 
5957   const auto &FuncAttrs = Function->getAttrs();
5958   for (Attr *Attr : FuncAttrs)
5959     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5960       Result.push_back(EnableIf);
5961 
5962   std::reverse(Result.begin(), Result.end());
5963   return Result;
5964 }
5965 
5966 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5967                                   bool MissingImplicitThis) {
5968   auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5969   if (EnableIfAttrs.empty())
5970     return nullptr;
5971 
5972   SFINAETrap Trap(*this);
5973   SmallVector<Expr *, 16> ConvertedArgs;
5974   bool InitializationFailed = false;
5975 
5976   // Convert the arguments.
5977   for (unsigned I = 0, E = Args.size(); I != E; ++I) {
5978     ExprResult R;
5979     if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5980         !cast<CXXMethodDecl>(Function)->isStatic() &&
5981         !isa<CXXConstructorDecl>(Function)) {
5982       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5983       R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5984                                               Method, Method);
5985     } else {
5986       R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5987                                         Context, Function->getParamDecl(I)),
5988                                     SourceLocation(), Args[I]);
5989     }
5990 
5991     if (R.isInvalid()) {
5992       InitializationFailed = true;
5993       break;
5994     }
5995 
5996     ConvertedArgs.push_back(R.get());
5997   }
5998 
5999   if (InitializationFailed || Trap.hasErrorOccurred())
6000     return EnableIfAttrs[0];
6001 
6002   // Push default arguments if needed.
6003   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6004     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6005       ParmVarDecl *P = Function->getParamDecl(i);
6006       ExprResult R = PerformCopyInitialization(
6007           InitializedEntity::InitializeParameter(Context,
6008                                                  Function->getParamDecl(i)),
6009           SourceLocation(),
6010           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6011                                            : P->getDefaultArg());
6012       if (R.isInvalid()) {
6013         InitializationFailed = true;
6014         break;
6015       }
6016       ConvertedArgs.push_back(R.get());
6017     }
6018 
6019     if (InitializationFailed || Trap.hasErrorOccurred())
6020       return EnableIfAttrs[0];
6021   }
6022 
6023   for (auto *EIA : EnableIfAttrs) {
6024     APValue Result;
6025     // FIXME: This doesn't consider value-dependent cases, because doing so is
6026     // very difficult. Ideally, we should handle them more gracefully.
6027     if (!EIA->getCond()->EvaluateWithSubstitution(
6028             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6029       return EIA;
6030 
6031     if (!Result.isInt() || !Result.getInt().getBoolValue())
6032       return EIA;
6033   }
6034   return nullptr;
6035 }
6036 
6037 /// \brief Add all of the function declarations in the given function set to
6038 /// the overload candidate set.
6039 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6040                                  ArrayRef<Expr *> Args,
6041                                  OverloadCandidateSet& CandidateSet,
6042                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6043                                  bool SuppressUserConversions,
6044                                  bool PartialOverloading) {
6045   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6046     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6047     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6048       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6049         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6050                            cast<CXXMethodDecl>(FD)->getParent(),
6051                            Args[0]->getType(), Args[0]->Classify(Context),
6052                            Args.slice(1), CandidateSet,
6053                            SuppressUserConversions, PartialOverloading);
6054       else
6055         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6056                              SuppressUserConversions, PartialOverloading);
6057     } else {
6058       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6059       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6060           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6061         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6062                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6063                                    ExplicitTemplateArgs,
6064                                    Args[0]->getType(),
6065                                    Args[0]->Classify(Context), Args.slice(1),
6066                                    CandidateSet, SuppressUserConversions,
6067                                    PartialOverloading);
6068       else
6069         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6070                                      ExplicitTemplateArgs, Args,
6071                                      CandidateSet, SuppressUserConversions,
6072                                      PartialOverloading);
6073     }
6074   }
6075 }
6076 
6077 /// AddMethodCandidate - Adds a named decl (which is some kind of
6078 /// method) as a method candidate to the given overload set.
6079 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6080                               QualType ObjectType,
6081                               Expr::Classification ObjectClassification,
6082                               ArrayRef<Expr *> Args,
6083                               OverloadCandidateSet& CandidateSet,
6084                               bool SuppressUserConversions) {
6085   NamedDecl *Decl = FoundDecl.getDecl();
6086   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6087 
6088   if (isa<UsingShadowDecl>(Decl))
6089     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6090 
6091   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6092     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6093            "Expected a member function template");
6094     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6095                                /*ExplicitArgs*/ nullptr,
6096                                ObjectType, ObjectClassification,
6097                                Args, CandidateSet,
6098                                SuppressUserConversions);
6099   } else {
6100     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6101                        ObjectType, ObjectClassification,
6102                        Args,
6103                        CandidateSet, SuppressUserConversions);
6104   }
6105 }
6106 
6107 /// AddMethodCandidate - Adds the given C++ member function to the set
6108 /// of candidate functions, using the given function call arguments
6109 /// and the object argument (@c Object). For example, in a call
6110 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6111 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6112 /// allow user-defined conversions via constructors or conversion
6113 /// operators.
6114 void
6115 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6116                          CXXRecordDecl *ActingContext, QualType ObjectType,
6117                          Expr::Classification ObjectClassification,
6118                          ArrayRef<Expr *> Args,
6119                          OverloadCandidateSet &CandidateSet,
6120                          bool SuppressUserConversions,
6121                          bool PartialOverloading) {
6122   const FunctionProtoType *Proto
6123     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6124   assert(Proto && "Methods without a prototype cannot be overloaded");
6125   assert(!isa<CXXConstructorDecl>(Method) &&
6126          "Use AddOverloadCandidate for constructors");
6127 
6128   if (!CandidateSet.isNewCandidate(Method))
6129     return;
6130 
6131   // C++11 [class.copy]p23: [DR1402]
6132   //   A defaulted move assignment operator that is defined as deleted is
6133   //   ignored by overload resolution.
6134   if (Method->isDefaulted() && Method->isDeleted() &&
6135       Method->isMoveAssignmentOperator())
6136     return;
6137 
6138   // Overload resolution is always an unevaluated context.
6139   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6140 
6141   // Add this candidate
6142   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6143   Candidate.FoundDecl = FoundDecl;
6144   Candidate.Function = Method;
6145   Candidate.IsSurrogate = false;
6146   Candidate.IgnoreObjectArgument = false;
6147   Candidate.ExplicitCallArguments = Args.size();
6148 
6149   unsigned NumParams = Proto->getNumParams();
6150 
6151   // (C++ 13.3.2p2): A candidate function having fewer than m
6152   // parameters is viable only if it has an ellipsis in its parameter
6153   // list (8.3.5).
6154   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6155       !Proto->isVariadic()) {
6156     Candidate.Viable = false;
6157     Candidate.FailureKind = ovl_fail_too_many_arguments;
6158     return;
6159   }
6160 
6161   // (C++ 13.3.2p2): A candidate function having more than m parameters
6162   // is viable only if the (m+1)st parameter has a default argument
6163   // (8.3.6). For the purposes of overload resolution, the
6164   // parameter list is truncated on the right, so that there are
6165   // exactly m parameters.
6166   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6167   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6168     // Not enough arguments.
6169     Candidate.Viable = false;
6170     Candidate.FailureKind = ovl_fail_too_few_arguments;
6171     return;
6172   }
6173 
6174   Candidate.Viable = true;
6175 
6176   if (Method->isStatic() || ObjectType.isNull())
6177     // The implicit object argument is ignored.
6178     Candidate.IgnoreObjectArgument = true;
6179   else {
6180     // Determine the implicit conversion sequence for the object
6181     // parameter.
6182     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6183         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6184         Method, ActingContext);
6185     if (Candidate.Conversions[0].isBad()) {
6186       Candidate.Viable = false;
6187       Candidate.FailureKind = ovl_fail_bad_conversion;
6188       return;
6189     }
6190   }
6191 
6192   // (CUDA B.1): Check for invalid calls between targets.
6193   if (getLangOpts().CUDA)
6194     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6195       if (CheckCUDATarget(Caller, Method)) {
6196         Candidate.Viable = false;
6197         Candidate.FailureKind = ovl_fail_bad_target;
6198         return;
6199       }
6200 
6201   // Determine the implicit conversion sequences for each of the
6202   // arguments.
6203   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6204     if (ArgIdx < NumParams) {
6205       // (C++ 13.3.2p3): for F to be a viable function, there shall
6206       // exist for each argument an implicit conversion sequence
6207       // (13.3.3.1) that converts that argument to the corresponding
6208       // parameter of F.
6209       QualType ParamType = Proto->getParamType(ArgIdx);
6210       Candidate.Conversions[ArgIdx + 1]
6211         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6212                                 SuppressUserConversions,
6213                                 /*InOverloadResolution=*/true,
6214                                 /*AllowObjCWritebackConversion=*/
6215                                   getLangOpts().ObjCAutoRefCount);
6216       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6217         Candidate.Viable = false;
6218         Candidate.FailureKind = ovl_fail_bad_conversion;
6219         return;
6220       }
6221     } else {
6222       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6223       // argument for which there is no corresponding parameter is
6224       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6225       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6226     }
6227   }
6228 
6229   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6230     Candidate.Viable = false;
6231     Candidate.FailureKind = ovl_fail_enable_if;
6232     Candidate.DeductionFailure.Data = FailedAttr;
6233     return;
6234   }
6235 }
6236 
6237 /// \brief Add a C++ member function template as a candidate to the candidate
6238 /// set, using template argument deduction to produce an appropriate member
6239 /// function template specialization.
6240 void
6241 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6242                                  DeclAccessPair FoundDecl,
6243                                  CXXRecordDecl *ActingContext,
6244                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6245                                  QualType ObjectType,
6246                                  Expr::Classification ObjectClassification,
6247                                  ArrayRef<Expr *> Args,
6248                                  OverloadCandidateSet& CandidateSet,
6249                                  bool SuppressUserConversions,
6250                                  bool PartialOverloading) {
6251   if (!CandidateSet.isNewCandidate(MethodTmpl))
6252     return;
6253 
6254   // C++ [over.match.funcs]p7:
6255   //   In each case where a candidate is a function template, candidate
6256   //   function template specializations are generated using template argument
6257   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6258   //   candidate functions in the usual way.113) A given name can refer to one
6259   //   or more function templates and also to a set of overloaded non-template
6260   //   functions. In such a case, the candidate functions generated from each
6261   //   function template are combined with the set of non-template candidate
6262   //   functions.
6263   TemplateDeductionInfo Info(CandidateSet.getLocation());
6264   FunctionDecl *Specialization = nullptr;
6265   if (TemplateDeductionResult Result
6266       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6267                                 Specialization, Info, PartialOverloading)) {
6268     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6269     Candidate.FoundDecl = FoundDecl;
6270     Candidate.Function = MethodTmpl->getTemplatedDecl();
6271     Candidate.Viable = false;
6272     Candidate.FailureKind = ovl_fail_bad_deduction;
6273     Candidate.IsSurrogate = false;
6274     Candidate.IgnoreObjectArgument = false;
6275     Candidate.ExplicitCallArguments = Args.size();
6276     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6277                                                           Info);
6278     return;
6279   }
6280 
6281   // Add the function template specialization produced by template argument
6282   // deduction as a candidate.
6283   assert(Specialization && "Missing member function template specialization?");
6284   assert(isa<CXXMethodDecl>(Specialization) &&
6285          "Specialization is not a member function?");
6286   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6287                      ActingContext, ObjectType, ObjectClassification, Args,
6288                      CandidateSet, SuppressUserConversions, PartialOverloading);
6289 }
6290 
6291 /// \brief Add a C++ function template specialization as a candidate
6292 /// in the candidate set, using template argument deduction to produce
6293 /// an appropriate function template specialization.
6294 void
6295 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6296                                    DeclAccessPair FoundDecl,
6297                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6298                                    ArrayRef<Expr *> Args,
6299                                    OverloadCandidateSet& CandidateSet,
6300                                    bool SuppressUserConversions,
6301                                    bool PartialOverloading) {
6302   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6303     return;
6304 
6305   // C++ [over.match.funcs]p7:
6306   //   In each case where a candidate is a function template, candidate
6307   //   function template specializations are generated using template argument
6308   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6309   //   candidate functions in the usual way.113) A given name can refer to one
6310   //   or more function templates and also to a set of overloaded non-template
6311   //   functions. In such a case, the candidate functions generated from each
6312   //   function template are combined with the set of non-template candidate
6313   //   functions.
6314   TemplateDeductionInfo Info(CandidateSet.getLocation());
6315   FunctionDecl *Specialization = nullptr;
6316   if (TemplateDeductionResult Result
6317         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6318                                   Specialization, Info, PartialOverloading)) {
6319     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6320     Candidate.FoundDecl = FoundDecl;
6321     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6322     Candidate.Viable = false;
6323     Candidate.FailureKind = ovl_fail_bad_deduction;
6324     Candidate.IsSurrogate = false;
6325     Candidate.IgnoreObjectArgument = false;
6326     Candidate.ExplicitCallArguments = Args.size();
6327     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6328                                                           Info);
6329     return;
6330   }
6331 
6332   // Add the function template specialization produced by template argument
6333   // deduction as a candidate.
6334   assert(Specialization && "Missing function template specialization?");
6335   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6336                        SuppressUserConversions, PartialOverloading);
6337 }
6338 
6339 /// Determine whether this is an allowable conversion from the result
6340 /// of an explicit conversion operator to the expected type, per C++
6341 /// [over.match.conv]p1 and [over.match.ref]p1.
6342 ///
6343 /// \param ConvType The return type of the conversion function.
6344 ///
6345 /// \param ToType The type we are converting to.
6346 ///
6347 /// \param AllowObjCPointerConversion Allow a conversion from one
6348 /// Objective-C pointer to another.
6349 ///
6350 /// \returns true if the conversion is allowable, false otherwise.
6351 static bool isAllowableExplicitConversion(Sema &S,
6352                                           QualType ConvType, QualType ToType,
6353                                           bool AllowObjCPointerConversion) {
6354   QualType ToNonRefType = ToType.getNonReferenceType();
6355 
6356   // Easy case: the types are the same.
6357   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6358     return true;
6359 
6360   // Allow qualification conversions.
6361   bool ObjCLifetimeConversion;
6362   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6363                                   ObjCLifetimeConversion))
6364     return true;
6365 
6366   // If we're not allowed to consider Objective-C pointer conversions,
6367   // we're done.
6368   if (!AllowObjCPointerConversion)
6369     return false;
6370 
6371   // Is this an Objective-C pointer conversion?
6372   bool IncompatibleObjC = false;
6373   QualType ConvertedType;
6374   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6375                                    IncompatibleObjC);
6376 }
6377 
6378 /// AddConversionCandidate - Add a C++ conversion function as a
6379 /// candidate in the candidate set (C++ [over.match.conv],
6380 /// C++ [over.match.copy]). From is the expression we're converting from,
6381 /// and ToType is the type that we're eventually trying to convert to
6382 /// (which may or may not be the same type as the type that the
6383 /// conversion function produces).
6384 void
6385 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6386                              DeclAccessPair FoundDecl,
6387                              CXXRecordDecl *ActingContext,
6388                              Expr *From, QualType ToType,
6389                              OverloadCandidateSet& CandidateSet,
6390                              bool AllowObjCConversionOnExplicit) {
6391   assert(!Conversion->getDescribedFunctionTemplate() &&
6392          "Conversion function templates use AddTemplateConversionCandidate");
6393   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6394   if (!CandidateSet.isNewCandidate(Conversion))
6395     return;
6396 
6397   // If the conversion function has an undeduced return type, trigger its
6398   // deduction now.
6399   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6400     if (DeduceReturnType(Conversion, From->getExprLoc()))
6401       return;
6402     ConvType = Conversion->getConversionType().getNonReferenceType();
6403   }
6404 
6405   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6406   // operator is only a candidate if its return type is the target type or
6407   // can be converted to the target type with a qualification conversion.
6408   if (Conversion->isExplicit() &&
6409       !isAllowableExplicitConversion(*this, ConvType, ToType,
6410                                      AllowObjCConversionOnExplicit))
6411     return;
6412 
6413   // Overload resolution is always an unevaluated context.
6414   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6415 
6416   // Add this candidate
6417   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6418   Candidate.FoundDecl = FoundDecl;
6419   Candidate.Function = Conversion;
6420   Candidate.IsSurrogate = false;
6421   Candidate.IgnoreObjectArgument = false;
6422   Candidate.FinalConversion.setAsIdentityConversion();
6423   Candidate.FinalConversion.setFromType(ConvType);
6424   Candidate.FinalConversion.setAllToTypes(ToType);
6425   Candidate.Viable = true;
6426   Candidate.ExplicitCallArguments = 1;
6427 
6428   // C++ [over.match.funcs]p4:
6429   //   For conversion functions, the function is considered to be a member of
6430   //   the class of the implicit implied object argument for the purpose of
6431   //   defining the type of the implicit object parameter.
6432   //
6433   // Determine the implicit conversion sequence for the implicit
6434   // object parameter.
6435   QualType ImplicitParamType = From->getType();
6436   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6437     ImplicitParamType = FromPtrType->getPointeeType();
6438   CXXRecordDecl *ConversionContext
6439     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6440 
6441   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6442       *this, CandidateSet.getLocation(), From->getType(),
6443       From->Classify(Context), Conversion, ConversionContext);
6444 
6445   if (Candidate.Conversions[0].isBad()) {
6446     Candidate.Viable = false;
6447     Candidate.FailureKind = ovl_fail_bad_conversion;
6448     return;
6449   }
6450 
6451   // We won't go through a user-defined type conversion function to convert a
6452   // derived to base as such conversions are given Conversion Rank. They only
6453   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6454   QualType FromCanon
6455     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6456   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6457   if (FromCanon == ToCanon ||
6458       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6459     Candidate.Viable = false;
6460     Candidate.FailureKind = ovl_fail_trivial_conversion;
6461     return;
6462   }
6463 
6464   // To determine what the conversion from the result of calling the
6465   // conversion function to the type we're eventually trying to
6466   // convert to (ToType), we need to synthesize a call to the
6467   // conversion function and attempt copy initialization from it. This
6468   // makes sure that we get the right semantics with respect to
6469   // lvalues/rvalues and the type. Fortunately, we can allocate this
6470   // call on the stack and we don't need its arguments to be
6471   // well-formed.
6472   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6473                             VK_LValue, From->getLocStart());
6474   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6475                                 Context.getPointerType(Conversion->getType()),
6476                                 CK_FunctionToPointerDecay,
6477                                 &ConversionRef, VK_RValue);
6478 
6479   QualType ConversionType = Conversion->getConversionType();
6480   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6481     Candidate.Viable = false;
6482     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6483     return;
6484   }
6485 
6486   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6487 
6488   // Note that it is safe to allocate CallExpr on the stack here because
6489   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6490   // allocator).
6491   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6492   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6493                 From->getLocStart());
6494   ImplicitConversionSequence ICS =
6495     TryCopyInitialization(*this, &Call, ToType,
6496                           /*SuppressUserConversions=*/true,
6497                           /*InOverloadResolution=*/false,
6498                           /*AllowObjCWritebackConversion=*/false);
6499 
6500   switch (ICS.getKind()) {
6501   case ImplicitConversionSequence::StandardConversion:
6502     Candidate.FinalConversion = ICS.Standard;
6503 
6504     // C++ [over.ics.user]p3:
6505     //   If the user-defined conversion is specified by a specialization of a
6506     //   conversion function template, the second standard conversion sequence
6507     //   shall have exact match rank.
6508     if (Conversion->getPrimaryTemplate() &&
6509         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6510       Candidate.Viable = false;
6511       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6512       return;
6513     }
6514 
6515     // C++0x [dcl.init.ref]p5:
6516     //    In the second case, if the reference is an rvalue reference and
6517     //    the second standard conversion sequence of the user-defined
6518     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6519     //    program is ill-formed.
6520     if (ToType->isRValueReferenceType() &&
6521         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6522       Candidate.Viable = false;
6523       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6524       return;
6525     }
6526     break;
6527 
6528   case ImplicitConversionSequence::BadConversion:
6529     Candidate.Viable = false;
6530     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6531     return;
6532 
6533   default:
6534     llvm_unreachable(
6535            "Can only end up with a standard conversion sequence or failure");
6536   }
6537 
6538   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6539     Candidate.Viable = false;
6540     Candidate.FailureKind = ovl_fail_enable_if;
6541     Candidate.DeductionFailure.Data = FailedAttr;
6542     return;
6543   }
6544 }
6545 
6546 /// \brief Adds a conversion function template specialization
6547 /// candidate to the overload set, using template argument deduction
6548 /// to deduce the template arguments of the conversion function
6549 /// template from the type that we are converting to (C++
6550 /// [temp.deduct.conv]).
6551 void
6552 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6553                                      DeclAccessPair FoundDecl,
6554                                      CXXRecordDecl *ActingDC,
6555                                      Expr *From, QualType ToType,
6556                                      OverloadCandidateSet &CandidateSet,
6557                                      bool AllowObjCConversionOnExplicit) {
6558   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6559          "Only conversion function templates permitted here");
6560 
6561   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6562     return;
6563 
6564   TemplateDeductionInfo Info(CandidateSet.getLocation());
6565   CXXConversionDecl *Specialization = nullptr;
6566   if (TemplateDeductionResult Result
6567         = DeduceTemplateArguments(FunctionTemplate, ToType,
6568                                   Specialization, Info)) {
6569     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6570     Candidate.FoundDecl = FoundDecl;
6571     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6572     Candidate.Viable = false;
6573     Candidate.FailureKind = ovl_fail_bad_deduction;
6574     Candidate.IsSurrogate = false;
6575     Candidate.IgnoreObjectArgument = false;
6576     Candidate.ExplicitCallArguments = 1;
6577     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6578                                                           Info);
6579     return;
6580   }
6581 
6582   // Add the conversion function template specialization produced by
6583   // template argument deduction as a candidate.
6584   assert(Specialization && "Missing function template specialization?");
6585   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6586                          CandidateSet, AllowObjCConversionOnExplicit);
6587 }
6588 
6589 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6590 /// converts the given @c Object to a function pointer via the
6591 /// conversion function @c Conversion, and then attempts to call it
6592 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6593 /// the type of function that we'll eventually be calling.
6594 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6595                                  DeclAccessPair FoundDecl,
6596                                  CXXRecordDecl *ActingContext,
6597                                  const FunctionProtoType *Proto,
6598                                  Expr *Object,
6599                                  ArrayRef<Expr *> Args,
6600                                  OverloadCandidateSet& CandidateSet) {
6601   if (!CandidateSet.isNewCandidate(Conversion))
6602     return;
6603 
6604   // Overload resolution is always an unevaluated context.
6605   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6606 
6607   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6608   Candidate.FoundDecl = FoundDecl;
6609   Candidate.Function = nullptr;
6610   Candidate.Surrogate = Conversion;
6611   Candidate.Viable = true;
6612   Candidate.IsSurrogate = true;
6613   Candidate.IgnoreObjectArgument = false;
6614   Candidate.ExplicitCallArguments = Args.size();
6615 
6616   // Determine the implicit conversion sequence for the implicit
6617   // object parameter.
6618   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6619       *this, CandidateSet.getLocation(), Object->getType(),
6620       Object->Classify(Context), Conversion, ActingContext);
6621   if (ObjectInit.isBad()) {
6622     Candidate.Viable = false;
6623     Candidate.FailureKind = ovl_fail_bad_conversion;
6624     Candidate.Conversions[0] = ObjectInit;
6625     return;
6626   }
6627 
6628   // The first conversion is actually a user-defined conversion whose
6629   // first conversion is ObjectInit's standard conversion (which is
6630   // effectively a reference binding). Record it as such.
6631   Candidate.Conversions[0].setUserDefined();
6632   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6633   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6634   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6635   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6636   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6637   Candidate.Conversions[0].UserDefined.After
6638     = Candidate.Conversions[0].UserDefined.Before;
6639   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6640 
6641   // Find the
6642   unsigned NumParams = Proto->getNumParams();
6643 
6644   // (C++ 13.3.2p2): A candidate function having fewer than m
6645   // parameters is viable only if it has an ellipsis in its parameter
6646   // list (8.3.5).
6647   if (Args.size() > NumParams && !Proto->isVariadic()) {
6648     Candidate.Viable = false;
6649     Candidate.FailureKind = ovl_fail_too_many_arguments;
6650     return;
6651   }
6652 
6653   // Function types don't have any default arguments, so just check if
6654   // we have enough arguments.
6655   if (Args.size() < NumParams) {
6656     // Not enough arguments.
6657     Candidate.Viable = false;
6658     Candidate.FailureKind = ovl_fail_too_few_arguments;
6659     return;
6660   }
6661 
6662   // Determine the implicit conversion sequences for each of the
6663   // arguments.
6664   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6665     if (ArgIdx < NumParams) {
6666       // (C++ 13.3.2p3): for F to be a viable function, there shall
6667       // exist for each argument an implicit conversion sequence
6668       // (13.3.3.1) that converts that argument to the corresponding
6669       // parameter of F.
6670       QualType ParamType = Proto->getParamType(ArgIdx);
6671       Candidate.Conversions[ArgIdx + 1]
6672         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6673                                 /*SuppressUserConversions=*/false,
6674                                 /*InOverloadResolution=*/false,
6675                                 /*AllowObjCWritebackConversion=*/
6676                                   getLangOpts().ObjCAutoRefCount);
6677       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6678         Candidate.Viable = false;
6679         Candidate.FailureKind = ovl_fail_bad_conversion;
6680         return;
6681       }
6682     } else {
6683       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6684       // argument for which there is no corresponding parameter is
6685       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6686       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6687     }
6688   }
6689 
6690   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6691     Candidate.Viable = false;
6692     Candidate.FailureKind = ovl_fail_enable_if;
6693     Candidate.DeductionFailure.Data = FailedAttr;
6694     return;
6695   }
6696 }
6697 
6698 /// \brief Add overload candidates for overloaded operators that are
6699 /// member functions.
6700 ///
6701 /// Add the overloaded operator candidates that are member functions
6702 /// for the operator Op that was used in an operator expression such
6703 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6704 /// CandidateSet will store the added overload candidates. (C++
6705 /// [over.match.oper]).
6706 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6707                                        SourceLocation OpLoc,
6708                                        ArrayRef<Expr *> Args,
6709                                        OverloadCandidateSet& CandidateSet,
6710                                        SourceRange OpRange) {
6711   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6712 
6713   // C++ [over.match.oper]p3:
6714   //   For a unary operator @ with an operand of a type whose
6715   //   cv-unqualified version is T1, and for a binary operator @ with
6716   //   a left operand of a type whose cv-unqualified version is T1 and
6717   //   a right operand of a type whose cv-unqualified version is T2,
6718   //   three sets of candidate functions, designated member
6719   //   candidates, non-member candidates and built-in candidates, are
6720   //   constructed as follows:
6721   QualType T1 = Args[0]->getType();
6722 
6723   //     -- If T1 is a complete class type or a class currently being
6724   //        defined, the set of member candidates is the result of the
6725   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6726   //        the set of member candidates is empty.
6727   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6728     // Complete the type if it can be completed.
6729     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6730       return;
6731     // If the type is neither complete nor being defined, bail out now.
6732     if (!T1Rec->getDecl()->getDefinition())
6733       return;
6734 
6735     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6736     LookupQualifiedName(Operators, T1Rec->getDecl());
6737     Operators.suppressDiagnostics();
6738 
6739     for (LookupResult::iterator Oper = Operators.begin(),
6740                              OperEnd = Operators.end();
6741          Oper != OperEnd;
6742          ++Oper)
6743       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6744                          Args[0]->Classify(Context),
6745                          Args.slice(1),
6746                          CandidateSet,
6747                          /* SuppressUserConversions = */ false);
6748   }
6749 }
6750 
6751 /// AddBuiltinCandidate - Add a candidate for a built-in
6752 /// operator. ResultTy and ParamTys are the result and parameter types
6753 /// of the built-in candidate, respectively. Args and NumArgs are the
6754 /// arguments being passed to the candidate. IsAssignmentOperator
6755 /// should be true when this built-in candidate is an assignment
6756 /// operator. NumContextualBoolArguments is the number of arguments
6757 /// (at the beginning of the argument list) that will be contextually
6758 /// converted to bool.
6759 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6760                                ArrayRef<Expr *> Args,
6761                                OverloadCandidateSet& CandidateSet,
6762                                bool IsAssignmentOperator,
6763                                unsigned NumContextualBoolArguments) {
6764   // Overload resolution is always an unevaluated context.
6765   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6766 
6767   // Add this candidate
6768   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6769   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6770   Candidate.Function = nullptr;
6771   Candidate.IsSurrogate = false;
6772   Candidate.IgnoreObjectArgument = false;
6773   Candidate.BuiltinTypes.ResultTy = ResultTy;
6774   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6775     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6776 
6777   // Determine the implicit conversion sequences for each of the
6778   // arguments.
6779   Candidate.Viable = true;
6780   Candidate.ExplicitCallArguments = Args.size();
6781   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6782     // C++ [over.match.oper]p4:
6783     //   For the built-in assignment operators, conversions of the
6784     //   left operand are restricted as follows:
6785     //     -- no temporaries are introduced to hold the left operand, and
6786     //     -- no user-defined conversions are applied to the left
6787     //        operand to achieve a type match with the left-most
6788     //        parameter of a built-in candidate.
6789     //
6790     // We block these conversions by turning off user-defined
6791     // conversions, since that is the only way that initialization of
6792     // a reference to a non-class type can occur from something that
6793     // is not of the same type.
6794     if (ArgIdx < NumContextualBoolArguments) {
6795       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6796              "Contextual conversion to bool requires bool type");
6797       Candidate.Conversions[ArgIdx]
6798         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6799     } else {
6800       Candidate.Conversions[ArgIdx]
6801         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6802                                 ArgIdx == 0 && IsAssignmentOperator,
6803                                 /*InOverloadResolution=*/false,
6804                                 /*AllowObjCWritebackConversion=*/
6805                                   getLangOpts().ObjCAutoRefCount);
6806     }
6807     if (Candidate.Conversions[ArgIdx].isBad()) {
6808       Candidate.Viable = false;
6809       Candidate.FailureKind = ovl_fail_bad_conversion;
6810       break;
6811     }
6812   }
6813 }
6814 
6815 namespace {
6816 
6817 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6818 /// candidate operator functions for built-in operators (C++
6819 /// [over.built]). The types are separated into pointer types and
6820 /// enumeration types.
6821 class BuiltinCandidateTypeSet  {
6822   /// TypeSet - A set of types.
6823   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6824                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
6825 
6826   /// PointerTypes - The set of pointer types that will be used in the
6827   /// built-in candidates.
6828   TypeSet PointerTypes;
6829 
6830   /// MemberPointerTypes - The set of member pointer types that will be
6831   /// used in the built-in candidates.
6832   TypeSet MemberPointerTypes;
6833 
6834   /// EnumerationTypes - The set of enumeration types that will be
6835   /// used in the built-in candidates.
6836   TypeSet EnumerationTypes;
6837 
6838   /// \brief The set of vector types that will be used in the built-in
6839   /// candidates.
6840   TypeSet VectorTypes;
6841 
6842   /// \brief A flag indicating non-record types are viable candidates
6843   bool HasNonRecordTypes;
6844 
6845   /// \brief A flag indicating whether either arithmetic or enumeration types
6846   /// were present in the candidate set.
6847   bool HasArithmeticOrEnumeralTypes;
6848 
6849   /// \brief A flag indicating whether the nullptr type was present in the
6850   /// candidate set.
6851   bool HasNullPtrType;
6852 
6853   /// Sema - The semantic analysis instance where we are building the
6854   /// candidate type set.
6855   Sema &SemaRef;
6856 
6857   /// Context - The AST context in which we will build the type sets.
6858   ASTContext &Context;
6859 
6860   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6861                                                const Qualifiers &VisibleQuals);
6862   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6863 
6864 public:
6865   /// iterator - Iterates through the types that are part of the set.
6866   typedef TypeSet::iterator iterator;
6867 
6868   BuiltinCandidateTypeSet(Sema &SemaRef)
6869     : HasNonRecordTypes(false),
6870       HasArithmeticOrEnumeralTypes(false),
6871       HasNullPtrType(false),
6872       SemaRef(SemaRef),
6873       Context(SemaRef.Context) { }
6874 
6875   void AddTypesConvertedFrom(QualType Ty,
6876                              SourceLocation Loc,
6877                              bool AllowUserConversions,
6878                              bool AllowExplicitConversions,
6879                              const Qualifiers &VisibleTypeConversionsQuals);
6880 
6881   /// pointer_begin - First pointer type found;
6882   iterator pointer_begin() { return PointerTypes.begin(); }
6883 
6884   /// pointer_end - Past the last pointer type found;
6885   iterator pointer_end() { return PointerTypes.end(); }
6886 
6887   /// member_pointer_begin - First member pointer type found;
6888   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6889 
6890   /// member_pointer_end - Past the last member pointer type found;
6891   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6892 
6893   /// enumeration_begin - First enumeration type found;
6894   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6895 
6896   /// enumeration_end - Past the last enumeration type found;
6897   iterator enumeration_end() { return EnumerationTypes.end(); }
6898 
6899   iterator vector_begin() { return VectorTypes.begin(); }
6900   iterator vector_end() { return VectorTypes.end(); }
6901 
6902   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6903   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6904   bool hasNullPtrType() const { return HasNullPtrType; }
6905 };
6906 
6907 } // end anonymous namespace
6908 
6909 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6910 /// the set of pointer types along with any more-qualified variants of
6911 /// that type. For example, if @p Ty is "int const *", this routine
6912 /// will add "int const *", "int const volatile *", "int const
6913 /// restrict *", and "int const volatile restrict *" to the set of
6914 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6915 /// false otherwise.
6916 ///
6917 /// FIXME: what to do about extended qualifiers?
6918 bool
6919 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6920                                              const Qualifiers &VisibleQuals) {
6921 
6922   // Insert this type.
6923   if (!PointerTypes.insert(Ty))
6924     return false;
6925 
6926   QualType PointeeTy;
6927   const PointerType *PointerTy = Ty->getAs<PointerType>();
6928   bool buildObjCPtr = false;
6929   if (!PointerTy) {
6930     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6931     PointeeTy = PTy->getPointeeType();
6932     buildObjCPtr = true;
6933   } else {
6934     PointeeTy = PointerTy->getPointeeType();
6935   }
6936 
6937   // Don't add qualified variants of arrays. For one, they're not allowed
6938   // (the qualifier would sink to the element type), and for another, the
6939   // only overload situation where it matters is subscript or pointer +- int,
6940   // and those shouldn't have qualifier variants anyway.
6941   if (PointeeTy->isArrayType())
6942     return true;
6943 
6944   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6945   bool hasVolatile = VisibleQuals.hasVolatile();
6946   bool hasRestrict = VisibleQuals.hasRestrict();
6947 
6948   // Iterate through all strict supersets of BaseCVR.
6949   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6950     if ((CVR | BaseCVR) != CVR) continue;
6951     // Skip over volatile if no volatile found anywhere in the types.
6952     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6953 
6954     // Skip over restrict if no restrict found anywhere in the types, or if
6955     // the type cannot be restrict-qualified.
6956     if ((CVR & Qualifiers::Restrict) &&
6957         (!hasRestrict ||
6958          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6959       continue;
6960 
6961     // Build qualified pointee type.
6962     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6963 
6964     // Build qualified pointer type.
6965     QualType QPointerTy;
6966     if (!buildObjCPtr)
6967       QPointerTy = Context.getPointerType(QPointeeTy);
6968     else
6969       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6970 
6971     // Insert qualified pointer type.
6972     PointerTypes.insert(QPointerTy);
6973   }
6974 
6975   return true;
6976 }
6977 
6978 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6979 /// to the set of pointer types along with any more-qualified variants of
6980 /// that type. For example, if @p Ty is "int const *", this routine
6981 /// will add "int const *", "int const volatile *", "int const
6982 /// restrict *", and "int const volatile restrict *" to the set of
6983 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6984 /// false otherwise.
6985 ///
6986 /// FIXME: what to do about extended qualifiers?
6987 bool
6988 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6989     QualType Ty) {
6990   // Insert this type.
6991   if (!MemberPointerTypes.insert(Ty))
6992     return false;
6993 
6994   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6995   assert(PointerTy && "type was not a member pointer type!");
6996 
6997   QualType PointeeTy = PointerTy->getPointeeType();
6998   // Don't add qualified variants of arrays. For one, they're not allowed
6999   // (the qualifier would sink to the element type), and for another, the
7000   // only overload situation where it matters is subscript or pointer +- int,
7001   // and those shouldn't have qualifier variants anyway.
7002   if (PointeeTy->isArrayType())
7003     return true;
7004   const Type *ClassTy = PointerTy->getClass();
7005 
7006   // Iterate through all strict supersets of the pointee type's CVR
7007   // qualifiers.
7008   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7009   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7010     if ((CVR | BaseCVR) != CVR) continue;
7011 
7012     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7013     MemberPointerTypes.insert(
7014       Context.getMemberPointerType(QPointeeTy, ClassTy));
7015   }
7016 
7017   return true;
7018 }
7019 
7020 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7021 /// Ty can be implicit converted to the given set of @p Types. We're
7022 /// primarily interested in pointer types and enumeration types. We also
7023 /// take member pointer types, for the conditional operator.
7024 /// AllowUserConversions is true if we should look at the conversion
7025 /// functions of a class type, and AllowExplicitConversions if we
7026 /// should also include the explicit conversion functions of a class
7027 /// type.
7028 void
7029 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7030                                                SourceLocation Loc,
7031                                                bool AllowUserConversions,
7032                                                bool AllowExplicitConversions,
7033                                                const Qualifiers &VisibleQuals) {
7034   // Only deal with canonical types.
7035   Ty = Context.getCanonicalType(Ty);
7036 
7037   // Look through reference types; they aren't part of the type of an
7038   // expression for the purposes of conversions.
7039   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7040     Ty = RefTy->getPointeeType();
7041 
7042   // If we're dealing with an array type, decay to the pointer.
7043   if (Ty->isArrayType())
7044     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7045 
7046   // Otherwise, we don't care about qualifiers on the type.
7047   Ty = Ty.getLocalUnqualifiedType();
7048 
7049   // Flag if we ever add a non-record type.
7050   const RecordType *TyRec = Ty->getAs<RecordType>();
7051   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7052 
7053   // Flag if we encounter an arithmetic type.
7054   HasArithmeticOrEnumeralTypes =
7055     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7056 
7057   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7058     PointerTypes.insert(Ty);
7059   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7060     // Insert our type, and its more-qualified variants, into the set
7061     // of types.
7062     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7063       return;
7064   } else if (Ty->isMemberPointerType()) {
7065     // Member pointers are far easier, since the pointee can't be converted.
7066     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7067       return;
7068   } else if (Ty->isEnumeralType()) {
7069     HasArithmeticOrEnumeralTypes = true;
7070     EnumerationTypes.insert(Ty);
7071   } else if (Ty->isVectorType()) {
7072     // We treat vector types as arithmetic types in many contexts as an
7073     // extension.
7074     HasArithmeticOrEnumeralTypes = true;
7075     VectorTypes.insert(Ty);
7076   } else if (Ty->isNullPtrType()) {
7077     HasNullPtrType = true;
7078   } else if (AllowUserConversions && TyRec) {
7079     // No conversion functions in incomplete types.
7080     if (!SemaRef.isCompleteType(Loc, Ty))
7081       return;
7082 
7083     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7084     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7085       if (isa<UsingShadowDecl>(D))
7086         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7087 
7088       // Skip conversion function templates; they don't tell us anything
7089       // about which builtin types we can convert to.
7090       if (isa<FunctionTemplateDecl>(D))
7091         continue;
7092 
7093       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7094       if (AllowExplicitConversions || !Conv->isExplicit()) {
7095         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7096                               VisibleQuals);
7097       }
7098     }
7099   }
7100 }
7101 
7102 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7103 /// the volatile- and non-volatile-qualified assignment operators for the
7104 /// given type to the candidate set.
7105 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7106                                                    QualType T,
7107                                                    ArrayRef<Expr *> Args,
7108                                     OverloadCandidateSet &CandidateSet) {
7109   QualType ParamTypes[2];
7110 
7111   // T& operator=(T&, T)
7112   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7113   ParamTypes[1] = T;
7114   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7115                         /*IsAssignmentOperator=*/true);
7116 
7117   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7118     // volatile T& operator=(volatile T&, T)
7119     ParamTypes[0]
7120       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7121     ParamTypes[1] = T;
7122     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7123                           /*IsAssignmentOperator=*/true);
7124   }
7125 }
7126 
7127 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7128 /// if any, found in visible type conversion functions found in ArgExpr's type.
7129 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7130     Qualifiers VRQuals;
7131     const RecordType *TyRec;
7132     if (const MemberPointerType *RHSMPType =
7133         ArgExpr->getType()->getAs<MemberPointerType>())
7134       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7135     else
7136       TyRec = ArgExpr->getType()->getAs<RecordType>();
7137     if (!TyRec) {
7138       // Just to be safe, assume the worst case.
7139       VRQuals.addVolatile();
7140       VRQuals.addRestrict();
7141       return VRQuals;
7142     }
7143 
7144     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7145     if (!ClassDecl->hasDefinition())
7146       return VRQuals;
7147 
7148     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7149       if (isa<UsingShadowDecl>(D))
7150         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7151       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7152         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7153         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7154           CanTy = ResTypeRef->getPointeeType();
7155         // Need to go down the pointer/mempointer chain and add qualifiers
7156         // as see them.
7157         bool done = false;
7158         while (!done) {
7159           if (CanTy.isRestrictQualified())
7160             VRQuals.addRestrict();
7161           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7162             CanTy = ResTypePtr->getPointeeType();
7163           else if (const MemberPointerType *ResTypeMPtr =
7164                 CanTy->getAs<MemberPointerType>())
7165             CanTy = ResTypeMPtr->getPointeeType();
7166           else
7167             done = true;
7168           if (CanTy.isVolatileQualified())
7169             VRQuals.addVolatile();
7170           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7171             return VRQuals;
7172         }
7173       }
7174     }
7175     return VRQuals;
7176 }
7177 
7178 namespace {
7179 
7180 /// \brief Helper class to manage the addition of builtin operator overload
7181 /// candidates. It provides shared state and utility methods used throughout
7182 /// the process, as well as a helper method to add each group of builtin
7183 /// operator overloads from the standard to a candidate set.
7184 class BuiltinOperatorOverloadBuilder {
7185   // Common instance state available to all overload candidate addition methods.
7186   Sema &S;
7187   ArrayRef<Expr *> Args;
7188   Qualifiers VisibleTypeConversionsQuals;
7189   bool HasArithmeticOrEnumeralCandidateType;
7190   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7191   OverloadCandidateSet &CandidateSet;
7192 
7193   // Define some constants used to index and iterate over the arithemetic types
7194   // provided via the getArithmeticType() method below.
7195   // The "promoted arithmetic types" are the arithmetic
7196   // types are that preserved by promotion (C++ [over.built]p2).
7197   static const unsigned FirstIntegralType = 4;
7198   static const unsigned LastIntegralType = 21;
7199   static const unsigned FirstPromotedIntegralType = 4,
7200                         LastPromotedIntegralType = 12;
7201   static const unsigned FirstPromotedArithmeticType = 0,
7202                         LastPromotedArithmeticType = 12;
7203   static const unsigned NumArithmeticTypes = 21;
7204 
7205   /// \brief Get the canonical type for a given arithmetic type index.
7206   CanQualType getArithmeticType(unsigned index) {
7207     assert(index < NumArithmeticTypes);
7208     static CanQualType ASTContext::* const
7209       ArithmeticTypes[NumArithmeticTypes] = {
7210       // Start of promoted types.
7211       &ASTContext::FloatTy,
7212       &ASTContext::DoubleTy,
7213       &ASTContext::LongDoubleTy,
7214       &ASTContext::Float128Ty,
7215 
7216       // Start of integral types.
7217       &ASTContext::IntTy,
7218       &ASTContext::LongTy,
7219       &ASTContext::LongLongTy,
7220       &ASTContext::Int128Ty,
7221       &ASTContext::UnsignedIntTy,
7222       &ASTContext::UnsignedLongTy,
7223       &ASTContext::UnsignedLongLongTy,
7224       &ASTContext::UnsignedInt128Ty,
7225       // End of promoted types.
7226 
7227       &ASTContext::BoolTy,
7228       &ASTContext::CharTy,
7229       &ASTContext::WCharTy,
7230       &ASTContext::Char16Ty,
7231       &ASTContext::Char32Ty,
7232       &ASTContext::SignedCharTy,
7233       &ASTContext::ShortTy,
7234       &ASTContext::UnsignedCharTy,
7235       &ASTContext::UnsignedShortTy,
7236       // End of integral types.
7237       // FIXME: What about complex? What about half?
7238     };
7239     return S.Context.*ArithmeticTypes[index];
7240   }
7241 
7242   /// \brief Gets the canonical type resulting from the usual arithemetic
7243   /// converions for the given arithmetic types.
7244   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7245     // Accelerator table for performing the usual arithmetic conversions.
7246     // The rules are basically:
7247     //   - if either is floating-point, use the wider floating-point
7248     //   - if same signedness, use the higher rank
7249     //   - if same size, use unsigned of the higher rank
7250     //   - use the larger type
7251     // These rules, together with the axiom that higher ranks are
7252     // never smaller, are sufficient to precompute all of these results
7253     // *except* when dealing with signed types of higher rank.
7254     // (we could precompute SLL x UI for all known platforms, but it's
7255     // better not to make any assumptions).
7256     // We assume that int128 has a higher rank than long long on all platforms.
7257     enum PromotedType : int8_t {
7258             Dep=-1,
7259             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7260     };
7261     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7262                                         [LastPromotedArithmeticType] = {
7263 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7264 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7265 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7266 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7267 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7268 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7269 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7270 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7271 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7272 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7273 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7274     };
7275 
7276     assert(L < LastPromotedArithmeticType);
7277     assert(R < LastPromotedArithmeticType);
7278     int Idx = ConversionsTable[L][R];
7279 
7280     // Fast path: the table gives us a concrete answer.
7281     if (Idx != Dep) return getArithmeticType(Idx);
7282 
7283     // Slow path: we need to compare widths.
7284     // An invariant is that the signed type has higher rank.
7285     CanQualType LT = getArithmeticType(L),
7286                 RT = getArithmeticType(R);
7287     unsigned LW = S.Context.getIntWidth(LT),
7288              RW = S.Context.getIntWidth(RT);
7289 
7290     // If they're different widths, use the signed type.
7291     if (LW > RW) return LT;
7292     else if (LW < RW) return RT;
7293 
7294     // Otherwise, use the unsigned type of the signed type's rank.
7295     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7296     assert(L == SLL || R == SLL);
7297     return S.Context.UnsignedLongLongTy;
7298   }
7299 
7300   /// \brief Helper method to factor out the common pattern of adding overloads
7301   /// for '++' and '--' builtin operators.
7302   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7303                                            bool HasVolatile,
7304                                            bool HasRestrict) {
7305     QualType ParamTypes[2] = {
7306       S.Context.getLValueReferenceType(CandidateTy),
7307       S.Context.IntTy
7308     };
7309 
7310     // Non-volatile version.
7311     if (Args.size() == 1)
7312       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7313     else
7314       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7315 
7316     // Use a heuristic to reduce number of builtin candidates in the set:
7317     // add volatile version only if there are conversions to a volatile type.
7318     if (HasVolatile) {
7319       ParamTypes[0] =
7320         S.Context.getLValueReferenceType(
7321           S.Context.getVolatileType(CandidateTy));
7322       if (Args.size() == 1)
7323         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7324       else
7325         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7326     }
7327 
7328     // Add restrict version only if there are conversions to a restrict type
7329     // and our candidate type is a non-restrict-qualified pointer.
7330     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7331         !CandidateTy.isRestrictQualified()) {
7332       ParamTypes[0]
7333         = S.Context.getLValueReferenceType(
7334             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7335       if (Args.size() == 1)
7336         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7337       else
7338         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7339 
7340       if (HasVolatile) {
7341         ParamTypes[0]
7342           = S.Context.getLValueReferenceType(
7343               S.Context.getCVRQualifiedType(CandidateTy,
7344                                             (Qualifiers::Volatile |
7345                                              Qualifiers::Restrict)));
7346         if (Args.size() == 1)
7347           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7348         else
7349           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7350       }
7351     }
7352 
7353   }
7354 
7355 public:
7356   BuiltinOperatorOverloadBuilder(
7357     Sema &S, ArrayRef<Expr *> Args,
7358     Qualifiers VisibleTypeConversionsQuals,
7359     bool HasArithmeticOrEnumeralCandidateType,
7360     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7361     OverloadCandidateSet &CandidateSet)
7362     : S(S), Args(Args),
7363       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7364       HasArithmeticOrEnumeralCandidateType(
7365         HasArithmeticOrEnumeralCandidateType),
7366       CandidateTypes(CandidateTypes),
7367       CandidateSet(CandidateSet) {
7368     // Validate some of our static helper constants in debug builds.
7369     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7370            "Invalid first promoted integral type");
7371     assert(getArithmeticType(LastPromotedIntegralType - 1)
7372              == S.Context.UnsignedInt128Ty &&
7373            "Invalid last promoted integral type");
7374     assert(getArithmeticType(FirstPromotedArithmeticType)
7375              == S.Context.FloatTy &&
7376            "Invalid first promoted arithmetic type");
7377     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7378              == S.Context.UnsignedInt128Ty &&
7379            "Invalid last promoted arithmetic type");
7380   }
7381 
7382   // C++ [over.built]p3:
7383   //
7384   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7385   //   is either volatile or empty, there exist candidate operator
7386   //   functions of the form
7387   //
7388   //       VQ T&      operator++(VQ T&);
7389   //       T          operator++(VQ T&, int);
7390   //
7391   // C++ [over.built]p4:
7392   //
7393   //   For every pair (T, VQ), where T is an arithmetic type other
7394   //   than bool, and VQ is either volatile or empty, there exist
7395   //   candidate operator functions of the form
7396   //
7397   //       VQ T&      operator--(VQ T&);
7398   //       T          operator--(VQ T&, int);
7399   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7400     if (!HasArithmeticOrEnumeralCandidateType)
7401       return;
7402 
7403     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7404          Arith < NumArithmeticTypes; ++Arith) {
7405       addPlusPlusMinusMinusStyleOverloads(
7406         getArithmeticType(Arith),
7407         VisibleTypeConversionsQuals.hasVolatile(),
7408         VisibleTypeConversionsQuals.hasRestrict());
7409     }
7410   }
7411 
7412   // C++ [over.built]p5:
7413   //
7414   //   For every pair (T, VQ), where T is a cv-qualified or
7415   //   cv-unqualified object type, and VQ is either volatile or
7416   //   empty, there exist candidate operator functions of the form
7417   //
7418   //       T*VQ&      operator++(T*VQ&);
7419   //       T*VQ&      operator--(T*VQ&);
7420   //       T*         operator++(T*VQ&, int);
7421   //       T*         operator--(T*VQ&, int);
7422   void addPlusPlusMinusMinusPointerOverloads() {
7423     for (BuiltinCandidateTypeSet::iterator
7424               Ptr = CandidateTypes[0].pointer_begin(),
7425            PtrEnd = CandidateTypes[0].pointer_end();
7426          Ptr != PtrEnd; ++Ptr) {
7427       // Skip pointer types that aren't pointers to object types.
7428       if (!(*Ptr)->getPointeeType()->isObjectType())
7429         continue;
7430 
7431       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7432         (!(*Ptr).isVolatileQualified() &&
7433          VisibleTypeConversionsQuals.hasVolatile()),
7434         (!(*Ptr).isRestrictQualified() &&
7435          VisibleTypeConversionsQuals.hasRestrict()));
7436     }
7437   }
7438 
7439   // C++ [over.built]p6:
7440   //   For every cv-qualified or cv-unqualified object type T, there
7441   //   exist candidate operator functions of the form
7442   //
7443   //       T&         operator*(T*);
7444   //
7445   // C++ [over.built]p7:
7446   //   For every function type T that does not have cv-qualifiers or a
7447   //   ref-qualifier, there exist candidate operator functions of the form
7448   //       T&         operator*(T*);
7449   void addUnaryStarPointerOverloads() {
7450     for (BuiltinCandidateTypeSet::iterator
7451               Ptr = CandidateTypes[0].pointer_begin(),
7452            PtrEnd = CandidateTypes[0].pointer_end();
7453          Ptr != PtrEnd; ++Ptr) {
7454       QualType ParamTy = *Ptr;
7455       QualType PointeeTy = ParamTy->getPointeeType();
7456       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7457         continue;
7458 
7459       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7460         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7461           continue;
7462 
7463       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7464                             &ParamTy, Args, CandidateSet);
7465     }
7466   }
7467 
7468   // C++ [over.built]p9:
7469   //  For every promoted arithmetic type T, there exist candidate
7470   //  operator functions of the form
7471   //
7472   //       T         operator+(T);
7473   //       T         operator-(T);
7474   void addUnaryPlusOrMinusArithmeticOverloads() {
7475     if (!HasArithmeticOrEnumeralCandidateType)
7476       return;
7477 
7478     for (unsigned Arith = FirstPromotedArithmeticType;
7479          Arith < LastPromotedArithmeticType; ++Arith) {
7480       QualType ArithTy = getArithmeticType(Arith);
7481       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7482     }
7483 
7484     // Extension: We also add these operators for vector types.
7485     for (BuiltinCandidateTypeSet::iterator
7486               Vec = CandidateTypes[0].vector_begin(),
7487            VecEnd = CandidateTypes[0].vector_end();
7488          Vec != VecEnd; ++Vec) {
7489       QualType VecTy = *Vec;
7490       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7491     }
7492   }
7493 
7494   // C++ [over.built]p8:
7495   //   For every type T, there exist candidate operator functions of
7496   //   the form
7497   //
7498   //       T*         operator+(T*);
7499   void addUnaryPlusPointerOverloads() {
7500     for (BuiltinCandidateTypeSet::iterator
7501               Ptr = CandidateTypes[0].pointer_begin(),
7502            PtrEnd = CandidateTypes[0].pointer_end();
7503          Ptr != PtrEnd; ++Ptr) {
7504       QualType ParamTy = *Ptr;
7505       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7506     }
7507   }
7508 
7509   // C++ [over.built]p10:
7510   //   For every promoted integral type T, there exist candidate
7511   //   operator functions of the form
7512   //
7513   //        T         operator~(T);
7514   void addUnaryTildePromotedIntegralOverloads() {
7515     if (!HasArithmeticOrEnumeralCandidateType)
7516       return;
7517 
7518     for (unsigned Int = FirstPromotedIntegralType;
7519          Int < LastPromotedIntegralType; ++Int) {
7520       QualType IntTy = getArithmeticType(Int);
7521       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7522     }
7523 
7524     // Extension: We also add this operator for vector types.
7525     for (BuiltinCandidateTypeSet::iterator
7526               Vec = CandidateTypes[0].vector_begin(),
7527            VecEnd = CandidateTypes[0].vector_end();
7528          Vec != VecEnd; ++Vec) {
7529       QualType VecTy = *Vec;
7530       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7531     }
7532   }
7533 
7534   // C++ [over.match.oper]p16:
7535   //   For every pointer to member type T, there exist candidate operator
7536   //   functions of the form
7537   //
7538   //        bool operator==(T,T);
7539   //        bool operator!=(T,T);
7540   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7541     /// Set of (canonical) types that we've already handled.
7542     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7543 
7544     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7545       for (BuiltinCandidateTypeSet::iterator
7546                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7547              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7548            MemPtr != MemPtrEnd;
7549            ++MemPtr) {
7550         // Don't add the same builtin candidate twice.
7551         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7552           continue;
7553 
7554         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7555         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7556       }
7557     }
7558   }
7559 
7560   // C++ [over.built]p15:
7561   //
7562   //   For every T, where T is an enumeration type, a pointer type, or
7563   //   std::nullptr_t, there exist candidate operator functions of the form
7564   //
7565   //        bool       operator<(T, T);
7566   //        bool       operator>(T, T);
7567   //        bool       operator<=(T, T);
7568   //        bool       operator>=(T, T);
7569   //        bool       operator==(T, T);
7570   //        bool       operator!=(T, T);
7571   void addRelationalPointerOrEnumeralOverloads() {
7572     // C++ [over.match.oper]p3:
7573     //   [...]the built-in candidates include all of the candidate operator
7574     //   functions defined in 13.6 that, compared to the given operator, [...]
7575     //   do not have the same parameter-type-list as any non-template non-member
7576     //   candidate.
7577     //
7578     // Note that in practice, this only affects enumeration types because there
7579     // aren't any built-in candidates of record type, and a user-defined operator
7580     // must have an operand of record or enumeration type. Also, the only other
7581     // overloaded operator with enumeration arguments, operator=,
7582     // cannot be overloaded for enumeration types, so this is the only place
7583     // where we must suppress candidates like this.
7584     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7585       UserDefinedBinaryOperators;
7586 
7587     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7588       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7589           CandidateTypes[ArgIdx].enumeration_end()) {
7590         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7591                                          CEnd = CandidateSet.end();
7592              C != CEnd; ++C) {
7593           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7594             continue;
7595 
7596           if (C->Function->isFunctionTemplateSpecialization())
7597             continue;
7598 
7599           QualType FirstParamType =
7600             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7601           QualType SecondParamType =
7602             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7603 
7604           // Skip if either parameter isn't of enumeral type.
7605           if (!FirstParamType->isEnumeralType() ||
7606               !SecondParamType->isEnumeralType())
7607             continue;
7608 
7609           // Add this operator to the set of known user-defined operators.
7610           UserDefinedBinaryOperators.insert(
7611             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7612                            S.Context.getCanonicalType(SecondParamType)));
7613         }
7614       }
7615     }
7616 
7617     /// Set of (canonical) types that we've already handled.
7618     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7619 
7620     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7621       for (BuiltinCandidateTypeSet::iterator
7622                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7623              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7624            Ptr != PtrEnd; ++Ptr) {
7625         // Don't add the same builtin candidate twice.
7626         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7627           continue;
7628 
7629         QualType ParamTypes[2] = { *Ptr, *Ptr };
7630         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7631       }
7632       for (BuiltinCandidateTypeSet::iterator
7633                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7634              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7635            Enum != EnumEnd; ++Enum) {
7636         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7637 
7638         // Don't add the same builtin candidate twice, or if a user defined
7639         // candidate exists.
7640         if (!AddedTypes.insert(CanonType).second ||
7641             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7642                                                             CanonType)))
7643           continue;
7644 
7645         QualType ParamTypes[2] = { *Enum, *Enum };
7646         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7647       }
7648 
7649       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7650         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7651         if (AddedTypes.insert(NullPtrTy).second &&
7652             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7653                                                              NullPtrTy))) {
7654           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7655           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7656                                 CandidateSet);
7657         }
7658       }
7659     }
7660   }
7661 
7662   // C++ [over.built]p13:
7663   //
7664   //   For every cv-qualified or cv-unqualified object type T
7665   //   there exist candidate operator functions of the form
7666   //
7667   //      T*         operator+(T*, ptrdiff_t);
7668   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7669   //      T*         operator-(T*, ptrdiff_t);
7670   //      T*         operator+(ptrdiff_t, T*);
7671   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7672   //
7673   // C++ [over.built]p14:
7674   //
7675   //   For every T, where T is a pointer to object type, there
7676   //   exist candidate operator functions of the form
7677   //
7678   //      ptrdiff_t  operator-(T, T);
7679   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7680     /// Set of (canonical) types that we've already handled.
7681     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7682 
7683     for (int Arg = 0; Arg < 2; ++Arg) {
7684       QualType AsymmetricParamTypes[2] = {
7685         S.Context.getPointerDiffType(),
7686         S.Context.getPointerDiffType(),
7687       };
7688       for (BuiltinCandidateTypeSet::iterator
7689                 Ptr = CandidateTypes[Arg].pointer_begin(),
7690              PtrEnd = CandidateTypes[Arg].pointer_end();
7691            Ptr != PtrEnd; ++Ptr) {
7692         QualType PointeeTy = (*Ptr)->getPointeeType();
7693         if (!PointeeTy->isObjectType())
7694           continue;
7695 
7696         AsymmetricParamTypes[Arg] = *Ptr;
7697         if (Arg == 0 || Op == OO_Plus) {
7698           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7699           // T* operator+(ptrdiff_t, T*);
7700           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7701         }
7702         if (Op == OO_Minus) {
7703           // ptrdiff_t operator-(T, T);
7704           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7705             continue;
7706 
7707           QualType ParamTypes[2] = { *Ptr, *Ptr };
7708           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7709                                 Args, CandidateSet);
7710         }
7711       }
7712     }
7713   }
7714 
7715   // C++ [over.built]p12:
7716   //
7717   //   For every pair of promoted arithmetic types L and R, there
7718   //   exist candidate operator functions of the form
7719   //
7720   //        LR         operator*(L, R);
7721   //        LR         operator/(L, R);
7722   //        LR         operator+(L, R);
7723   //        LR         operator-(L, R);
7724   //        bool       operator<(L, R);
7725   //        bool       operator>(L, R);
7726   //        bool       operator<=(L, R);
7727   //        bool       operator>=(L, R);
7728   //        bool       operator==(L, R);
7729   //        bool       operator!=(L, R);
7730   //
7731   //   where LR is the result of the usual arithmetic conversions
7732   //   between types L and R.
7733   //
7734   // C++ [over.built]p24:
7735   //
7736   //   For every pair of promoted arithmetic types L and R, there exist
7737   //   candidate operator functions of the form
7738   //
7739   //        LR       operator?(bool, L, R);
7740   //
7741   //   where LR is the result of the usual arithmetic conversions
7742   //   between types L and R.
7743   // Our candidates ignore the first parameter.
7744   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7745     if (!HasArithmeticOrEnumeralCandidateType)
7746       return;
7747 
7748     for (unsigned Left = FirstPromotedArithmeticType;
7749          Left < LastPromotedArithmeticType; ++Left) {
7750       for (unsigned Right = FirstPromotedArithmeticType;
7751            Right < LastPromotedArithmeticType; ++Right) {
7752         QualType LandR[2] = { getArithmeticType(Left),
7753                               getArithmeticType(Right) };
7754         QualType Result =
7755           isComparison ? S.Context.BoolTy
7756                        : getUsualArithmeticConversions(Left, Right);
7757         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7758       }
7759     }
7760 
7761     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7762     // conditional operator for vector types.
7763     for (BuiltinCandidateTypeSet::iterator
7764               Vec1 = CandidateTypes[0].vector_begin(),
7765            Vec1End = CandidateTypes[0].vector_end();
7766          Vec1 != Vec1End; ++Vec1) {
7767       for (BuiltinCandidateTypeSet::iterator
7768                 Vec2 = CandidateTypes[1].vector_begin(),
7769              Vec2End = CandidateTypes[1].vector_end();
7770            Vec2 != Vec2End; ++Vec2) {
7771         QualType LandR[2] = { *Vec1, *Vec2 };
7772         QualType Result = S.Context.BoolTy;
7773         if (!isComparison) {
7774           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7775             Result = *Vec1;
7776           else
7777             Result = *Vec2;
7778         }
7779 
7780         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7781       }
7782     }
7783   }
7784 
7785   // C++ [over.built]p17:
7786   //
7787   //   For every pair of promoted integral types L and R, there
7788   //   exist candidate operator functions of the form
7789   //
7790   //      LR         operator%(L, R);
7791   //      LR         operator&(L, R);
7792   //      LR         operator^(L, R);
7793   //      LR         operator|(L, R);
7794   //      L          operator<<(L, R);
7795   //      L          operator>>(L, R);
7796   //
7797   //   where LR is the result of the usual arithmetic conversions
7798   //   between types L and R.
7799   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7800     if (!HasArithmeticOrEnumeralCandidateType)
7801       return;
7802 
7803     for (unsigned Left = FirstPromotedIntegralType;
7804          Left < LastPromotedIntegralType; ++Left) {
7805       for (unsigned Right = FirstPromotedIntegralType;
7806            Right < LastPromotedIntegralType; ++Right) {
7807         QualType LandR[2] = { getArithmeticType(Left),
7808                               getArithmeticType(Right) };
7809         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7810             ? LandR[0]
7811             : getUsualArithmeticConversions(Left, Right);
7812         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7813       }
7814     }
7815   }
7816 
7817   // C++ [over.built]p20:
7818   //
7819   //   For every pair (T, VQ), where T is an enumeration or
7820   //   pointer to member type and VQ is either volatile or
7821   //   empty, there exist candidate operator functions of the form
7822   //
7823   //        VQ T&      operator=(VQ T&, T);
7824   void addAssignmentMemberPointerOrEnumeralOverloads() {
7825     /// Set of (canonical) types that we've already handled.
7826     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7827 
7828     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7829       for (BuiltinCandidateTypeSet::iterator
7830                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7831              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7832            Enum != EnumEnd; ++Enum) {
7833         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7834           continue;
7835 
7836         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7837       }
7838 
7839       for (BuiltinCandidateTypeSet::iterator
7840                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7841              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7842            MemPtr != MemPtrEnd; ++MemPtr) {
7843         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7844           continue;
7845 
7846         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7847       }
7848     }
7849   }
7850 
7851   // C++ [over.built]p19:
7852   //
7853   //   For every pair (T, VQ), where T is any type and VQ is either
7854   //   volatile or empty, there exist candidate operator functions
7855   //   of the form
7856   //
7857   //        T*VQ&      operator=(T*VQ&, T*);
7858   //
7859   // C++ [over.built]p21:
7860   //
7861   //   For every pair (T, VQ), where T is a cv-qualified or
7862   //   cv-unqualified object type and VQ is either volatile or
7863   //   empty, there exist candidate operator functions of the form
7864   //
7865   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7866   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7867   void addAssignmentPointerOverloads(bool isEqualOp) {
7868     /// Set of (canonical) types that we've already handled.
7869     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7870 
7871     for (BuiltinCandidateTypeSet::iterator
7872               Ptr = CandidateTypes[0].pointer_begin(),
7873            PtrEnd = CandidateTypes[0].pointer_end();
7874          Ptr != PtrEnd; ++Ptr) {
7875       // If this is operator=, keep track of the builtin candidates we added.
7876       if (isEqualOp)
7877         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7878       else if (!(*Ptr)->getPointeeType()->isObjectType())
7879         continue;
7880 
7881       // non-volatile version
7882       QualType ParamTypes[2] = {
7883         S.Context.getLValueReferenceType(*Ptr),
7884         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7885       };
7886       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7887                             /*IsAssigmentOperator=*/ isEqualOp);
7888 
7889       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7890                           VisibleTypeConversionsQuals.hasVolatile();
7891       if (NeedVolatile) {
7892         // volatile version
7893         ParamTypes[0] =
7894           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7895         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7896                               /*IsAssigmentOperator=*/isEqualOp);
7897       }
7898 
7899       if (!(*Ptr).isRestrictQualified() &&
7900           VisibleTypeConversionsQuals.hasRestrict()) {
7901         // restrict version
7902         ParamTypes[0]
7903           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7904         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7905                               /*IsAssigmentOperator=*/isEqualOp);
7906 
7907         if (NeedVolatile) {
7908           // volatile restrict version
7909           ParamTypes[0]
7910             = S.Context.getLValueReferenceType(
7911                 S.Context.getCVRQualifiedType(*Ptr,
7912                                               (Qualifiers::Volatile |
7913                                                Qualifiers::Restrict)));
7914           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7915                                 /*IsAssigmentOperator=*/isEqualOp);
7916         }
7917       }
7918     }
7919 
7920     if (isEqualOp) {
7921       for (BuiltinCandidateTypeSet::iterator
7922                 Ptr = CandidateTypes[1].pointer_begin(),
7923              PtrEnd = CandidateTypes[1].pointer_end();
7924            Ptr != PtrEnd; ++Ptr) {
7925         // Make sure we don't add the same candidate twice.
7926         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7927           continue;
7928 
7929         QualType ParamTypes[2] = {
7930           S.Context.getLValueReferenceType(*Ptr),
7931           *Ptr,
7932         };
7933 
7934         // non-volatile version
7935         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7936                               /*IsAssigmentOperator=*/true);
7937 
7938         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7939                            VisibleTypeConversionsQuals.hasVolatile();
7940         if (NeedVolatile) {
7941           // volatile version
7942           ParamTypes[0] =
7943             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7944           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7945                                 /*IsAssigmentOperator=*/true);
7946         }
7947 
7948         if (!(*Ptr).isRestrictQualified() &&
7949             VisibleTypeConversionsQuals.hasRestrict()) {
7950           // restrict version
7951           ParamTypes[0]
7952             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7953           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7954                                 /*IsAssigmentOperator=*/true);
7955 
7956           if (NeedVolatile) {
7957             // volatile restrict version
7958             ParamTypes[0]
7959               = S.Context.getLValueReferenceType(
7960                   S.Context.getCVRQualifiedType(*Ptr,
7961                                                 (Qualifiers::Volatile |
7962                                                  Qualifiers::Restrict)));
7963             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7964                                   /*IsAssigmentOperator=*/true);
7965           }
7966         }
7967       }
7968     }
7969   }
7970 
7971   // C++ [over.built]p18:
7972   //
7973   //   For every triple (L, VQ, R), where L is an arithmetic type,
7974   //   VQ is either volatile or empty, and R is a promoted
7975   //   arithmetic type, there exist candidate operator functions of
7976   //   the form
7977   //
7978   //        VQ L&      operator=(VQ L&, R);
7979   //        VQ L&      operator*=(VQ L&, R);
7980   //        VQ L&      operator/=(VQ L&, R);
7981   //        VQ L&      operator+=(VQ L&, R);
7982   //        VQ L&      operator-=(VQ L&, R);
7983   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7984     if (!HasArithmeticOrEnumeralCandidateType)
7985       return;
7986 
7987     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7988       for (unsigned Right = FirstPromotedArithmeticType;
7989            Right < LastPromotedArithmeticType; ++Right) {
7990         QualType ParamTypes[2];
7991         ParamTypes[1] = getArithmeticType(Right);
7992 
7993         // Add this built-in operator as a candidate (VQ is empty).
7994         ParamTypes[0] =
7995           S.Context.getLValueReferenceType(getArithmeticType(Left));
7996         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7997                               /*IsAssigmentOperator=*/isEqualOp);
7998 
7999         // Add this built-in operator as a candidate (VQ is 'volatile').
8000         if (VisibleTypeConversionsQuals.hasVolatile()) {
8001           ParamTypes[0] =
8002             S.Context.getVolatileType(getArithmeticType(Left));
8003           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8004           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8005                                 /*IsAssigmentOperator=*/isEqualOp);
8006         }
8007       }
8008     }
8009 
8010     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8011     for (BuiltinCandidateTypeSet::iterator
8012               Vec1 = CandidateTypes[0].vector_begin(),
8013            Vec1End = CandidateTypes[0].vector_end();
8014          Vec1 != Vec1End; ++Vec1) {
8015       for (BuiltinCandidateTypeSet::iterator
8016                 Vec2 = CandidateTypes[1].vector_begin(),
8017              Vec2End = CandidateTypes[1].vector_end();
8018            Vec2 != Vec2End; ++Vec2) {
8019         QualType ParamTypes[2];
8020         ParamTypes[1] = *Vec2;
8021         // Add this built-in operator as a candidate (VQ is empty).
8022         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8023         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8024                               /*IsAssigmentOperator=*/isEqualOp);
8025 
8026         // Add this built-in operator as a candidate (VQ is 'volatile').
8027         if (VisibleTypeConversionsQuals.hasVolatile()) {
8028           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8029           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8030           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8031                                 /*IsAssigmentOperator=*/isEqualOp);
8032         }
8033       }
8034     }
8035   }
8036 
8037   // C++ [over.built]p22:
8038   //
8039   //   For every triple (L, VQ, R), where L is an integral type, VQ
8040   //   is either volatile or empty, and R is a promoted integral
8041   //   type, there exist candidate operator functions of the form
8042   //
8043   //        VQ L&       operator%=(VQ L&, R);
8044   //        VQ L&       operator<<=(VQ L&, R);
8045   //        VQ L&       operator>>=(VQ L&, R);
8046   //        VQ L&       operator&=(VQ L&, R);
8047   //        VQ L&       operator^=(VQ L&, R);
8048   //        VQ L&       operator|=(VQ L&, R);
8049   void addAssignmentIntegralOverloads() {
8050     if (!HasArithmeticOrEnumeralCandidateType)
8051       return;
8052 
8053     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8054       for (unsigned Right = FirstPromotedIntegralType;
8055            Right < LastPromotedIntegralType; ++Right) {
8056         QualType ParamTypes[2];
8057         ParamTypes[1] = getArithmeticType(Right);
8058 
8059         // Add this built-in operator as a candidate (VQ is empty).
8060         ParamTypes[0] =
8061           S.Context.getLValueReferenceType(getArithmeticType(Left));
8062         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8063         if (VisibleTypeConversionsQuals.hasVolatile()) {
8064           // Add this built-in operator as a candidate (VQ is 'volatile').
8065           ParamTypes[0] = getArithmeticType(Left);
8066           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8067           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8068           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8069         }
8070       }
8071     }
8072   }
8073 
8074   // C++ [over.operator]p23:
8075   //
8076   //   There also exist candidate operator functions of the form
8077   //
8078   //        bool        operator!(bool);
8079   //        bool        operator&&(bool, bool);
8080   //        bool        operator||(bool, bool);
8081   void addExclaimOverload() {
8082     QualType ParamTy = S.Context.BoolTy;
8083     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8084                           /*IsAssignmentOperator=*/false,
8085                           /*NumContextualBoolArguments=*/1);
8086   }
8087   void addAmpAmpOrPipePipeOverload() {
8088     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8089     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8090                           /*IsAssignmentOperator=*/false,
8091                           /*NumContextualBoolArguments=*/2);
8092   }
8093 
8094   // C++ [over.built]p13:
8095   //
8096   //   For every cv-qualified or cv-unqualified object type T there
8097   //   exist candidate operator functions of the form
8098   //
8099   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8100   //        T&         operator[](T*, ptrdiff_t);
8101   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8102   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8103   //        T&         operator[](ptrdiff_t, T*);
8104   void addSubscriptOverloads() {
8105     for (BuiltinCandidateTypeSet::iterator
8106               Ptr = CandidateTypes[0].pointer_begin(),
8107            PtrEnd = CandidateTypes[0].pointer_end();
8108          Ptr != PtrEnd; ++Ptr) {
8109       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8110       QualType PointeeType = (*Ptr)->getPointeeType();
8111       if (!PointeeType->isObjectType())
8112         continue;
8113 
8114       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8115 
8116       // T& operator[](T*, ptrdiff_t)
8117       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8118     }
8119 
8120     for (BuiltinCandidateTypeSet::iterator
8121               Ptr = CandidateTypes[1].pointer_begin(),
8122            PtrEnd = CandidateTypes[1].pointer_end();
8123          Ptr != PtrEnd; ++Ptr) {
8124       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8125       QualType PointeeType = (*Ptr)->getPointeeType();
8126       if (!PointeeType->isObjectType())
8127         continue;
8128 
8129       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8130 
8131       // T& operator[](ptrdiff_t, T*)
8132       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8133     }
8134   }
8135 
8136   // C++ [over.built]p11:
8137   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8138   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8139   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8140   //    there exist candidate operator functions of the form
8141   //
8142   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8143   //
8144   //    where CV12 is the union of CV1 and CV2.
8145   void addArrowStarOverloads() {
8146     for (BuiltinCandidateTypeSet::iterator
8147              Ptr = CandidateTypes[0].pointer_begin(),
8148            PtrEnd = CandidateTypes[0].pointer_end();
8149          Ptr != PtrEnd; ++Ptr) {
8150       QualType C1Ty = (*Ptr);
8151       QualType C1;
8152       QualifierCollector Q1;
8153       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8154       if (!isa<RecordType>(C1))
8155         continue;
8156       // heuristic to reduce number of builtin candidates in the set.
8157       // Add volatile/restrict version only if there are conversions to a
8158       // volatile/restrict type.
8159       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8160         continue;
8161       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8162         continue;
8163       for (BuiltinCandidateTypeSet::iterator
8164                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8165              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8166            MemPtr != MemPtrEnd; ++MemPtr) {
8167         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8168         QualType C2 = QualType(mptr->getClass(), 0);
8169         C2 = C2.getUnqualifiedType();
8170         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8171           break;
8172         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8173         // build CV12 T&
8174         QualType T = mptr->getPointeeType();
8175         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8176             T.isVolatileQualified())
8177           continue;
8178         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8179             T.isRestrictQualified())
8180           continue;
8181         T = Q1.apply(S.Context, T);
8182         QualType ResultTy = S.Context.getLValueReferenceType(T);
8183         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8184       }
8185     }
8186   }
8187 
8188   // Note that we don't consider the first argument, since it has been
8189   // contextually converted to bool long ago. The candidates below are
8190   // therefore added as binary.
8191   //
8192   // C++ [over.built]p25:
8193   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8194   //   enumeration type, there exist candidate operator functions of the form
8195   //
8196   //        T        operator?(bool, T, T);
8197   //
8198   void addConditionalOperatorOverloads() {
8199     /// Set of (canonical) types that we've already handled.
8200     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8201 
8202     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8203       for (BuiltinCandidateTypeSet::iterator
8204                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8205              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8206            Ptr != PtrEnd; ++Ptr) {
8207         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8208           continue;
8209 
8210         QualType ParamTypes[2] = { *Ptr, *Ptr };
8211         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8212       }
8213 
8214       for (BuiltinCandidateTypeSet::iterator
8215                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8216              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8217            MemPtr != MemPtrEnd; ++MemPtr) {
8218         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8219           continue;
8220 
8221         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8222         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8223       }
8224 
8225       if (S.getLangOpts().CPlusPlus11) {
8226         for (BuiltinCandidateTypeSet::iterator
8227                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8228                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8229              Enum != EnumEnd; ++Enum) {
8230           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8231             continue;
8232 
8233           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8234             continue;
8235 
8236           QualType ParamTypes[2] = { *Enum, *Enum };
8237           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8238         }
8239       }
8240     }
8241   }
8242 };
8243 
8244 } // end anonymous namespace
8245 
8246 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8247 /// operator overloads to the candidate set (C++ [over.built]), based
8248 /// on the operator @p Op and the arguments given. For example, if the
8249 /// operator is a binary '+', this routine might add "int
8250 /// operator+(int, int)" to cover integer addition.
8251 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8252                                         SourceLocation OpLoc,
8253                                         ArrayRef<Expr *> Args,
8254                                         OverloadCandidateSet &CandidateSet) {
8255   // Find all of the types that the arguments can convert to, but only
8256   // if the operator we're looking at has built-in operator candidates
8257   // that make use of these types. Also record whether we encounter non-record
8258   // candidate types or either arithmetic or enumeral candidate types.
8259   Qualifiers VisibleTypeConversionsQuals;
8260   VisibleTypeConversionsQuals.addConst();
8261   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8262     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8263 
8264   bool HasNonRecordCandidateType = false;
8265   bool HasArithmeticOrEnumeralCandidateType = false;
8266   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8267   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8268     CandidateTypes.emplace_back(*this);
8269     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8270                                                  OpLoc,
8271                                                  true,
8272                                                  (Op == OO_Exclaim ||
8273                                                   Op == OO_AmpAmp ||
8274                                                   Op == OO_PipePipe),
8275                                                  VisibleTypeConversionsQuals);
8276     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8277         CandidateTypes[ArgIdx].hasNonRecordTypes();
8278     HasArithmeticOrEnumeralCandidateType =
8279         HasArithmeticOrEnumeralCandidateType ||
8280         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8281   }
8282 
8283   // Exit early when no non-record types have been added to the candidate set
8284   // for any of the arguments to the operator.
8285   //
8286   // We can't exit early for !, ||, or &&, since there we have always have
8287   // 'bool' overloads.
8288   if (!HasNonRecordCandidateType &&
8289       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8290     return;
8291 
8292   // Setup an object to manage the common state for building overloads.
8293   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8294                                            VisibleTypeConversionsQuals,
8295                                            HasArithmeticOrEnumeralCandidateType,
8296                                            CandidateTypes, CandidateSet);
8297 
8298   // Dispatch over the operation to add in only those overloads which apply.
8299   switch (Op) {
8300   case OO_None:
8301   case NUM_OVERLOADED_OPERATORS:
8302     llvm_unreachable("Expected an overloaded operator");
8303 
8304   case OO_New:
8305   case OO_Delete:
8306   case OO_Array_New:
8307   case OO_Array_Delete:
8308   case OO_Call:
8309     llvm_unreachable(
8310                     "Special operators don't use AddBuiltinOperatorCandidates");
8311 
8312   case OO_Comma:
8313   case OO_Arrow:
8314   case OO_Coawait:
8315     // C++ [over.match.oper]p3:
8316     //   -- For the operator ',', the unary operator '&', the
8317     //      operator '->', or the operator 'co_await', the
8318     //      built-in candidates set is empty.
8319     break;
8320 
8321   case OO_Plus: // '+' is either unary or binary
8322     if (Args.size() == 1)
8323       OpBuilder.addUnaryPlusPointerOverloads();
8324     // Fall through.
8325 
8326   case OO_Minus: // '-' is either unary or binary
8327     if (Args.size() == 1) {
8328       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8329     } else {
8330       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8331       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8332     }
8333     break;
8334 
8335   case OO_Star: // '*' is either unary or binary
8336     if (Args.size() == 1)
8337       OpBuilder.addUnaryStarPointerOverloads();
8338     else
8339       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8340     break;
8341 
8342   case OO_Slash:
8343     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8344     break;
8345 
8346   case OO_PlusPlus:
8347   case OO_MinusMinus:
8348     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8349     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8350     break;
8351 
8352   case OO_EqualEqual:
8353   case OO_ExclaimEqual:
8354     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8355     // Fall through.
8356 
8357   case OO_Less:
8358   case OO_Greater:
8359   case OO_LessEqual:
8360   case OO_GreaterEqual:
8361     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8362     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8363     break;
8364 
8365   case OO_Percent:
8366   case OO_Caret:
8367   case OO_Pipe:
8368   case OO_LessLess:
8369   case OO_GreaterGreater:
8370     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8371     break;
8372 
8373   case OO_Amp: // '&' is either unary or binary
8374     if (Args.size() == 1)
8375       // C++ [over.match.oper]p3:
8376       //   -- For the operator ',', the unary operator '&', or the
8377       //      operator '->', the built-in candidates set is empty.
8378       break;
8379 
8380     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8381     break;
8382 
8383   case OO_Tilde:
8384     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8385     break;
8386 
8387   case OO_Equal:
8388     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8389     // Fall through.
8390 
8391   case OO_PlusEqual:
8392   case OO_MinusEqual:
8393     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8394     // Fall through.
8395 
8396   case OO_StarEqual:
8397   case OO_SlashEqual:
8398     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8399     break;
8400 
8401   case OO_PercentEqual:
8402   case OO_LessLessEqual:
8403   case OO_GreaterGreaterEqual:
8404   case OO_AmpEqual:
8405   case OO_CaretEqual:
8406   case OO_PipeEqual:
8407     OpBuilder.addAssignmentIntegralOverloads();
8408     break;
8409 
8410   case OO_Exclaim:
8411     OpBuilder.addExclaimOverload();
8412     break;
8413 
8414   case OO_AmpAmp:
8415   case OO_PipePipe:
8416     OpBuilder.addAmpAmpOrPipePipeOverload();
8417     break;
8418 
8419   case OO_Subscript:
8420     OpBuilder.addSubscriptOverloads();
8421     break;
8422 
8423   case OO_ArrowStar:
8424     OpBuilder.addArrowStarOverloads();
8425     break;
8426 
8427   case OO_Conditional:
8428     OpBuilder.addConditionalOperatorOverloads();
8429     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8430     break;
8431   }
8432 }
8433 
8434 /// \brief Add function candidates found via argument-dependent lookup
8435 /// to the set of overloading candidates.
8436 ///
8437 /// This routine performs argument-dependent name lookup based on the
8438 /// given function name (which may also be an operator name) and adds
8439 /// all of the overload candidates found by ADL to the overload
8440 /// candidate set (C++ [basic.lookup.argdep]).
8441 void
8442 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8443                                            SourceLocation Loc,
8444                                            ArrayRef<Expr *> Args,
8445                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8446                                            OverloadCandidateSet& CandidateSet,
8447                                            bool PartialOverloading) {
8448   ADLResult Fns;
8449 
8450   // FIXME: This approach for uniquing ADL results (and removing
8451   // redundant candidates from the set) relies on pointer-equality,
8452   // which means we need to key off the canonical decl.  However,
8453   // always going back to the canonical decl might not get us the
8454   // right set of default arguments.  What default arguments are
8455   // we supposed to consider on ADL candidates, anyway?
8456 
8457   // FIXME: Pass in the explicit template arguments?
8458   ArgumentDependentLookup(Name, Loc, Args, Fns);
8459 
8460   // Erase all of the candidates we already knew about.
8461   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8462                                    CandEnd = CandidateSet.end();
8463        Cand != CandEnd; ++Cand)
8464     if (Cand->Function) {
8465       Fns.erase(Cand->Function);
8466       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8467         Fns.erase(FunTmpl);
8468     }
8469 
8470   // For each of the ADL candidates we found, add it to the overload
8471   // set.
8472   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8473     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8474     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8475       if (ExplicitTemplateArgs)
8476         continue;
8477 
8478       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8479                            PartialOverloading);
8480     } else
8481       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8482                                    FoundDecl, ExplicitTemplateArgs,
8483                                    Args, CandidateSet, PartialOverloading);
8484   }
8485 }
8486 
8487 namespace {
8488 enum class Comparison { Equal, Better, Worse };
8489 }
8490 
8491 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8492 /// overload resolution.
8493 ///
8494 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8495 /// Cand1's first N enable_if attributes have precisely the same conditions as
8496 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8497 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8498 ///
8499 /// Note that you can have a pair of candidates such that Cand1's enable_if
8500 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8501 /// worse than Cand1's.
8502 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8503                                        const FunctionDecl *Cand2) {
8504   // Common case: One (or both) decls don't have enable_if attrs.
8505   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8506   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8507   if (!Cand1Attr || !Cand2Attr) {
8508     if (Cand1Attr == Cand2Attr)
8509       return Comparison::Equal;
8510     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8511   }
8512 
8513   // FIXME: The next several lines are just
8514   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8515   // instead of reverse order which is how they're stored in the AST.
8516   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8517   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8518 
8519   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8520   // has fewer enable_if attributes than Cand2.
8521   if (Cand1Attrs.size() < Cand2Attrs.size())
8522     return Comparison::Worse;
8523 
8524   auto Cand1I = Cand1Attrs.begin();
8525   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8526   for (auto &Cand2A : Cand2Attrs) {
8527     Cand1ID.clear();
8528     Cand2ID.clear();
8529 
8530     auto &Cand1A = *Cand1I++;
8531     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8532     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8533     if (Cand1ID != Cand2ID)
8534       return Comparison::Worse;
8535   }
8536 
8537   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8538 }
8539 
8540 /// isBetterOverloadCandidate - Determines whether the first overload
8541 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8542 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8543                                       const OverloadCandidate &Cand2,
8544                                       SourceLocation Loc,
8545                                       bool UserDefinedConversion) {
8546   // Define viable functions to be better candidates than non-viable
8547   // functions.
8548   if (!Cand2.Viable)
8549     return Cand1.Viable;
8550   else if (!Cand1.Viable)
8551     return false;
8552 
8553   // C++ [over.match.best]p1:
8554   //
8555   //   -- if F is a static member function, ICS1(F) is defined such
8556   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8557   //      any function G, and, symmetrically, ICS1(G) is neither
8558   //      better nor worse than ICS1(F).
8559   unsigned StartArg = 0;
8560   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8561     StartArg = 1;
8562 
8563   // C++ [over.match.best]p1:
8564   //   A viable function F1 is defined to be a better function than another
8565   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8566   //   conversion sequence than ICSi(F2), and then...
8567   unsigned NumArgs = Cand1.NumConversions;
8568   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8569   bool HasBetterConversion = false;
8570   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8571     switch (CompareImplicitConversionSequences(S, Loc,
8572                                                Cand1.Conversions[ArgIdx],
8573                                                Cand2.Conversions[ArgIdx])) {
8574     case ImplicitConversionSequence::Better:
8575       // Cand1 has a better conversion sequence.
8576       HasBetterConversion = true;
8577       break;
8578 
8579     case ImplicitConversionSequence::Worse:
8580       // Cand1 can't be better than Cand2.
8581       return false;
8582 
8583     case ImplicitConversionSequence::Indistinguishable:
8584       // Do nothing.
8585       break;
8586     }
8587   }
8588 
8589   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8590   //       ICSj(F2), or, if not that,
8591   if (HasBetterConversion)
8592     return true;
8593 
8594   //   -- the context is an initialization by user-defined conversion
8595   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8596   //      from the return type of F1 to the destination type (i.e.,
8597   //      the type of the entity being initialized) is a better
8598   //      conversion sequence than the standard conversion sequence
8599   //      from the return type of F2 to the destination type.
8600   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8601       isa<CXXConversionDecl>(Cand1.Function) &&
8602       isa<CXXConversionDecl>(Cand2.Function)) {
8603     // First check whether we prefer one of the conversion functions over the
8604     // other. This only distinguishes the results in non-standard, extension
8605     // cases such as the conversion from a lambda closure type to a function
8606     // pointer or block.
8607     ImplicitConversionSequence::CompareKind Result =
8608         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8609     if (Result == ImplicitConversionSequence::Indistinguishable)
8610       Result = CompareStandardConversionSequences(S, Loc,
8611                                                   Cand1.FinalConversion,
8612                                                   Cand2.FinalConversion);
8613 
8614     if (Result != ImplicitConversionSequence::Indistinguishable)
8615       return Result == ImplicitConversionSequence::Better;
8616 
8617     // FIXME: Compare kind of reference binding if conversion functions
8618     // convert to a reference type used in direct reference binding, per
8619     // C++14 [over.match.best]p1 section 2 bullet 3.
8620   }
8621 
8622   //    -- F1 is a non-template function and F2 is a function template
8623   //       specialization, or, if not that,
8624   bool Cand1IsSpecialization = Cand1.Function &&
8625                                Cand1.Function->getPrimaryTemplate();
8626   bool Cand2IsSpecialization = Cand2.Function &&
8627                                Cand2.Function->getPrimaryTemplate();
8628   if (Cand1IsSpecialization != Cand2IsSpecialization)
8629     return Cand2IsSpecialization;
8630 
8631   //   -- F1 and F2 are function template specializations, and the function
8632   //      template for F1 is more specialized than the template for F2
8633   //      according to the partial ordering rules described in 14.5.5.2, or,
8634   //      if not that,
8635   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8636     if (FunctionTemplateDecl *BetterTemplate
8637           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8638                                          Cand2.Function->getPrimaryTemplate(),
8639                                          Loc,
8640                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8641                                                              : TPOC_Call,
8642                                          Cand1.ExplicitCallArguments,
8643                                          Cand2.ExplicitCallArguments))
8644       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8645   }
8646 
8647   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8648   // A derived-class constructor beats an (inherited) base class constructor.
8649   bool Cand1IsInherited =
8650       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8651   bool Cand2IsInherited =
8652       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8653   if (Cand1IsInherited != Cand2IsInherited)
8654     return Cand2IsInherited;
8655   else if (Cand1IsInherited) {
8656     assert(Cand2IsInherited);
8657     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8658     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8659     if (Cand1Class->isDerivedFrom(Cand2Class))
8660       return true;
8661     if (Cand2Class->isDerivedFrom(Cand1Class))
8662       return false;
8663     // Inherited from sibling base classes: still ambiguous.
8664   }
8665 
8666   // Check for enable_if value-based overload resolution.
8667   if (Cand1.Function && Cand2.Function) {
8668     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8669     if (Cmp != Comparison::Equal)
8670       return Cmp == Comparison::Better;
8671   }
8672 
8673   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8674     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8675     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8676            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8677   }
8678 
8679   bool HasPS1 = Cand1.Function != nullptr &&
8680                 functionHasPassObjectSizeParams(Cand1.Function);
8681   bool HasPS2 = Cand2.Function != nullptr &&
8682                 functionHasPassObjectSizeParams(Cand2.Function);
8683   return HasPS1 != HasPS2 && HasPS1;
8684 }
8685 
8686 /// Determine whether two declarations are "equivalent" for the purposes of
8687 /// name lookup and overload resolution. This applies when the same internal/no
8688 /// linkage entity is defined by two modules (probably by textually including
8689 /// the same header). In such a case, we don't consider the declarations to
8690 /// declare the same entity, but we also don't want lookups with both
8691 /// declarations visible to be ambiguous in some cases (this happens when using
8692 /// a modularized libstdc++).
8693 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8694                                                   const NamedDecl *B) {
8695   auto *VA = dyn_cast_or_null<ValueDecl>(A);
8696   auto *VB = dyn_cast_or_null<ValueDecl>(B);
8697   if (!VA || !VB)
8698     return false;
8699 
8700   // The declarations must be declaring the same name as an internal linkage
8701   // entity in different modules.
8702   if (!VA->getDeclContext()->getRedeclContext()->Equals(
8703           VB->getDeclContext()->getRedeclContext()) ||
8704       getOwningModule(const_cast<ValueDecl *>(VA)) ==
8705           getOwningModule(const_cast<ValueDecl *>(VB)) ||
8706       VA->isExternallyVisible() || VB->isExternallyVisible())
8707     return false;
8708 
8709   // Check that the declarations appear to be equivalent.
8710   //
8711   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8712   // For constants and functions, we should check the initializer or body is
8713   // the same. For non-constant variables, we shouldn't allow it at all.
8714   if (Context.hasSameType(VA->getType(), VB->getType()))
8715     return true;
8716 
8717   // Enum constants within unnamed enumerations will have different types, but
8718   // may still be similar enough to be interchangeable for our purposes.
8719   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8720     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8721       // Only handle anonymous enums. If the enumerations were named and
8722       // equivalent, they would have been merged to the same type.
8723       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8724       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8725       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8726           !Context.hasSameType(EnumA->getIntegerType(),
8727                                EnumB->getIntegerType()))
8728         return false;
8729       // Allow this only if the value is the same for both enumerators.
8730       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8731     }
8732   }
8733 
8734   // Nothing else is sufficiently similar.
8735   return false;
8736 }
8737 
8738 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8739     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8740   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8741 
8742   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8743   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8744       << !M << (M ? M->getFullModuleName() : "");
8745 
8746   for (auto *E : Equiv) {
8747     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8748     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8749         << !M << (M ? M->getFullModuleName() : "");
8750   }
8751 }
8752 
8753 /// \brief Computes the best viable function (C++ 13.3.3)
8754 /// within an overload candidate set.
8755 ///
8756 /// \param Loc The location of the function name (or operator symbol) for
8757 /// which overload resolution occurs.
8758 ///
8759 /// \param Best If overload resolution was successful or found a deleted
8760 /// function, \p Best points to the candidate function found.
8761 ///
8762 /// \returns The result of overload resolution.
8763 OverloadingResult
8764 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8765                                          iterator &Best,
8766                                          bool UserDefinedConversion) {
8767   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8768   std::transform(begin(), end(), std::back_inserter(Candidates),
8769                  [](OverloadCandidate &Cand) { return &Cand; });
8770 
8771   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA
8772   // but accepted by both clang and NVCC. However during a particular
8773   // compilation mode only one call variant is viable. We need to
8774   // exclude non-viable overload candidates from consideration based
8775   // only on their host/device attributes. Specifically, if one
8776   // candidate call is WrongSide and the other is SameSide, we ignore
8777   // the WrongSide candidate.
8778   if (S.getLangOpts().CUDA) {
8779     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8780     bool ContainsSameSideCandidate =
8781         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8782           return Cand->Function &&
8783                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8784                      Sema::CFP_SameSide;
8785         });
8786     if (ContainsSameSideCandidate) {
8787       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8788         return Cand->Function &&
8789                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8790                    Sema::CFP_WrongSide;
8791       };
8792       Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8793                                       IsWrongSideCandidate),
8794                        Candidates.end());
8795     }
8796   }
8797 
8798   // Find the best viable function.
8799   Best = end();
8800   for (auto *Cand : Candidates)
8801     if (Cand->Viable)
8802       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8803                                                      UserDefinedConversion))
8804         Best = Cand;
8805 
8806   // If we didn't find any viable functions, abort.
8807   if (Best == end())
8808     return OR_No_Viable_Function;
8809 
8810   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8811 
8812   // Make sure that this function is better than every other viable
8813   // function. If not, we have an ambiguity.
8814   for (auto *Cand : Candidates) {
8815     if (Cand->Viable &&
8816         Cand != Best &&
8817         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8818                                    UserDefinedConversion)) {
8819       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8820                                                    Cand->Function)) {
8821         EquivalentCands.push_back(Cand->Function);
8822         continue;
8823       }
8824 
8825       Best = end();
8826       return OR_Ambiguous;
8827     }
8828   }
8829 
8830   // Best is the best viable function.
8831   if (Best->Function &&
8832       (Best->Function->isDeleted() ||
8833        S.isFunctionConsideredUnavailable(Best->Function)))
8834     return OR_Deleted;
8835 
8836   if (!EquivalentCands.empty())
8837     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8838                                                     EquivalentCands);
8839 
8840   return OR_Success;
8841 }
8842 
8843 namespace {
8844 
8845 enum OverloadCandidateKind {
8846   oc_function,
8847   oc_method,
8848   oc_constructor,
8849   oc_function_template,
8850   oc_method_template,
8851   oc_constructor_template,
8852   oc_implicit_default_constructor,
8853   oc_implicit_copy_constructor,
8854   oc_implicit_move_constructor,
8855   oc_implicit_copy_assignment,
8856   oc_implicit_move_assignment,
8857   oc_inherited_constructor,
8858   oc_inherited_constructor_template
8859 };
8860 
8861 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8862                                                 NamedDecl *Found,
8863                                                 FunctionDecl *Fn,
8864                                                 std::string &Description) {
8865   bool isTemplate = false;
8866 
8867   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8868     isTemplate = true;
8869     Description = S.getTemplateArgumentBindingsText(
8870       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8871   }
8872 
8873   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8874     if (!Ctor->isImplicit()) {
8875       if (isa<ConstructorUsingShadowDecl>(Found))
8876         return isTemplate ? oc_inherited_constructor_template
8877                           : oc_inherited_constructor;
8878       else
8879         return isTemplate ? oc_constructor_template : oc_constructor;
8880     }
8881 
8882     if (Ctor->isDefaultConstructor())
8883       return oc_implicit_default_constructor;
8884 
8885     if (Ctor->isMoveConstructor())
8886       return oc_implicit_move_constructor;
8887 
8888     assert(Ctor->isCopyConstructor() &&
8889            "unexpected sort of implicit constructor");
8890     return oc_implicit_copy_constructor;
8891   }
8892 
8893   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8894     // This actually gets spelled 'candidate function' for now, but
8895     // it doesn't hurt to split it out.
8896     if (!Meth->isImplicit())
8897       return isTemplate ? oc_method_template : oc_method;
8898 
8899     if (Meth->isMoveAssignmentOperator())
8900       return oc_implicit_move_assignment;
8901 
8902     if (Meth->isCopyAssignmentOperator())
8903       return oc_implicit_copy_assignment;
8904 
8905     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8906     return oc_method;
8907   }
8908 
8909   return isTemplate ? oc_function_template : oc_function;
8910 }
8911 
8912 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
8913   // FIXME: It'd be nice to only emit a note once per using-decl per overload
8914   // set.
8915   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
8916     S.Diag(FoundDecl->getLocation(),
8917            diag::note_ovl_candidate_inherited_constructor)
8918       << Shadow->getNominatedBaseClass();
8919 }
8920 
8921 } // end anonymous namespace
8922 
8923 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8924                                     const FunctionDecl *FD) {
8925   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8926     bool AlwaysTrue;
8927     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8928       return false;
8929     if (!AlwaysTrue)
8930       return false;
8931   }
8932   return true;
8933 }
8934 
8935 /// \brief Returns true if we can take the address of the function.
8936 ///
8937 /// \param Complain - If true, we'll emit a diagnostic
8938 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8939 ///   we in overload resolution?
8940 /// \param Loc - The location of the statement we're complaining about. Ignored
8941 ///   if we're not complaining, or if we're in overload resolution.
8942 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8943                                               bool Complain,
8944                                               bool InOverloadResolution,
8945                                               SourceLocation Loc) {
8946   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8947     if (Complain) {
8948       if (InOverloadResolution)
8949         S.Diag(FD->getLocStart(),
8950                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8951       else
8952         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8953     }
8954     return false;
8955   }
8956 
8957   auto I = llvm::find_if(
8958       FD->parameters(), std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8959   if (I == FD->param_end())
8960     return true;
8961 
8962   if (Complain) {
8963     // Add one to ParamNo because it's user-facing
8964     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8965     if (InOverloadResolution)
8966       S.Diag(FD->getLocation(),
8967              diag::note_ovl_candidate_has_pass_object_size_params)
8968           << ParamNo;
8969     else
8970       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8971           << FD << ParamNo;
8972   }
8973   return false;
8974 }
8975 
8976 static bool checkAddressOfCandidateIsAvailable(Sema &S,
8977                                                const FunctionDecl *FD) {
8978   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8979                                            /*InOverloadResolution=*/true,
8980                                            /*Loc=*/SourceLocation());
8981 }
8982 
8983 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8984                                              bool Complain,
8985                                              SourceLocation Loc) {
8986   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8987                                              /*InOverloadResolution=*/false,
8988                                              Loc);
8989 }
8990 
8991 // Notes the location of an overload candidate.
8992 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
8993                                  QualType DestType, bool TakingAddress) {
8994   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8995     return;
8996 
8997   std::string FnDesc;
8998   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
8999   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9000                              << (unsigned) K << FnDesc;
9001 
9002   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9003   Diag(Fn->getLocation(), PD);
9004   MaybeEmitInheritedConstructorNote(*this, Found);
9005 }
9006 
9007 // Notes the location of all overload candidates designated through
9008 // OverloadedExpr
9009 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9010                                      bool TakingAddress) {
9011   assert(OverloadedExpr->getType() == Context.OverloadTy);
9012 
9013   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9014   OverloadExpr *OvlExpr = Ovl.Expression;
9015 
9016   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9017                             IEnd = OvlExpr->decls_end();
9018        I != IEnd; ++I) {
9019     if (FunctionTemplateDecl *FunTmpl =
9020                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9021       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9022                             TakingAddress);
9023     } else if (FunctionDecl *Fun
9024                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9025       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9026     }
9027   }
9028 }
9029 
9030 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9031 /// "lead" diagnostic; it will be given two arguments, the source and
9032 /// target types of the conversion.
9033 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9034                                  Sema &S,
9035                                  SourceLocation CaretLoc,
9036                                  const PartialDiagnostic &PDiag) const {
9037   S.Diag(CaretLoc, PDiag)
9038     << Ambiguous.getFromType() << Ambiguous.getToType();
9039   // FIXME: The note limiting machinery is borrowed from
9040   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9041   // refactoring here.
9042   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9043   unsigned CandsShown = 0;
9044   AmbiguousConversionSequence::const_iterator I, E;
9045   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9046     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9047       break;
9048     ++CandsShown;
9049     S.NoteOverloadCandidate(I->first, I->second);
9050   }
9051   if (I != E)
9052     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9053 }
9054 
9055 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9056                                   unsigned I, bool TakingCandidateAddress) {
9057   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9058   assert(Conv.isBad());
9059   assert(Cand->Function && "for now, candidate must be a function");
9060   FunctionDecl *Fn = Cand->Function;
9061 
9062   // There's a conversion slot for the object argument if this is a
9063   // non-constructor method.  Note that 'I' corresponds the
9064   // conversion-slot index.
9065   bool isObjectArgument = false;
9066   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9067     if (I == 0)
9068       isObjectArgument = true;
9069     else
9070       I--;
9071   }
9072 
9073   std::string FnDesc;
9074   OverloadCandidateKind FnKind =
9075       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9076 
9077   Expr *FromExpr = Conv.Bad.FromExpr;
9078   QualType FromTy = Conv.Bad.getFromType();
9079   QualType ToTy = Conv.Bad.getToType();
9080 
9081   if (FromTy == S.Context.OverloadTy) {
9082     assert(FromExpr && "overload set argument came from implicit argument?");
9083     Expr *E = FromExpr->IgnoreParens();
9084     if (isa<UnaryOperator>(E))
9085       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9086     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9087 
9088     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9089       << (unsigned) FnKind << FnDesc
9090       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9091       << ToTy << Name << I+1;
9092     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9093     return;
9094   }
9095 
9096   // Do some hand-waving analysis to see if the non-viability is due
9097   // to a qualifier mismatch.
9098   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9099   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9100   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9101     CToTy = RT->getPointeeType();
9102   else {
9103     // TODO: detect and diagnose the full richness of const mismatches.
9104     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9105       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9106         CFromTy = FromPT->getPointeeType();
9107         CToTy = ToPT->getPointeeType();
9108       }
9109   }
9110 
9111   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9112       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9113     Qualifiers FromQs = CFromTy.getQualifiers();
9114     Qualifiers ToQs = CToTy.getQualifiers();
9115 
9116     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9117       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9118         << (unsigned) FnKind << FnDesc
9119         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9120         << FromTy
9121         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9122         << (unsigned) isObjectArgument << I+1;
9123       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9124       return;
9125     }
9126 
9127     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9128       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9129         << (unsigned) FnKind << FnDesc
9130         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9131         << FromTy
9132         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9133         << (unsigned) isObjectArgument << I+1;
9134       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9135       return;
9136     }
9137 
9138     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9139       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9140       << (unsigned) FnKind << FnDesc
9141       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9142       << FromTy
9143       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9144       << (unsigned) isObjectArgument << I+1;
9145       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9146       return;
9147     }
9148 
9149     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9150       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9151         << (unsigned) FnKind << FnDesc
9152         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9153         << FromTy << FromQs.hasUnaligned() << I+1;
9154       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9155       return;
9156     }
9157 
9158     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9159     assert(CVR && "unexpected qualifiers mismatch");
9160 
9161     if (isObjectArgument) {
9162       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9163         << (unsigned) FnKind << FnDesc
9164         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9165         << FromTy << (CVR - 1);
9166     } else {
9167       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9168         << (unsigned) FnKind << FnDesc
9169         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9170         << FromTy << (CVR - 1) << I+1;
9171     }
9172     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9173     return;
9174   }
9175 
9176   // Special diagnostic for failure to convert an initializer list, since
9177   // telling the user that it has type void is not useful.
9178   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9179     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9180       << (unsigned) FnKind << FnDesc
9181       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9182       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9183     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9184     return;
9185   }
9186 
9187   // Diagnose references or pointers to incomplete types differently,
9188   // since it's far from impossible that the incompleteness triggered
9189   // the failure.
9190   QualType TempFromTy = FromTy.getNonReferenceType();
9191   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9192     TempFromTy = PTy->getPointeeType();
9193   if (TempFromTy->isIncompleteType()) {
9194     // Emit the generic diagnostic and, optionally, add the hints to it.
9195     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9196       << (unsigned) FnKind << FnDesc
9197       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9198       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9199       << (unsigned) (Cand->Fix.Kind);
9200 
9201     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9202     return;
9203   }
9204 
9205   // Diagnose base -> derived pointer conversions.
9206   unsigned BaseToDerivedConversion = 0;
9207   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9208     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9209       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9210                                                FromPtrTy->getPointeeType()) &&
9211           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9212           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9213           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9214                           FromPtrTy->getPointeeType()))
9215         BaseToDerivedConversion = 1;
9216     }
9217   } else if (const ObjCObjectPointerType *FromPtrTy
9218                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9219     if (const ObjCObjectPointerType *ToPtrTy
9220                                         = ToTy->getAs<ObjCObjectPointerType>())
9221       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9222         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9223           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9224                                                 FromPtrTy->getPointeeType()) &&
9225               FromIface->isSuperClassOf(ToIface))
9226             BaseToDerivedConversion = 2;
9227   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9228     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9229         !FromTy->isIncompleteType() &&
9230         !ToRefTy->getPointeeType()->isIncompleteType() &&
9231         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9232       BaseToDerivedConversion = 3;
9233     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9234                ToTy.getNonReferenceType().getCanonicalType() ==
9235                FromTy.getNonReferenceType().getCanonicalType()) {
9236       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9237         << (unsigned) FnKind << FnDesc
9238         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9239         << (unsigned) isObjectArgument << I + 1;
9240       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9241       return;
9242     }
9243   }
9244 
9245   if (BaseToDerivedConversion) {
9246     S.Diag(Fn->getLocation(),
9247            diag::note_ovl_candidate_bad_base_to_derived_conv)
9248       << (unsigned) FnKind << FnDesc
9249       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9250       << (BaseToDerivedConversion - 1)
9251       << FromTy << ToTy << I+1;
9252     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9253     return;
9254   }
9255 
9256   if (isa<ObjCObjectPointerType>(CFromTy) &&
9257       isa<PointerType>(CToTy)) {
9258       Qualifiers FromQs = CFromTy.getQualifiers();
9259       Qualifiers ToQs = CToTy.getQualifiers();
9260       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9261         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9262         << (unsigned) FnKind << FnDesc
9263         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9264         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9265         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9266         return;
9267       }
9268   }
9269 
9270   if (TakingCandidateAddress &&
9271       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9272     return;
9273 
9274   // Emit the generic diagnostic and, optionally, add the hints to it.
9275   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9276   FDiag << (unsigned) FnKind << FnDesc
9277     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9278     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9279     << (unsigned) (Cand->Fix.Kind);
9280 
9281   // If we can fix the conversion, suggest the FixIts.
9282   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9283        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9284     FDiag << *HI;
9285   S.Diag(Fn->getLocation(), FDiag);
9286 
9287   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9288 }
9289 
9290 /// Additional arity mismatch diagnosis specific to a function overload
9291 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9292 /// over a candidate in any candidate set.
9293 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9294                                unsigned NumArgs) {
9295   FunctionDecl *Fn = Cand->Function;
9296   unsigned MinParams = Fn->getMinRequiredArguments();
9297 
9298   // With invalid overloaded operators, it's possible that we think we
9299   // have an arity mismatch when in fact it looks like we have the
9300   // right number of arguments, because only overloaded operators have
9301   // the weird behavior of overloading member and non-member functions.
9302   // Just don't report anything.
9303   if (Fn->isInvalidDecl() &&
9304       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9305     return true;
9306 
9307   if (NumArgs < MinParams) {
9308     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9309            (Cand->FailureKind == ovl_fail_bad_deduction &&
9310             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9311   } else {
9312     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9313            (Cand->FailureKind == ovl_fail_bad_deduction &&
9314             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9315   }
9316 
9317   return false;
9318 }
9319 
9320 /// General arity mismatch diagnosis over a candidate in a candidate set.
9321 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9322                                   unsigned NumFormalArgs) {
9323   assert(isa<FunctionDecl>(D) &&
9324       "The templated declaration should at least be a function"
9325       " when diagnosing bad template argument deduction due to too many"
9326       " or too few arguments");
9327 
9328   FunctionDecl *Fn = cast<FunctionDecl>(D);
9329 
9330   // TODO: treat calls to a missing default constructor as a special case
9331   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9332   unsigned MinParams = Fn->getMinRequiredArguments();
9333 
9334   // at least / at most / exactly
9335   unsigned mode, modeCount;
9336   if (NumFormalArgs < MinParams) {
9337     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9338         FnTy->isTemplateVariadic())
9339       mode = 0; // "at least"
9340     else
9341       mode = 2; // "exactly"
9342     modeCount = MinParams;
9343   } else {
9344     if (MinParams != FnTy->getNumParams())
9345       mode = 1; // "at most"
9346     else
9347       mode = 2; // "exactly"
9348     modeCount = FnTy->getNumParams();
9349   }
9350 
9351   std::string Description;
9352   OverloadCandidateKind FnKind =
9353       ClassifyOverloadCandidate(S, Found, Fn, Description);
9354 
9355   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9356     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9357       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9358       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9359   else
9360     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9361       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9362       << mode << modeCount << NumFormalArgs;
9363   MaybeEmitInheritedConstructorNote(S, Found);
9364 }
9365 
9366 /// Arity mismatch diagnosis specific to a function overload candidate.
9367 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9368                                   unsigned NumFormalArgs) {
9369   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9370     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9371 }
9372 
9373 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9374   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9375     return TD;
9376   llvm_unreachable("Unsupported: Getting the described template declaration"
9377                    " for bad deduction diagnosis");
9378 }
9379 
9380 /// Diagnose a failed template-argument deduction.
9381 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9382                                  DeductionFailureInfo &DeductionFailure,
9383                                  unsigned NumArgs,
9384                                  bool TakingCandidateAddress) {
9385   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9386   NamedDecl *ParamD;
9387   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9388   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9389   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9390   switch (DeductionFailure.Result) {
9391   case Sema::TDK_Success:
9392     llvm_unreachable("TDK_success while diagnosing bad deduction");
9393 
9394   case Sema::TDK_Incomplete: {
9395     assert(ParamD && "no parameter found for incomplete deduction result");
9396     S.Diag(Templated->getLocation(),
9397            diag::note_ovl_candidate_incomplete_deduction)
9398         << ParamD->getDeclName();
9399     MaybeEmitInheritedConstructorNote(S, Found);
9400     return;
9401   }
9402 
9403   case Sema::TDK_Underqualified: {
9404     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9405     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9406 
9407     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9408 
9409     // Param will have been canonicalized, but it should just be a
9410     // qualified version of ParamD, so move the qualifiers to that.
9411     QualifierCollector Qs;
9412     Qs.strip(Param);
9413     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9414     assert(S.Context.hasSameType(Param, NonCanonParam));
9415 
9416     // Arg has also been canonicalized, but there's nothing we can do
9417     // about that.  It also doesn't matter as much, because it won't
9418     // have any template parameters in it (because deduction isn't
9419     // done on dependent types).
9420     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9421 
9422     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9423         << ParamD->getDeclName() << Arg << NonCanonParam;
9424     MaybeEmitInheritedConstructorNote(S, Found);
9425     return;
9426   }
9427 
9428   case Sema::TDK_Inconsistent: {
9429     assert(ParamD && "no parameter found for inconsistent deduction result");
9430     int which = 0;
9431     if (isa<TemplateTypeParmDecl>(ParamD))
9432       which = 0;
9433     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9434       which = 1;
9435     else {
9436       which = 2;
9437     }
9438 
9439     S.Diag(Templated->getLocation(),
9440            diag::note_ovl_candidate_inconsistent_deduction)
9441         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9442         << *DeductionFailure.getSecondArg();
9443     MaybeEmitInheritedConstructorNote(S, Found);
9444     return;
9445   }
9446 
9447   case Sema::TDK_InvalidExplicitArguments:
9448     assert(ParamD && "no parameter found for invalid explicit arguments");
9449     if (ParamD->getDeclName())
9450       S.Diag(Templated->getLocation(),
9451              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9452           << ParamD->getDeclName();
9453     else {
9454       int index = 0;
9455       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9456         index = TTP->getIndex();
9457       else if (NonTypeTemplateParmDecl *NTTP
9458                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9459         index = NTTP->getIndex();
9460       else
9461         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9462       S.Diag(Templated->getLocation(),
9463              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9464           << (index + 1);
9465     }
9466     MaybeEmitInheritedConstructorNote(S, Found);
9467     return;
9468 
9469   case Sema::TDK_TooManyArguments:
9470   case Sema::TDK_TooFewArguments:
9471     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9472     return;
9473 
9474   case Sema::TDK_InstantiationDepth:
9475     S.Diag(Templated->getLocation(),
9476            diag::note_ovl_candidate_instantiation_depth);
9477     MaybeEmitInheritedConstructorNote(S, Found);
9478     return;
9479 
9480   case Sema::TDK_SubstitutionFailure: {
9481     // Format the template argument list into the argument string.
9482     SmallString<128> TemplateArgString;
9483     if (TemplateArgumentList *Args =
9484             DeductionFailure.getTemplateArgumentList()) {
9485       TemplateArgString = " ";
9486       TemplateArgString += S.getTemplateArgumentBindingsText(
9487           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9488     }
9489 
9490     // If this candidate was disabled by enable_if, say so.
9491     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9492     if (PDiag && PDiag->second.getDiagID() ==
9493           diag::err_typename_nested_not_found_enable_if) {
9494       // FIXME: Use the source range of the condition, and the fully-qualified
9495       //        name of the enable_if template. These are both present in PDiag.
9496       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9497         << "'enable_if'" << TemplateArgString;
9498       return;
9499     }
9500 
9501     // Format the SFINAE diagnostic into the argument string.
9502     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9503     //        formatted message in another diagnostic.
9504     SmallString<128> SFINAEArgString;
9505     SourceRange R;
9506     if (PDiag) {
9507       SFINAEArgString = ": ";
9508       R = SourceRange(PDiag->first, PDiag->first);
9509       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9510     }
9511 
9512     S.Diag(Templated->getLocation(),
9513            diag::note_ovl_candidate_substitution_failure)
9514         << TemplateArgString << SFINAEArgString << R;
9515     MaybeEmitInheritedConstructorNote(S, Found);
9516     return;
9517   }
9518 
9519   case Sema::TDK_FailedOverloadResolution: {
9520     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9521     S.Diag(Templated->getLocation(),
9522            diag::note_ovl_candidate_failed_overload_resolution)
9523         << R.Expression->getName();
9524     return;
9525   }
9526 
9527   case Sema::TDK_DeducedMismatch: {
9528     // Format the template argument list into the argument string.
9529     SmallString<128> TemplateArgString;
9530     if (TemplateArgumentList *Args =
9531             DeductionFailure.getTemplateArgumentList()) {
9532       TemplateArgString = " ";
9533       TemplateArgString += S.getTemplateArgumentBindingsText(
9534           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9535     }
9536 
9537     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9538         << (*DeductionFailure.getCallArgIndex() + 1)
9539         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9540         << TemplateArgString;
9541     break;
9542   }
9543 
9544   case Sema::TDK_NonDeducedMismatch: {
9545     // FIXME: Provide a source location to indicate what we couldn't match.
9546     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9547     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9548     if (FirstTA.getKind() == TemplateArgument::Template &&
9549         SecondTA.getKind() == TemplateArgument::Template) {
9550       TemplateName FirstTN = FirstTA.getAsTemplate();
9551       TemplateName SecondTN = SecondTA.getAsTemplate();
9552       if (FirstTN.getKind() == TemplateName::Template &&
9553           SecondTN.getKind() == TemplateName::Template) {
9554         if (FirstTN.getAsTemplateDecl()->getName() ==
9555             SecondTN.getAsTemplateDecl()->getName()) {
9556           // FIXME: This fixes a bad diagnostic where both templates are named
9557           // the same.  This particular case is a bit difficult since:
9558           // 1) It is passed as a string to the diagnostic printer.
9559           // 2) The diagnostic printer only attempts to find a better
9560           //    name for types, not decls.
9561           // Ideally, this should folded into the diagnostic printer.
9562           S.Diag(Templated->getLocation(),
9563                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9564               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9565           return;
9566         }
9567       }
9568     }
9569 
9570     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9571         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9572       return;
9573 
9574     // FIXME: For generic lambda parameters, check if the function is a lambda
9575     // call operator, and if so, emit a prettier and more informative
9576     // diagnostic that mentions 'auto' and lambda in addition to
9577     // (or instead of?) the canonical template type parameters.
9578     S.Diag(Templated->getLocation(),
9579            diag::note_ovl_candidate_non_deduced_mismatch)
9580         << FirstTA << SecondTA;
9581     return;
9582   }
9583   // TODO: diagnose these individually, then kill off
9584   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9585   case Sema::TDK_MiscellaneousDeductionFailure:
9586     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9587     MaybeEmitInheritedConstructorNote(S, Found);
9588     return;
9589   }
9590 }
9591 
9592 /// Diagnose a failed template-argument deduction, for function calls.
9593 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9594                                  unsigned NumArgs,
9595                                  bool TakingCandidateAddress) {
9596   unsigned TDK = Cand->DeductionFailure.Result;
9597   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9598     if (CheckArityMismatch(S, Cand, NumArgs))
9599       return;
9600   }
9601   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9602                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9603 }
9604 
9605 /// CUDA: diagnose an invalid call across targets.
9606 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9607   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9608   FunctionDecl *Callee = Cand->Function;
9609 
9610   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9611                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9612 
9613   std::string FnDesc;
9614   OverloadCandidateKind FnKind =
9615       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9616 
9617   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9618       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9619 
9620   // This could be an implicit constructor for which we could not infer the
9621   // target due to a collsion. Diagnose that case.
9622   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9623   if (Meth != nullptr && Meth->isImplicit()) {
9624     CXXRecordDecl *ParentClass = Meth->getParent();
9625     Sema::CXXSpecialMember CSM;
9626 
9627     switch (FnKind) {
9628     default:
9629       return;
9630     case oc_implicit_default_constructor:
9631       CSM = Sema::CXXDefaultConstructor;
9632       break;
9633     case oc_implicit_copy_constructor:
9634       CSM = Sema::CXXCopyConstructor;
9635       break;
9636     case oc_implicit_move_constructor:
9637       CSM = Sema::CXXMoveConstructor;
9638       break;
9639     case oc_implicit_copy_assignment:
9640       CSM = Sema::CXXCopyAssignment;
9641       break;
9642     case oc_implicit_move_assignment:
9643       CSM = Sema::CXXMoveAssignment;
9644       break;
9645     };
9646 
9647     bool ConstRHS = false;
9648     if (Meth->getNumParams()) {
9649       if (const ReferenceType *RT =
9650               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9651         ConstRHS = RT->getPointeeType().isConstQualified();
9652       }
9653     }
9654 
9655     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9656                                               /* ConstRHS */ ConstRHS,
9657                                               /* Diagnose */ true);
9658   }
9659 }
9660 
9661 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9662   FunctionDecl *Callee = Cand->Function;
9663   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9664 
9665   S.Diag(Callee->getLocation(),
9666          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9667       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9668 }
9669 
9670 /// Generates a 'note' diagnostic for an overload candidate.  We've
9671 /// already generated a primary error at the call site.
9672 ///
9673 /// It really does need to be a single diagnostic with its caret
9674 /// pointed at the candidate declaration.  Yes, this creates some
9675 /// major challenges of technical writing.  Yes, this makes pointing
9676 /// out problems with specific arguments quite awkward.  It's still
9677 /// better than generating twenty screens of text for every failed
9678 /// overload.
9679 ///
9680 /// It would be great to be able to express per-candidate problems
9681 /// more richly for those diagnostic clients that cared, but we'd
9682 /// still have to be just as careful with the default diagnostics.
9683 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9684                                   unsigned NumArgs,
9685                                   bool TakingCandidateAddress) {
9686   FunctionDecl *Fn = Cand->Function;
9687 
9688   // Note deleted candidates, but only if they're viable.
9689   if (Cand->Viable && (Fn->isDeleted() ||
9690       S.isFunctionConsideredUnavailable(Fn))) {
9691     std::string FnDesc;
9692     OverloadCandidateKind FnKind =
9693         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9694 
9695     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9696       << FnKind << FnDesc
9697       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9698     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9699     return;
9700   }
9701 
9702   // We don't really have anything else to say about viable candidates.
9703   if (Cand->Viable) {
9704     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9705     return;
9706   }
9707 
9708   switch (Cand->FailureKind) {
9709   case ovl_fail_too_many_arguments:
9710   case ovl_fail_too_few_arguments:
9711     return DiagnoseArityMismatch(S, Cand, NumArgs);
9712 
9713   case ovl_fail_bad_deduction:
9714     return DiagnoseBadDeduction(S, Cand, NumArgs,
9715                                 TakingCandidateAddress);
9716 
9717   case ovl_fail_illegal_constructor: {
9718     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9719       << (Fn->getPrimaryTemplate() ? 1 : 0);
9720     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9721     return;
9722   }
9723 
9724   case ovl_fail_trivial_conversion:
9725   case ovl_fail_bad_final_conversion:
9726   case ovl_fail_final_conversion_not_exact:
9727     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9728 
9729   case ovl_fail_bad_conversion: {
9730     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9731     for (unsigned N = Cand->NumConversions; I != N; ++I)
9732       if (Cand->Conversions[I].isBad())
9733         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9734 
9735     // FIXME: this currently happens when we're called from SemaInit
9736     // when user-conversion overload fails.  Figure out how to handle
9737     // those conditions and diagnose them well.
9738     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9739   }
9740 
9741   case ovl_fail_bad_target:
9742     return DiagnoseBadTarget(S, Cand);
9743 
9744   case ovl_fail_enable_if:
9745     return DiagnoseFailedEnableIfAttr(S, Cand);
9746 
9747   case ovl_fail_addr_not_available: {
9748     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9749     (void)Available;
9750     assert(!Available);
9751     break;
9752   }
9753   }
9754 }
9755 
9756 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9757   // Desugar the type of the surrogate down to a function type,
9758   // retaining as many typedefs as possible while still showing
9759   // the function type (and, therefore, its parameter types).
9760   QualType FnType = Cand->Surrogate->getConversionType();
9761   bool isLValueReference = false;
9762   bool isRValueReference = false;
9763   bool isPointer = false;
9764   if (const LValueReferenceType *FnTypeRef =
9765         FnType->getAs<LValueReferenceType>()) {
9766     FnType = FnTypeRef->getPointeeType();
9767     isLValueReference = true;
9768   } else if (const RValueReferenceType *FnTypeRef =
9769                FnType->getAs<RValueReferenceType>()) {
9770     FnType = FnTypeRef->getPointeeType();
9771     isRValueReference = true;
9772   }
9773   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9774     FnType = FnTypePtr->getPointeeType();
9775     isPointer = true;
9776   }
9777   // Desugar down to a function type.
9778   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9779   // Reconstruct the pointer/reference as appropriate.
9780   if (isPointer) FnType = S.Context.getPointerType(FnType);
9781   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9782   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9783 
9784   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9785     << FnType;
9786 }
9787 
9788 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9789                                          SourceLocation OpLoc,
9790                                          OverloadCandidate *Cand) {
9791   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9792   std::string TypeStr("operator");
9793   TypeStr += Opc;
9794   TypeStr += "(";
9795   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9796   if (Cand->NumConversions == 1) {
9797     TypeStr += ")";
9798     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9799   } else {
9800     TypeStr += ", ";
9801     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9802     TypeStr += ")";
9803     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9804   }
9805 }
9806 
9807 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9808                                          OverloadCandidate *Cand) {
9809   unsigned NoOperands = Cand->NumConversions;
9810   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9811     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9812     if (ICS.isBad()) break; // all meaningless after first invalid
9813     if (!ICS.isAmbiguous()) continue;
9814 
9815     ICS.DiagnoseAmbiguousConversion(
9816         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
9817   }
9818 }
9819 
9820 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9821   if (Cand->Function)
9822     return Cand->Function->getLocation();
9823   if (Cand->IsSurrogate)
9824     return Cand->Surrogate->getLocation();
9825   return SourceLocation();
9826 }
9827 
9828 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9829   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9830   case Sema::TDK_Success:
9831     llvm_unreachable("TDK_success while diagnosing bad deduction");
9832 
9833   case Sema::TDK_Invalid:
9834   case Sema::TDK_Incomplete:
9835     return 1;
9836 
9837   case Sema::TDK_Underqualified:
9838   case Sema::TDK_Inconsistent:
9839     return 2;
9840 
9841   case Sema::TDK_SubstitutionFailure:
9842   case Sema::TDK_DeducedMismatch:
9843   case Sema::TDK_NonDeducedMismatch:
9844   case Sema::TDK_MiscellaneousDeductionFailure:
9845     return 3;
9846 
9847   case Sema::TDK_InstantiationDepth:
9848   case Sema::TDK_FailedOverloadResolution:
9849     return 4;
9850 
9851   case Sema::TDK_InvalidExplicitArguments:
9852     return 5;
9853 
9854   case Sema::TDK_TooManyArguments:
9855   case Sema::TDK_TooFewArguments:
9856     return 6;
9857   }
9858   llvm_unreachable("Unhandled deduction result");
9859 }
9860 
9861 namespace {
9862 struct CompareOverloadCandidatesForDisplay {
9863   Sema &S;
9864   SourceLocation Loc;
9865   size_t NumArgs;
9866 
9867   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9868       : S(S), NumArgs(nArgs) {}
9869 
9870   bool operator()(const OverloadCandidate *L,
9871                   const OverloadCandidate *R) {
9872     // Fast-path this check.
9873     if (L == R) return false;
9874 
9875     // Order first by viability.
9876     if (L->Viable) {
9877       if (!R->Viable) return true;
9878 
9879       // TODO: introduce a tri-valued comparison for overload
9880       // candidates.  Would be more worthwhile if we had a sort
9881       // that could exploit it.
9882       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9883       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9884     } else if (R->Viable)
9885       return false;
9886 
9887     assert(L->Viable == R->Viable);
9888 
9889     // Criteria by which we can sort non-viable candidates:
9890     if (!L->Viable) {
9891       // 1. Arity mismatches come after other candidates.
9892       if (L->FailureKind == ovl_fail_too_many_arguments ||
9893           L->FailureKind == ovl_fail_too_few_arguments) {
9894         if (R->FailureKind == ovl_fail_too_many_arguments ||
9895             R->FailureKind == ovl_fail_too_few_arguments) {
9896           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9897           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9898           if (LDist == RDist) {
9899             if (L->FailureKind == R->FailureKind)
9900               // Sort non-surrogates before surrogates.
9901               return !L->IsSurrogate && R->IsSurrogate;
9902             // Sort candidates requiring fewer parameters than there were
9903             // arguments given after candidates requiring more parameters
9904             // than there were arguments given.
9905             return L->FailureKind == ovl_fail_too_many_arguments;
9906           }
9907           return LDist < RDist;
9908         }
9909         return false;
9910       }
9911       if (R->FailureKind == ovl_fail_too_many_arguments ||
9912           R->FailureKind == ovl_fail_too_few_arguments)
9913         return true;
9914 
9915       // 2. Bad conversions come first and are ordered by the number
9916       // of bad conversions and quality of good conversions.
9917       if (L->FailureKind == ovl_fail_bad_conversion) {
9918         if (R->FailureKind != ovl_fail_bad_conversion)
9919           return true;
9920 
9921         // The conversion that can be fixed with a smaller number of changes,
9922         // comes first.
9923         unsigned numLFixes = L->Fix.NumConversionsFixed;
9924         unsigned numRFixes = R->Fix.NumConversionsFixed;
9925         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9926         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9927         if (numLFixes != numRFixes) {
9928           return numLFixes < numRFixes;
9929         }
9930 
9931         // If there's any ordering between the defined conversions...
9932         // FIXME: this might not be transitive.
9933         assert(L->NumConversions == R->NumConversions);
9934 
9935         int leftBetter = 0;
9936         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9937         for (unsigned E = L->NumConversions; I != E; ++I) {
9938           switch (CompareImplicitConversionSequences(S, Loc,
9939                                                      L->Conversions[I],
9940                                                      R->Conversions[I])) {
9941           case ImplicitConversionSequence::Better:
9942             leftBetter++;
9943             break;
9944 
9945           case ImplicitConversionSequence::Worse:
9946             leftBetter--;
9947             break;
9948 
9949           case ImplicitConversionSequence::Indistinguishable:
9950             break;
9951           }
9952         }
9953         if (leftBetter > 0) return true;
9954         if (leftBetter < 0) return false;
9955 
9956       } else if (R->FailureKind == ovl_fail_bad_conversion)
9957         return false;
9958 
9959       if (L->FailureKind == ovl_fail_bad_deduction) {
9960         if (R->FailureKind != ovl_fail_bad_deduction)
9961           return true;
9962 
9963         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9964           return RankDeductionFailure(L->DeductionFailure)
9965                < RankDeductionFailure(R->DeductionFailure);
9966       } else if (R->FailureKind == ovl_fail_bad_deduction)
9967         return false;
9968 
9969       // TODO: others?
9970     }
9971 
9972     // Sort everything else by location.
9973     SourceLocation LLoc = GetLocationForCandidate(L);
9974     SourceLocation RLoc = GetLocationForCandidate(R);
9975 
9976     // Put candidates without locations (e.g. builtins) at the end.
9977     if (LLoc.isInvalid()) return false;
9978     if (RLoc.isInvalid()) return true;
9979 
9980     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9981   }
9982 };
9983 }
9984 
9985 /// CompleteNonViableCandidate - Normally, overload resolution only
9986 /// computes up to the first. Produces the FixIt set if possible.
9987 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9988                                        ArrayRef<Expr *> Args) {
9989   assert(!Cand->Viable);
9990 
9991   // Don't do anything on failures other than bad conversion.
9992   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9993 
9994   // We only want the FixIts if all the arguments can be corrected.
9995   bool Unfixable = false;
9996   // Use a implicit copy initialization to check conversion fixes.
9997   Cand->Fix.setConversionChecker(TryCopyInitialization);
9998 
9999   // Skip forward to the first bad conversion.
10000   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10001   unsigned ConvCount = Cand->NumConversions;
10002   while (true) {
10003     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10004     ConvIdx++;
10005     if (Cand->Conversions[ConvIdx - 1].isBad()) {
10006       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
10007       break;
10008     }
10009   }
10010 
10011   if (ConvIdx == ConvCount)
10012     return;
10013 
10014   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10015          "remaining conversion is initialized?");
10016 
10017   // FIXME: this should probably be preserved from the overload
10018   // operation somehow.
10019   bool SuppressUserConversions = false;
10020 
10021   const FunctionProtoType* Proto;
10022   unsigned ArgIdx = ConvIdx;
10023 
10024   if (Cand->IsSurrogate) {
10025     QualType ConvType
10026       = Cand->Surrogate->getConversionType().getNonReferenceType();
10027     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10028       ConvType = ConvPtrType->getPointeeType();
10029     Proto = ConvType->getAs<FunctionProtoType>();
10030     ArgIdx--;
10031   } else if (Cand->Function) {
10032     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10033     if (isa<CXXMethodDecl>(Cand->Function) &&
10034         !isa<CXXConstructorDecl>(Cand->Function))
10035       ArgIdx--;
10036   } else {
10037     // Builtin binary operator with a bad first conversion.
10038     assert(ConvCount <= 3);
10039     for (; ConvIdx != ConvCount; ++ConvIdx)
10040       Cand->Conversions[ConvIdx]
10041         = TryCopyInitialization(S, Args[ConvIdx],
10042                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10043                                 SuppressUserConversions,
10044                                 /*InOverloadResolution*/ true,
10045                                 /*AllowObjCWritebackConversion=*/
10046                                   S.getLangOpts().ObjCAutoRefCount);
10047     return;
10048   }
10049 
10050   // Fill in the rest of the conversions.
10051   unsigned NumParams = Proto->getNumParams();
10052   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10053     if (ArgIdx < NumParams) {
10054       Cand->Conversions[ConvIdx] = TryCopyInitialization(
10055           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10056           /*InOverloadResolution=*/true,
10057           /*AllowObjCWritebackConversion=*/
10058           S.getLangOpts().ObjCAutoRefCount);
10059       // Store the FixIt in the candidate if it exists.
10060       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10061         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10062     }
10063     else
10064       Cand->Conversions[ConvIdx].setEllipsis();
10065   }
10066 }
10067 
10068 /// PrintOverloadCandidates - When overload resolution fails, prints
10069 /// diagnostic messages containing the candidates in the candidate
10070 /// set.
10071 void OverloadCandidateSet::NoteCandidates(Sema &S,
10072                                           OverloadCandidateDisplayKind OCD,
10073                                           ArrayRef<Expr *> Args,
10074                                           StringRef Opc,
10075                                           SourceLocation OpLoc) {
10076   // Sort the candidates by viability and position.  Sorting directly would
10077   // be prohibitive, so we make a set of pointers and sort those.
10078   SmallVector<OverloadCandidate*, 32> Cands;
10079   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10080   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10081     if (Cand->Viable)
10082       Cands.push_back(Cand);
10083     else if (OCD == OCD_AllCandidates) {
10084       CompleteNonViableCandidate(S, Cand, Args);
10085       if (Cand->Function || Cand->IsSurrogate)
10086         Cands.push_back(Cand);
10087       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10088       // want to list every possible builtin candidate.
10089     }
10090   }
10091 
10092   std::sort(Cands.begin(), Cands.end(),
10093             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10094 
10095   bool ReportedAmbiguousConversions = false;
10096 
10097   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10098   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10099   unsigned CandsShown = 0;
10100   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10101     OverloadCandidate *Cand = *I;
10102 
10103     // Set an arbitrary limit on the number of candidate functions we'll spam
10104     // the user with.  FIXME: This limit should depend on details of the
10105     // candidate list.
10106     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10107       break;
10108     }
10109     ++CandsShown;
10110 
10111     if (Cand->Function)
10112       NoteFunctionCandidate(S, Cand, Args.size(),
10113                             /*TakingCandidateAddress=*/false);
10114     else if (Cand->IsSurrogate)
10115       NoteSurrogateCandidate(S, Cand);
10116     else {
10117       assert(Cand->Viable &&
10118              "Non-viable built-in candidates are not added to Cands.");
10119       // Generally we only see ambiguities including viable builtin
10120       // operators if overload resolution got screwed up by an
10121       // ambiguous user-defined conversion.
10122       //
10123       // FIXME: It's quite possible for different conversions to see
10124       // different ambiguities, though.
10125       if (!ReportedAmbiguousConversions) {
10126         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10127         ReportedAmbiguousConversions = true;
10128       }
10129 
10130       // If this is a viable builtin, print it.
10131       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10132     }
10133   }
10134 
10135   if (I != E)
10136     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10137 }
10138 
10139 static SourceLocation
10140 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10141   return Cand->Specialization ? Cand->Specialization->getLocation()
10142                               : SourceLocation();
10143 }
10144 
10145 namespace {
10146 struct CompareTemplateSpecCandidatesForDisplay {
10147   Sema &S;
10148   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10149 
10150   bool operator()(const TemplateSpecCandidate *L,
10151                   const TemplateSpecCandidate *R) {
10152     // Fast-path this check.
10153     if (L == R)
10154       return false;
10155 
10156     // Assuming that both candidates are not matches...
10157 
10158     // Sort by the ranking of deduction failures.
10159     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10160       return RankDeductionFailure(L->DeductionFailure) <
10161              RankDeductionFailure(R->DeductionFailure);
10162 
10163     // Sort everything else by location.
10164     SourceLocation LLoc = GetLocationForCandidate(L);
10165     SourceLocation RLoc = GetLocationForCandidate(R);
10166 
10167     // Put candidates without locations (e.g. builtins) at the end.
10168     if (LLoc.isInvalid())
10169       return false;
10170     if (RLoc.isInvalid())
10171       return true;
10172 
10173     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10174   }
10175 };
10176 }
10177 
10178 /// Diagnose a template argument deduction failure.
10179 /// We are treating these failures as overload failures due to bad
10180 /// deductions.
10181 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10182                                                  bool ForTakingAddress) {
10183   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10184                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10185 }
10186 
10187 void TemplateSpecCandidateSet::destroyCandidates() {
10188   for (iterator i = begin(), e = end(); i != e; ++i) {
10189     i->DeductionFailure.Destroy();
10190   }
10191 }
10192 
10193 void TemplateSpecCandidateSet::clear() {
10194   destroyCandidates();
10195   Candidates.clear();
10196 }
10197 
10198 /// NoteCandidates - When no template specialization match is found, prints
10199 /// diagnostic messages containing the non-matching specializations that form
10200 /// the candidate set.
10201 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10202 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10203 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10204   // Sort the candidates by position (assuming no candidate is a match).
10205   // Sorting directly would be prohibitive, so we make a set of pointers
10206   // and sort those.
10207   SmallVector<TemplateSpecCandidate *, 32> Cands;
10208   Cands.reserve(size());
10209   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10210     if (Cand->Specialization)
10211       Cands.push_back(Cand);
10212     // Otherwise, this is a non-matching builtin candidate.  We do not,
10213     // in general, want to list every possible builtin candidate.
10214   }
10215 
10216   std::sort(Cands.begin(), Cands.end(),
10217             CompareTemplateSpecCandidatesForDisplay(S));
10218 
10219   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10220   // for generalization purposes (?).
10221   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10222 
10223   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10224   unsigned CandsShown = 0;
10225   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10226     TemplateSpecCandidate *Cand = *I;
10227 
10228     // Set an arbitrary limit on the number of candidates we'll spam
10229     // the user with.  FIXME: This limit should depend on details of the
10230     // candidate list.
10231     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10232       break;
10233     ++CandsShown;
10234 
10235     assert(Cand->Specialization &&
10236            "Non-matching built-in candidates are not added to Cands.");
10237     Cand->NoteDeductionFailure(S, ForTakingAddress);
10238   }
10239 
10240   if (I != E)
10241     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10242 }
10243 
10244 // [PossiblyAFunctionType]  -->   [Return]
10245 // NonFunctionType --> NonFunctionType
10246 // R (A) --> R(A)
10247 // R (*)(A) --> R (A)
10248 // R (&)(A) --> R (A)
10249 // R (S::*)(A) --> R (A)
10250 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10251   QualType Ret = PossiblyAFunctionType;
10252   if (const PointerType *ToTypePtr =
10253     PossiblyAFunctionType->getAs<PointerType>())
10254     Ret = ToTypePtr->getPointeeType();
10255   else if (const ReferenceType *ToTypeRef =
10256     PossiblyAFunctionType->getAs<ReferenceType>())
10257     Ret = ToTypeRef->getPointeeType();
10258   else if (const MemberPointerType *MemTypePtr =
10259     PossiblyAFunctionType->getAs<MemberPointerType>())
10260     Ret = MemTypePtr->getPointeeType();
10261   Ret =
10262     Context.getCanonicalType(Ret).getUnqualifiedType();
10263   return Ret;
10264 }
10265 
10266 namespace {
10267 // A helper class to help with address of function resolution
10268 // - allows us to avoid passing around all those ugly parameters
10269 class AddressOfFunctionResolver {
10270   Sema& S;
10271   Expr* SourceExpr;
10272   const QualType& TargetType;
10273   QualType TargetFunctionType; // Extracted function type from target type
10274 
10275   bool Complain;
10276   //DeclAccessPair& ResultFunctionAccessPair;
10277   ASTContext& Context;
10278 
10279   bool TargetTypeIsNonStaticMemberFunction;
10280   bool FoundNonTemplateFunction;
10281   bool StaticMemberFunctionFromBoundPointer;
10282   bool HasComplained;
10283 
10284   OverloadExpr::FindResult OvlExprInfo;
10285   OverloadExpr *OvlExpr;
10286   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10287   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10288   TemplateSpecCandidateSet FailedCandidates;
10289 
10290 public:
10291   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10292                             const QualType &TargetType, bool Complain)
10293       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10294         Complain(Complain), Context(S.getASTContext()),
10295         TargetTypeIsNonStaticMemberFunction(
10296             !!TargetType->getAs<MemberPointerType>()),
10297         FoundNonTemplateFunction(false),
10298         StaticMemberFunctionFromBoundPointer(false),
10299         HasComplained(false),
10300         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10301         OvlExpr(OvlExprInfo.Expression),
10302         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10303     ExtractUnqualifiedFunctionTypeFromTargetType();
10304 
10305     if (TargetFunctionType->isFunctionType()) {
10306       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10307         if (!UME->isImplicitAccess() &&
10308             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10309           StaticMemberFunctionFromBoundPointer = true;
10310     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10311       DeclAccessPair dap;
10312       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10313               OvlExpr, false, &dap)) {
10314         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10315           if (!Method->isStatic()) {
10316             // If the target type is a non-function type and the function found
10317             // is a non-static member function, pretend as if that was the
10318             // target, it's the only possible type to end up with.
10319             TargetTypeIsNonStaticMemberFunction = true;
10320 
10321             // And skip adding the function if its not in the proper form.
10322             // We'll diagnose this due to an empty set of functions.
10323             if (!OvlExprInfo.HasFormOfMemberPointer)
10324               return;
10325           }
10326 
10327         Matches.push_back(std::make_pair(dap, Fn));
10328       }
10329       return;
10330     }
10331 
10332     if (OvlExpr->hasExplicitTemplateArgs())
10333       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10334 
10335     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10336       // C++ [over.over]p4:
10337       //   If more than one function is selected, [...]
10338       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10339         if (FoundNonTemplateFunction)
10340           EliminateAllTemplateMatches();
10341         else
10342           EliminateAllExceptMostSpecializedTemplate();
10343       }
10344     }
10345 
10346     if (S.getLangOpts().CUDA && Matches.size() > 1)
10347       EliminateSuboptimalCudaMatches();
10348   }
10349 
10350   bool hasComplained() const { return HasComplained; }
10351 
10352 private:
10353   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10354     QualType Discard;
10355     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10356            S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
10357   }
10358 
10359   /// \return true if A is considered a better overload candidate for the
10360   /// desired type than B.
10361   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10362     // If A doesn't have exactly the correct type, we don't want to classify it
10363     // as "better" than anything else. This way, the user is required to
10364     // disambiguate for us if there are multiple candidates and no exact match.
10365     return candidateHasExactlyCorrectType(A) &&
10366            (!candidateHasExactlyCorrectType(B) ||
10367             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10368   }
10369 
10370   /// \return true if we were able to eliminate all but one overload candidate,
10371   /// false otherwise.
10372   bool eliminiateSuboptimalOverloadCandidates() {
10373     // Same algorithm as overload resolution -- one pass to pick the "best",
10374     // another pass to be sure that nothing is better than the best.
10375     auto Best = Matches.begin();
10376     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10377       if (isBetterCandidate(I->second, Best->second))
10378         Best = I;
10379 
10380     const FunctionDecl *BestFn = Best->second;
10381     auto IsBestOrInferiorToBest = [this, BestFn](
10382         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10383       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10384     };
10385 
10386     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10387     // option, so we can potentially give the user a better error
10388     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10389       return false;
10390     Matches[0] = *Best;
10391     Matches.resize(1);
10392     return true;
10393   }
10394 
10395   bool isTargetTypeAFunction() const {
10396     return TargetFunctionType->isFunctionType();
10397   }
10398 
10399   // [ToType]     [Return]
10400 
10401   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10402   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10403   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10404   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10405     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10406   }
10407 
10408   // return true if any matching specializations were found
10409   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10410                                    const DeclAccessPair& CurAccessFunPair) {
10411     if (CXXMethodDecl *Method
10412               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10413       // Skip non-static function templates when converting to pointer, and
10414       // static when converting to member pointer.
10415       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10416         return false;
10417     }
10418     else if (TargetTypeIsNonStaticMemberFunction)
10419       return false;
10420 
10421     // C++ [over.over]p2:
10422     //   If the name is a function template, template argument deduction is
10423     //   done (14.8.2.2), and if the argument deduction succeeds, the
10424     //   resulting template argument list is used to generate a single
10425     //   function template specialization, which is added to the set of
10426     //   overloaded functions considered.
10427     FunctionDecl *Specialization = nullptr;
10428     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10429     if (Sema::TemplateDeductionResult Result
10430           = S.DeduceTemplateArguments(FunctionTemplate,
10431                                       &OvlExplicitTemplateArgs,
10432                                       TargetFunctionType, Specialization,
10433                                       Info, /*InOverloadResolution=*/true)) {
10434       // Make a note of the failed deduction for diagnostics.
10435       FailedCandidates.addCandidate()
10436           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10437                MakeDeductionFailureInfo(Context, Result, Info));
10438       return false;
10439     }
10440 
10441     // Template argument deduction ensures that we have an exact match or
10442     // compatible pointer-to-function arguments that would be adjusted by ICS.
10443     // This function template specicalization works.
10444     assert(S.isSameOrCompatibleFunctionType(
10445               Context.getCanonicalType(Specialization->getType()),
10446               Context.getCanonicalType(TargetFunctionType)));
10447 
10448     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10449       return false;
10450 
10451     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10452     return true;
10453   }
10454 
10455   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10456                                       const DeclAccessPair& CurAccessFunPair) {
10457     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10458       // Skip non-static functions when converting to pointer, and static
10459       // when converting to member pointer.
10460       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10461         return false;
10462     }
10463     else if (TargetTypeIsNonStaticMemberFunction)
10464       return false;
10465 
10466     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10467       if (S.getLangOpts().CUDA)
10468         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10469           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
10470             return false;
10471 
10472       // If any candidate has a placeholder return type, trigger its deduction
10473       // now.
10474       if (S.getLangOpts().CPlusPlus14 &&
10475           FunDecl->getReturnType()->isUndeducedType() &&
10476           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10477         HasComplained |= Complain;
10478         return false;
10479       }
10480 
10481       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10482         return false;
10483 
10484       // If we're in C, we need to support types that aren't exactly identical.
10485       if (!S.getLangOpts().CPlusPlus ||
10486           candidateHasExactlyCorrectType(FunDecl)) {
10487         Matches.push_back(std::make_pair(
10488             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10489         FoundNonTemplateFunction = true;
10490         return true;
10491       }
10492     }
10493 
10494     return false;
10495   }
10496 
10497   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10498     bool Ret = false;
10499 
10500     // If the overload expression doesn't have the form of a pointer to
10501     // member, don't try to convert it to a pointer-to-member type.
10502     if (IsInvalidFormOfPointerToMemberFunction())
10503       return false;
10504 
10505     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10506                                E = OvlExpr->decls_end();
10507          I != E; ++I) {
10508       // Look through any using declarations to find the underlying function.
10509       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10510 
10511       // C++ [over.over]p3:
10512       //   Non-member functions and static member functions match
10513       //   targets of type "pointer-to-function" or "reference-to-function."
10514       //   Nonstatic member functions match targets of
10515       //   type "pointer-to-member-function."
10516       // Note that according to DR 247, the containing class does not matter.
10517       if (FunctionTemplateDecl *FunctionTemplate
10518                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10519         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10520           Ret = true;
10521       }
10522       // If we have explicit template arguments supplied, skip non-templates.
10523       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10524                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10525         Ret = true;
10526     }
10527     assert(Ret || Matches.empty());
10528     return Ret;
10529   }
10530 
10531   void EliminateAllExceptMostSpecializedTemplate() {
10532     //   [...] and any given function template specialization F1 is
10533     //   eliminated if the set contains a second function template
10534     //   specialization whose function template is more specialized
10535     //   than the function template of F1 according to the partial
10536     //   ordering rules of 14.5.5.2.
10537 
10538     // The algorithm specified above is quadratic. We instead use a
10539     // two-pass algorithm (similar to the one used to identify the
10540     // best viable function in an overload set) that identifies the
10541     // best function template (if it exists).
10542 
10543     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10544     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10545       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10546 
10547     // TODO: It looks like FailedCandidates does not serve much purpose
10548     // here, since the no_viable diagnostic has index 0.
10549     UnresolvedSetIterator Result = S.getMostSpecialized(
10550         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10551         SourceExpr->getLocStart(), S.PDiag(),
10552         S.PDiag(diag::err_addr_ovl_ambiguous)
10553           << Matches[0].second->getDeclName(),
10554         S.PDiag(diag::note_ovl_candidate)
10555           << (unsigned)oc_function_template,
10556         Complain, TargetFunctionType);
10557 
10558     if (Result != MatchesCopy.end()) {
10559       // Make it the first and only element
10560       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10561       Matches[0].second = cast<FunctionDecl>(*Result);
10562       Matches.resize(1);
10563     } else
10564       HasComplained |= Complain;
10565   }
10566 
10567   void EliminateAllTemplateMatches() {
10568     //   [...] any function template specializations in the set are
10569     //   eliminated if the set also contains a non-template function, [...]
10570     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10571       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10572         ++I;
10573       else {
10574         Matches[I] = Matches[--N];
10575         Matches.resize(N);
10576       }
10577     }
10578   }
10579 
10580   void EliminateSuboptimalCudaMatches() {
10581     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10582   }
10583 
10584 public:
10585   void ComplainNoMatchesFound() const {
10586     assert(Matches.empty());
10587     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10588         << OvlExpr->getName() << TargetFunctionType
10589         << OvlExpr->getSourceRange();
10590     if (FailedCandidates.empty())
10591       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10592                                   /*TakingAddress=*/true);
10593     else {
10594       // We have some deduction failure messages. Use them to diagnose
10595       // the function templates, and diagnose the non-template candidates
10596       // normally.
10597       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10598                                  IEnd = OvlExpr->decls_end();
10599            I != IEnd; ++I)
10600         if (FunctionDecl *Fun =
10601                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10602           if (!functionHasPassObjectSizeParams(Fun))
10603             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10604                                     /*TakingAddress=*/true);
10605       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10606     }
10607   }
10608 
10609   bool IsInvalidFormOfPointerToMemberFunction() const {
10610     return TargetTypeIsNonStaticMemberFunction &&
10611       !OvlExprInfo.HasFormOfMemberPointer;
10612   }
10613 
10614   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10615       // TODO: Should we condition this on whether any functions might
10616       // have matched, or is it more appropriate to do that in callers?
10617       // TODO: a fixit wouldn't hurt.
10618       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10619         << TargetType << OvlExpr->getSourceRange();
10620   }
10621 
10622   bool IsStaticMemberFunctionFromBoundPointer() const {
10623     return StaticMemberFunctionFromBoundPointer;
10624   }
10625 
10626   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10627     S.Diag(OvlExpr->getLocStart(),
10628            diag::err_invalid_form_pointer_member_function)
10629       << OvlExpr->getSourceRange();
10630   }
10631 
10632   void ComplainOfInvalidConversion() const {
10633     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10634       << OvlExpr->getName() << TargetType;
10635   }
10636 
10637   void ComplainMultipleMatchesFound() const {
10638     assert(Matches.size() > 1);
10639     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10640       << OvlExpr->getName()
10641       << OvlExpr->getSourceRange();
10642     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10643                                 /*TakingAddress=*/true);
10644   }
10645 
10646   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10647 
10648   int getNumMatches() const { return Matches.size(); }
10649 
10650   FunctionDecl* getMatchingFunctionDecl() const {
10651     if (Matches.size() != 1) return nullptr;
10652     return Matches[0].second;
10653   }
10654 
10655   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10656     if (Matches.size() != 1) return nullptr;
10657     return &Matches[0].first;
10658   }
10659 };
10660 }
10661 
10662 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10663 /// an overloaded function (C++ [over.over]), where @p From is an
10664 /// expression with overloaded function type and @p ToType is the type
10665 /// we're trying to resolve to. For example:
10666 ///
10667 /// @code
10668 /// int f(double);
10669 /// int f(int);
10670 ///
10671 /// int (*pfd)(double) = f; // selects f(double)
10672 /// @endcode
10673 ///
10674 /// This routine returns the resulting FunctionDecl if it could be
10675 /// resolved, and NULL otherwise. When @p Complain is true, this
10676 /// routine will emit diagnostics if there is an error.
10677 FunctionDecl *
10678 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10679                                          QualType TargetType,
10680                                          bool Complain,
10681                                          DeclAccessPair &FoundResult,
10682                                          bool *pHadMultipleCandidates) {
10683   assert(AddressOfExpr->getType() == Context.OverloadTy);
10684 
10685   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10686                                      Complain);
10687   int NumMatches = Resolver.getNumMatches();
10688   FunctionDecl *Fn = nullptr;
10689   bool ShouldComplain = Complain && !Resolver.hasComplained();
10690   if (NumMatches == 0 && ShouldComplain) {
10691     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10692       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10693     else
10694       Resolver.ComplainNoMatchesFound();
10695   }
10696   else if (NumMatches > 1 && ShouldComplain)
10697     Resolver.ComplainMultipleMatchesFound();
10698   else if (NumMatches == 1) {
10699     Fn = Resolver.getMatchingFunctionDecl();
10700     assert(Fn);
10701     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10702     if (Complain) {
10703       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10704         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10705       else
10706         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10707     }
10708   }
10709 
10710   if (pHadMultipleCandidates)
10711     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10712   return Fn;
10713 }
10714 
10715 /// \brief Given an expression that refers to an overloaded function, try to
10716 /// resolve that function to a single function that can have its address taken.
10717 /// This will modify `Pair` iff it returns non-null.
10718 ///
10719 /// This routine can only realistically succeed if all but one candidates in the
10720 /// overload set for SrcExpr cannot have their addresses taken.
10721 FunctionDecl *
10722 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10723                                                   DeclAccessPair &Pair) {
10724   OverloadExpr::FindResult R = OverloadExpr::find(E);
10725   OverloadExpr *Ovl = R.Expression;
10726   FunctionDecl *Result = nullptr;
10727   DeclAccessPair DAP;
10728   // Don't use the AddressOfResolver because we're specifically looking for
10729   // cases where we have one overload candidate that lacks
10730   // enable_if/pass_object_size/...
10731   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10732     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10733     if (!FD)
10734       return nullptr;
10735 
10736     if (!checkAddressOfFunctionIsAvailable(FD))
10737       continue;
10738 
10739     // We have more than one result; quit.
10740     if (Result)
10741       return nullptr;
10742     DAP = I.getPair();
10743     Result = FD;
10744   }
10745 
10746   if (Result)
10747     Pair = DAP;
10748   return Result;
10749 }
10750 
10751 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
10752 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10753 /// will perform access checks, diagnose the use of the resultant decl, and, if
10754 /// necessary, perform a function-to-pointer decay.
10755 ///
10756 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10757 /// Otherwise, returns true. This may emit diagnostics and return true.
10758 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10759     ExprResult &SrcExpr) {
10760   Expr *E = SrcExpr.get();
10761   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10762 
10763   DeclAccessPair DAP;
10764   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10765   if (!Found)
10766     return false;
10767 
10768   // Emitting multiple diagnostics for a function that is both inaccessible and
10769   // unavailable is consistent with our behavior elsewhere. So, always check
10770   // for both.
10771   DiagnoseUseOfDecl(Found, E->getExprLoc());
10772   CheckAddressOfMemberAccess(E, DAP);
10773   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10774   if (Fixed->getType()->isFunctionType())
10775     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10776   else
10777     SrcExpr = Fixed;
10778   return true;
10779 }
10780 
10781 /// \brief Given an expression that refers to an overloaded function, try to
10782 /// resolve that overloaded function expression down to a single function.
10783 ///
10784 /// This routine can only resolve template-ids that refer to a single function
10785 /// template, where that template-id refers to a single template whose template
10786 /// arguments are either provided by the template-id or have defaults,
10787 /// as described in C++0x [temp.arg.explicit]p3.
10788 ///
10789 /// If no template-ids are found, no diagnostics are emitted and NULL is
10790 /// returned.
10791 FunctionDecl *
10792 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10793                                                   bool Complain,
10794                                                   DeclAccessPair *FoundResult) {
10795   // C++ [over.over]p1:
10796   //   [...] [Note: any redundant set of parentheses surrounding the
10797   //   overloaded function name is ignored (5.1). ]
10798   // C++ [over.over]p1:
10799   //   [...] The overloaded function name can be preceded by the &
10800   //   operator.
10801 
10802   // If we didn't actually find any template-ids, we're done.
10803   if (!ovl->hasExplicitTemplateArgs())
10804     return nullptr;
10805 
10806   TemplateArgumentListInfo ExplicitTemplateArgs;
10807   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10808   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10809 
10810   // Look through all of the overloaded functions, searching for one
10811   // whose type matches exactly.
10812   FunctionDecl *Matched = nullptr;
10813   for (UnresolvedSetIterator I = ovl->decls_begin(),
10814          E = ovl->decls_end(); I != E; ++I) {
10815     // C++0x [temp.arg.explicit]p3:
10816     //   [...] In contexts where deduction is done and fails, or in contexts
10817     //   where deduction is not done, if a template argument list is
10818     //   specified and it, along with any default template arguments,
10819     //   identifies a single function template specialization, then the
10820     //   template-id is an lvalue for the function template specialization.
10821     FunctionTemplateDecl *FunctionTemplate
10822       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10823 
10824     // C++ [over.over]p2:
10825     //   If the name is a function template, template argument deduction is
10826     //   done (14.8.2.2), and if the argument deduction succeeds, the
10827     //   resulting template argument list is used to generate a single
10828     //   function template specialization, which is added to the set of
10829     //   overloaded functions considered.
10830     FunctionDecl *Specialization = nullptr;
10831     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10832     if (TemplateDeductionResult Result
10833           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10834                                     Specialization, Info,
10835                                     /*InOverloadResolution=*/true)) {
10836       // Make a note of the failed deduction for diagnostics.
10837       // TODO: Actually use the failed-deduction info?
10838       FailedCandidates.addCandidate()
10839           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
10840                MakeDeductionFailureInfo(Context, Result, Info));
10841       continue;
10842     }
10843 
10844     assert(Specialization && "no specialization and no error?");
10845 
10846     // Multiple matches; we can't resolve to a single declaration.
10847     if (Matched) {
10848       if (Complain) {
10849         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10850           << ovl->getName();
10851         NoteAllOverloadCandidates(ovl);
10852       }
10853       return nullptr;
10854     }
10855 
10856     Matched = Specialization;
10857     if (FoundResult) *FoundResult = I.getPair();
10858   }
10859 
10860   if (Matched && getLangOpts().CPlusPlus14 &&
10861       Matched->getReturnType()->isUndeducedType() &&
10862       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10863     return nullptr;
10864 
10865   return Matched;
10866 }
10867 
10868 
10869 
10870 
10871 // Resolve and fix an overloaded expression that can be resolved
10872 // because it identifies a single function template specialization.
10873 //
10874 // Last three arguments should only be supplied if Complain = true
10875 //
10876 // Return true if it was logically possible to so resolve the
10877 // expression, regardless of whether or not it succeeded.  Always
10878 // returns true if 'complain' is set.
10879 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10880                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10881                       bool complain, SourceRange OpRangeForComplaining,
10882                                            QualType DestTypeForComplaining,
10883                                             unsigned DiagIDForComplaining) {
10884   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10885 
10886   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10887 
10888   DeclAccessPair found;
10889   ExprResult SingleFunctionExpression;
10890   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10891                            ovl.Expression, /*complain*/ false, &found)) {
10892     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10893       SrcExpr = ExprError();
10894       return true;
10895     }
10896 
10897     // It is only correct to resolve to an instance method if we're
10898     // resolving a form that's permitted to be a pointer to member.
10899     // Otherwise we'll end up making a bound member expression, which
10900     // is illegal in all the contexts we resolve like this.
10901     if (!ovl.HasFormOfMemberPointer &&
10902         isa<CXXMethodDecl>(fn) &&
10903         cast<CXXMethodDecl>(fn)->isInstance()) {
10904       if (!complain) return false;
10905 
10906       Diag(ovl.Expression->getExprLoc(),
10907            diag::err_bound_member_function)
10908         << 0 << ovl.Expression->getSourceRange();
10909 
10910       // TODO: I believe we only end up here if there's a mix of
10911       // static and non-static candidates (otherwise the expression
10912       // would have 'bound member' type, not 'overload' type).
10913       // Ideally we would note which candidate was chosen and why
10914       // the static candidates were rejected.
10915       SrcExpr = ExprError();
10916       return true;
10917     }
10918 
10919     // Fix the expression to refer to 'fn'.
10920     SingleFunctionExpression =
10921         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10922 
10923     // If desired, do function-to-pointer decay.
10924     if (doFunctionPointerConverion) {
10925       SingleFunctionExpression =
10926         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10927       if (SingleFunctionExpression.isInvalid()) {
10928         SrcExpr = ExprError();
10929         return true;
10930       }
10931     }
10932   }
10933 
10934   if (!SingleFunctionExpression.isUsable()) {
10935     if (complain) {
10936       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10937         << ovl.Expression->getName()
10938         << DestTypeForComplaining
10939         << OpRangeForComplaining
10940         << ovl.Expression->getQualifierLoc().getSourceRange();
10941       NoteAllOverloadCandidates(SrcExpr.get());
10942 
10943       SrcExpr = ExprError();
10944       return true;
10945     }
10946 
10947     return false;
10948   }
10949 
10950   SrcExpr = SingleFunctionExpression;
10951   return true;
10952 }
10953 
10954 /// \brief Add a single candidate to the overload set.
10955 static void AddOverloadedCallCandidate(Sema &S,
10956                                        DeclAccessPair FoundDecl,
10957                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10958                                        ArrayRef<Expr *> Args,
10959                                        OverloadCandidateSet &CandidateSet,
10960                                        bool PartialOverloading,
10961                                        bool KnownValid) {
10962   NamedDecl *Callee = FoundDecl.getDecl();
10963   if (isa<UsingShadowDecl>(Callee))
10964     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10965 
10966   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10967     if (ExplicitTemplateArgs) {
10968       assert(!KnownValid && "Explicit template arguments?");
10969       return;
10970     }
10971     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10972                            /*SuppressUsedConversions=*/false,
10973                            PartialOverloading);
10974     return;
10975   }
10976 
10977   if (FunctionTemplateDecl *FuncTemplate
10978       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10979     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10980                                    ExplicitTemplateArgs, Args, CandidateSet,
10981                                    /*SuppressUsedConversions=*/false,
10982                                    PartialOverloading);
10983     return;
10984   }
10985 
10986   assert(!KnownValid && "unhandled case in overloaded call candidate");
10987 }
10988 
10989 /// \brief Add the overload candidates named by callee and/or found by argument
10990 /// dependent lookup to the given overload set.
10991 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10992                                        ArrayRef<Expr *> Args,
10993                                        OverloadCandidateSet &CandidateSet,
10994                                        bool PartialOverloading) {
10995 
10996 #ifndef NDEBUG
10997   // Verify that ArgumentDependentLookup is consistent with the rules
10998   // in C++0x [basic.lookup.argdep]p3:
10999   //
11000   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11001   //   and let Y be the lookup set produced by argument dependent
11002   //   lookup (defined as follows). If X contains
11003   //
11004   //     -- a declaration of a class member, or
11005   //
11006   //     -- a block-scope function declaration that is not a
11007   //        using-declaration, or
11008   //
11009   //     -- a declaration that is neither a function or a function
11010   //        template
11011   //
11012   //   then Y is empty.
11013 
11014   if (ULE->requiresADL()) {
11015     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11016            E = ULE->decls_end(); I != E; ++I) {
11017       assert(!(*I)->getDeclContext()->isRecord());
11018       assert(isa<UsingShadowDecl>(*I) ||
11019              !(*I)->getDeclContext()->isFunctionOrMethod());
11020       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11021     }
11022   }
11023 #endif
11024 
11025   // It would be nice to avoid this copy.
11026   TemplateArgumentListInfo TABuffer;
11027   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11028   if (ULE->hasExplicitTemplateArgs()) {
11029     ULE->copyTemplateArgumentsInto(TABuffer);
11030     ExplicitTemplateArgs = &TABuffer;
11031   }
11032 
11033   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11034          E = ULE->decls_end(); I != E; ++I)
11035     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11036                                CandidateSet, PartialOverloading,
11037                                /*KnownValid*/ true);
11038 
11039   if (ULE->requiresADL())
11040     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11041                                          Args, ExplicitTemplateArgs,
11042                                          CandidateSet, PartialOverloading);
11043 }
11044 
11045 /// Determine whether a declaration with the specified name could be moved into
11046 /// a different namespace.
11047 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11048   switch (Name.getCXXOverloadedOperator()) {
11049   case OO_New: case OO_Array_New:
11050   case OO_Delete: case OO_Array_Delete:
11051     return false;
11052 
11053   default:
11054     return true;
11055   }
11056 }
11057 
11058 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11059 /// template, where the non-dependent name was declared after the template
11060 /// was defined. This is common in code written for a compilers which do not
11061 /// correctly implement two-stage name lookup.
11062 ///
11063 /// Returns true if a viable candidate was found and a diagnostic was issued.
11064 static bool
11065 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11066                        const CXXScopeSpec &SS, LookupResult &R,
11067                        OverloadCandidateSet::CandidateSetKind CSK,
11068                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11069                        ArrayRef<Expr *> Args,
11070                        bool *DoDiagnoseEmptyLookup = nullptr) {
11071   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11072     return false;
11073 
11074   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11075     if (DC->isTransparentContext())
11076       continue;
11077 
11078     SemaRef.LookupQualifiedName(R, DC);
11079 
11080     if (!R.empty()) {
11081       R.suppressDiagnostics();
11082 
11083       if (isa<CXXRecordDecl>(DC)) {
11084         // Don't diagnose names we find in classes; we get much better
11085         // diagnostics for these from DiagnoseEmptyLookup.
11086         R.clear();
11087         if (DoDiagnoseEmptyLookup)
11088           *DoDiagnoseEmptyLookup = true;
11089         return false;
11090       }
11091 
11092       OverloadCandidateSet Candidates(FnLoc, CSK);
11093       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11094         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11095                                    ExplicitTemplateArgs, Args,
11096                                    Candidates, false, /*KnownValid*/ false);
11097 
11098       OverloadCandidateSet::iterator Best;
11099       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11100         // No viable functions. Don't bother the user with notes for functions
11101         // which don't work and shouldn't be found anyway.
11102         R.clear();
11103         return false;
11104       }
11105 
11106       // Find the namespaces where ADL would have looked, and suggest
11107       // declaring the function there instead.
11108       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11109       Sema::AssociatedClassSet AssociatedClasses;
11110       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11111                                                  AssociatedNamespaces,
11112                                                  AssociatedClasses);
11113       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11114       if (canBeDeclaredInNamespace(R.getLookupName())) {
11115         DeclContext *Std = SemaRef.getStdNamespace();
11116         for (Sema::AssociatedNamespaceSet::iterator
11117                it = AssociatedNamespaces.begin(),
11118                end = AssociatedNamespaces.end(); it != end; ++it) {
11119           // Never suggest declaring a function within namespace 'std'.
11120           if (Std && Std->Encloses(*it))
11121             continue;
11122 
11123           // Never suggest declaring a function within a namespace with a
11124           // reserved name, like __gnu_cxx.
11125           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11126           if (NS &&
11127               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11128             continue;
11129 
11130           SuggestedNamespaces.insert(*it);
11131         }
11132       }
11133 
11134       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11135         << R.getLookupName();
11136       if (SuggestedNamespaces.empty()) {
11137         SemaRef.Diag(Best->Function->getLocation(),
11138                      diag::note_not_found_by_two_phase_lookup)
11139           << R.getLookupName() << 0;
11140       } else if (SuggestedNamespaces.size() == 1) {
11141         SemaRef.Diag(Best->Function->getLocation(),
11142                      diag::note_not_found_by_two_phase_lookup)
11143           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11144       } else {
11145         // FIXME: It would be useful to list the associated namespaces here,
11146         // but the diagnostics infrastructure doesn't provide a way to produce
11147         // a localized representation of a list of items.
11148         SemaRef.Diag(Best->Function->getLocation(),
11149                      diag::note_not_found_by_two_phase_lookup)
11150           << R.getLookupName() << 2;
11151       }
11152 
11153       // Try to recover by calling this function.
11154       return true;
11155     }
11156 
11157     R.clear();
11158   }
11159 
11160   return false;
11161 }
11162 
11163 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11164 /// template, where the non-dependent operator was declared after the template
11165 /// was defined.
11166 ///
11167 /// Returns true if a viable candidate was found and a diagnostic was issued.
11168 static bool
11169 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11170                                SourceLocation OpLoc,
11171                                ArrayRef<Expr *> Args) {
11172   DeclarationName OpName =
11173     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11174   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11175   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11176                                 OverloadCandidateSet::CSK_Operator,
11177                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11178 }
11179 
11180 namespace {
11181 class BuildRecoveryCallExprRAII {
11182   Sema &SemaRef;
11183 public:
11184   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11185     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11186     SemaRef.IsBuildingRecoveryCallExpr = true;
11187   }
11188 
11189   ~BuildRecoveryCallExprRAII() {
11190     SemaRef.IsBuildingRecoveryCallExpr = false;
11191   }
11192 };
11193 
11194 }
11195 
11196 static std::unique_ptr<CorrectionCandidateCallback>
11197 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11198               bool HasTemplateArgs, bool AllowTypoCorrection) {
11199   if (!AllowTypoCorrection)
11200     return llvm::make_unique<NoTypoCorrectionCCC>();
11201   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11202                                                   HasTemplateArgs, ME);
11203 }
11204 
11205 /// Attempts to recover from a call where no functions were found.
11206 ///
11207 /// Returns true if new candidates were found.
11208 static ExprResult
11209 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11210                       UnresolvedLookupExpr *ULE,
11211                       SourceLocation LParenLoc,
11212                       MutableArrayRef<Expr *> Args,
11213                       SourceLocation RParenLoc,
11214                       bool EmptyLookup, bool AllowTypoCorrection) {
11215   // Do not try to recover if it is already building a recovery call.
11216   // This stops infinite loops for template instantiations like
11217   //
11218   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11219   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11220   //
11221   if (SemaRef.IsBuildingRecoveryCallExpr)
11222     return ExprError();
11223   BuildRecoveryCallExprRAII RCE(SemaRef);
11224 
11225   CXXScopeSpec SS;
11226   SS.Adopt(ULE->getQualifierLoc());
11227   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11228 
11229   TemplateArgumentListInfo TABuffer;
11230   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11231   if (ULE->hasExplicitTemplateArgs()) {
11232     ULE->copyTemplateArgumentsInto(TABuffer);
11233     ExplicitTemplateArgs = &TABuffer;
11234   }
11235 
11236   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11237                  Sema::LookupOrdinaryName);
11238   bool DoDiagnoseEmptyLookup = EmptyLookup;
11239   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11240                               OverloadCandidateSet::CSK_Normal,
11241                               ExplicitTemplateArgs, Args,
11242                               &DoDiagnoseEmptyLookup) &&
11243     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11244         S, SS, R,
11245         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11246                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11247         ExplicitTemplateArgs, Args)))
11248     return ExprError();
11249 
11250   assert(!R.empty() && "lookup results empty despite recovery");
11251 
11252   // Build an implicit member call if appropriate.  Just drop the
11253   // casts and such from the call, we don't really care.
11254   ExprResult NewFn = ExprError();
11255   if ((*R.begin())->isCXXClassMember())
11256     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11257                                                     ExplicitTemplateArgs, S);
11258   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11259     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11260                                         ExplicitTemplateArgs);
11261   else
11262     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11263 
11264   if (NewFn.isInvalid())
11265     return ExprError();
11266 
11267   // This shouldn't cause an infinite loop because we're giving it
11268   // an expression with viable lookup results, which should never
11269   // end up here.
11270   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11271                                MultiExprArg(Args.data(), Args.size()),
11272                                RParenLoc);
11273 }
11274 
11275 /// \brief Constructs and populates an OverloadedCandidateSet from
11276 /// the given function.
11277 /// \returns true when an the ExprResult output parameter has been set.
11278 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11279                                   UnresolvedLookupExpr *ULE,
11280                                   MultiExprArg Args,
11281                                   SourceLocation RParenLoc,
11282                                   OverloadCandidateSet *CandidateSet,
11283                                   ExprResult *Result) {
11284 #ifndef NDEBUG
11285   if (ULE->requiresADL()) {
11286     // To do ADL, we must have found an unqualified name.
11287     assert(!ULE->getQualifier() && "qualified name with ADL");
11288 
11289     // We don't perform ADL for implicit declarations of builtins.
11290     // Verify that this was correctly set up.
11291     FunctionDecl *F;
11292     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11293         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11294         F->getBuiltinID() && F->isImplicit())
11295       llvm_unreachable("performing ADL for builtin");
11296 
11297     // We don't perform ADL in C.
11298     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11299   }
11300 #endif
11301 
11302   UnbridgedCastsSet UnbridgedCasts;
11303   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11304     *Result = ExprError();
11305     return true;
11306   }
11307 
11308   // Add the functions denoted by the callee to the set of candidate
11309   // functions, including those from argument-dependent lookup.
11310   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11311 
11312   if (getLangOpts().MSVCCompat &&
11313       CurContext->isDependentContext() && !isSFINAEContext() &&
11314       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11315 
11316     OverloadCandidateSet::iterator Best;
11317     if (CandidateSet->empty() ||
11318         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11319             OR_No_Viable_Function) {
11320       // In Microsoft mode, if we are inside a template class member function then
11321       // create a type dependent CallExpr. The goal is to postpone name lookup
11322       // to instantiation time to be able to search into type dependent base
11323       // classes.
11324       CallExpr *CE = new (Context) CallExpr(
11325           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11326       CE->setTypeDependent(true);
11327       CE->setValueDependent(true);
11328       CE->setInstantiationDependent(true);
11329       *Result = CE;
11330       return true;
11331     }
11332   }
11333 
11334   if (CandidateSet->empty())
11335     return false;
11336 
11337   UnbridgedCasts.restore();
11338   return false;
11339 }
11340 
11341 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11342 /// the completed call expression. If overload resolution fails, emits
11343 /// diagnostics and returns ExprError()
11344 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11345                                            UnresolvedLookupExpr *ULE,
11346                                            SourceLocation LParenLoc,
11347                                            MultiExprArg Args,
11348                                            SourceLocation RParenLoc,
11349                                            Expr *ExecConfig,
11350                                            OverloadCandidateSet *CandidateSet,
11351                                            OverloadCandidateSet::iterator *Best,
11352                                            OverloadingResult OverloadResult,
11353                                            bool AllowTypoCorrection) {
11354   if (CandidateSet->empty())
11355     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11356                                  RParenLoc, /*EmptyLookup=*/true,
11357                                  AllowTypoCorrection);
11358 
11359   switch (OverloadResult) {
11360   case OR_Success: {
11361     FunctionDecl *FDecl = (*Best)->Function;
11362     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11363     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11364       return ExprError();
11365     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11366     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11367                                          ExecConfig);
11368   }
11369 
11370   case OR_No_Viable_Function: {
11371     // Try to recover by looking for viable functions which the user might
11372     // have meant to call.
11373     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11374                                                 Args, RParenLoc,
11375                                                 /*EmptyLookup=*/false,
11376                                                 AllowTypoCorrection);
11377     if (!Recovery.isInvalid())
11378       return Recovery;
11379 
11380     // If the user passes in a function that we can't take the address of, we
11381     // generally end up emitting really bad error messages. Here, we attempt to
11382     // emit better ones.
11383     for (const Expr *Arg : Args) {
11384       if (!Arg->getType()->isFunctionType())
11385         continue;
11386       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11387         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11388         if (FD &&
11389             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11390                                                        Arg->getExprLoc()))
11391           return ExprError();
11392       }
11393     }
11394 
11395     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11396         << ULE->getName() << Fn->getSourceRange();
11397     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11398     break;
11399   }
11400 
11401   case OR_Ambiguous:
11402     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11403       << ULE->getName() << Fn->getSourceRange();
11404     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11405     break;
11406 
11407   case OR_Deleted: {
11408     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11409       << (*Best)->Function->isDeleted()
11410       << ULE->getName()
11411       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11412       << Fn->getSourceRange();
11413     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11414 
11415     // We emitted an error for the unvailable/deleted function call but keep
11416     // the call in the AST.
11417     FunctionDecl *FDecl = (*Best)->Function;
11418     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11419     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11420                                          ExecConfig);
11421   }
11422   }
11423 
11424   // Overload resolution failed.
11425   return ExprError();
11426 }
11427 
11428 static void markUnaddressableCandidatesUnviable(Sema &S,
11429                                                 OverloadCandidateSet &CS) {
11430   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11431     if (I->Viable &&
11432         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11433       I->Viable = false;
11434       I->FailureKind = ovl_fail_addr_not_available;
11435     }
11436   }
11437 }
11438 
11439 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11440 /// (which eventually refers to the declaration Func) and the call
11441 /// arguments Args/NumArgs, attempt to resolve the function call down
11442 /// to a specific function. If overload resolution succeeds, returns
11443 /// the call expression produced by overload resolution.
11444 /// Otherwise, emits diagnostics and returns ExprError.
11445 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11446                                          UnresolvedLookupExpr *ULE,
11447                                          SourceLocation LParenLoc,
11448                                          MultiExprArg Args,
11449                                          SourceLocation RParenLoc,
11450                                          Expr *ExecConfig,
11451                                          bool AllowTypoCorrection,
11452                                          bool CalleesAddressIsTaken) {
11453   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11454                                     OverloadCandidateSet::CSK_Normal);
11455   ExprResult result;
11456 
11457   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11458                              &result))
11459     return result;
11460 
11461   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11462   // functions that aren't addressible are considered unviable.
11463   if (CalleesAddressIsTaken)
11464     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11465 
11466   OverloadCandidateSet::iterator Best;
11467   OverloadingResult OverloadResult =
11468       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11469 
11470   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11471                                   RParenLoc, ExecConfig, &CandidateSet,
11472                                   &Best, OverloadResult,
11473                                   AllowTypoCorrection);
11474 }
11475 
11476 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11477   return Functions.size() > 1 ||
11478     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11479 }
11480 
11481 /// \brief Create a unary operation that may resolve to an overloaded
11482 /// operator.
11483 ///
11484 /// \param OpLoc The location of the operator itself (e.g., '*').
11485 ///
11486 /// \param Opc The UnaryOperatorKind that describes this operator.
11487 ///
11488 /// \param Fns The set of non-member functions that will be
11489 /// considered by overload resolution. The caller needs to build this
11490 /// set based on the context using, e.g.,
11491 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11492 /// set should not contain any member functions; those will be added
11493 /// by CreateOverloadedUnaryOp().
11494 ///
11495 /// \param Input The input argument.
11496 ExprResult
11497 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11498                               const UnresolvedSetImpl &Fns,
11499                               Expr *Input) {
11500   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11501   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11502   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11503   // TODO: provide better source location info.
11504   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11505 
11506   if (checkPlaceholderForOverload(*this, Input))
11507     return ExprError();
11508 
11509   Expr *Args[2] = { Input, nullptr };
11510   unsigned NumArgs = 1;
11511 
11512   // For post-increment and post-decrement, add the implicit '0' as
11513   // the second argument, so that we know this is a post-increment or
11514   // post-decrement.
11515   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11516     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11517     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11518                                      SourceLocation());
11519     NumArgs = 2;
11520   }
11521 
11522   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11523 
11524   if (Input->isTypeDependent()) {
11525     if (Fns.empty())
11526       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11527                                          VK_RValue, OK_Ordinary, OpLoc);
11528 
11529     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11530     UnresolvedLookupExpr *Fn
11531       = UnresolvedLookupExpr::Create(Context, NamingClass,
11532                                      NestedNameSpecifierLoc(), OpNameInfo,
11533                                      /*ADL*/ true, IsOverloaded(Fns),
11534                                      Fns.begin(), Fns.end());
11535     return new (Context)
11536         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11537                             VK_RValue, OpLoc, false);
11538   }
11539 
11540   // Build an empty overload set.
11541   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11542 
11543   // Add the candidates from the given function set.
11544   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11545 
11546   // Add operator candidates that are member functions.
11547   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11548 
11549   // Add candidates from ADL.
11550   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11551                                        /*ExplicitTemplateArgs*/nullptr,
11552                                        CandidateSet);
11553 
11554   // Add builtin operator candidates.
11555   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11556 
11557   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11558 
11559   // Perform overload resolution.
11560   OverloadCandidateSet::iterator Best;
11561   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11562   case OR_Success: {
11563     // We found a built-in operator or an overloaded operator.
11564     FunctionDecl *FnDecl = Best->Function;
11565 
11566     if (FnDecl) {
11567       // We matched an overloaded operator. Build a call to that
11568       // operator.
11569 
11570       // Convert the arguments.
11571       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11572         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11573 
11574         ExprResult InputRes =
11575           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11576                                               Best->FoundDecl, Method);
11577         if (InputRes.isInvalid())
11578           return ExprError();
11579         Input = InputRes.get();
11580       } else {
11581         // Convert the arguments.
11582         ExprResult InputInit
11583           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11584                                                       Context,
11585                                                       FnDecl->getParamDecl(0)),
11586                                       SourceLocation(),
11587                                       Input);
11588         if (InputInit.isInvalid())
11589           return ExprError();
11590         Input = InputInit.get();
11591       }
11592 
11593       // Build the actual expression node.
11594       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11595                                                 HadMultipleCandidates, OpLoc);
11596       if (FnExpr.isInvalid())
11597         return ExprError();
11598 
11599       // Determine the result type.
11600       QualType ResultTy = FnDecl->getReturnType();
11601       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11602       ResultTy = ResultTy.getNonLValueExprType(Context);
11603 
11604       Args[0] = Input;
11605       CallExpr *TheCall =
11606         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11607                                           ResultTy, VK, OpLoc, false);
11608 
11609       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11610         return ExprError();
11611 
11612       return MaybeBindToTemporary(TheCall);
11613     } else {
11614       // We matched a built-in operator. Convert the arguments, then
11615       // break out so that we will build the appropriate built-in
11616       // operator node.
11617       ExprResult InputRes =
11618         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11619                                   Best->Conversions[0], AA_Passing);
11620       if (InputRes.isInvalid())
11621         return ExprError();
11622       Input = InputRes.get();
11623       break;
11624     }
11625   }
11626 
11627   case OR_No_Viable_Function:
11628     // This is an erroneous use of an operator which can be overloaded by
11629     // a non-member function. Check for non-member operators which were
11630     // defined too late to be candidates.
11631     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11632       // FIXME: Recover by calling the found function.
11633       return ExprError();
11634 
11635     // No viable function; fall through to handling this as a
11636     // built-in operator, which will produce an error message for us.
11637     break;
11638 
11639   case OR_Ambiguous:
11640     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11641         << UnaryOperator::getOpcodeStr(Opc)
11642         << Input->getType()
11643         << Input->getSourceRange();
11644     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11645                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11646     return ExprError();
11647 
11648   case OR_Deleted:
11649     Diag(OpLoc, diag::err_ovl_deleted_oper)
11650       << Best->Function->isDeleted()
11651       << UnaryOperator::getOpcodeStr(Opc)
11652       << getDeletedOrUnavailableSuffix(Best->Function)
11653       << Input->getSourceRange();
11654     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11655                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11656     return ExprError();
11657   }
11658 
11659   // Either we found no viable overloaded operator or we matched a
11660   // built-in operator. In either case, fall through to trying to
11661   // build a built-in operation.
11662   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11663 }
11664 
11665 /// \brief Create a binary operation that may resolve to an overloaded
11666 /// operator.
11667 ///
11668 /// \param OpLoc The location of the operator itself (e.g., '+').
11669 ///
11670 /// \param Opc The BinaryOperatorKind that describes this operator.
11671 ///
11672 /// \param Fns The set of non-member functions that will be
11673 /// considered by overload resolution. The caller needs to build this
11674 /// set based on the context using, e.g.,
11675 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11676 /// set should not contain any member functions; those will be added
11677 /// by CreateOverloadedBinOp().
11678 ///
11679 /// \param LHS Left-hand argument.
11680 /// \param RHS Right-hand argument.
11681 ExprResult
11682 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11683                             BinaryOperatorKind Opc,
11684                             const UnresolvedSetImpl &Fns,
11685                             Expr *LHS, Expr *RHS) {
11686   Expr *Args[2] = { LHS, RHS };
11687   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11688 
11689   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11690   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11691 
11692   // If either side is type-dependent, create an appropriate dependent
11693   // expression.
11694   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11695     if (Fns.empty()) {
11696       // If there are no functions to store, just build a dependent
11697       // BinaryOperator or CompoundAssignment.
11698       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11699         return new (Context) BinaryOperator(
11700             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11701             OpLoc, FPFeatures.fp_contract);
11702 
11703       return new (Context) CompoundAssignOperator(
11704           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11705           Context.DependentTy, Context.DependentTy, OpLoc,
11706           FPFeatures.fp_contract);
11707     }
11708 
11709     // FIXME: save results of ADL from here?
11710     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11711     // TODO: provide better source location info in DNLoc component.
11712     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11713     UnresolvedLookupExpr *Fn
11714       = UnresolvedLookupExpr::Create(Context, NamingClass,
11715                                      NestedNameSpecifierLoc(), OpNameInfo,
11716                                      /*ADL*/ true, IsOverloaded(Fns),
11717                                      Fns.begin(), Fns.end());
11718     return new (Context)
11719         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11720                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11721   }
11722 
11723   // Always do placeholder-like conversions on the RHS.
11724   if (checkPlaceholderForOverload(*this, Args[1]))
11725     return ExprError();
11726 
11727   // Do placeholder-like conversion on the LHS; note that we should
11728   // not get here with a PseudoObject LHS.
11729   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11730   if (checkPlaceholderForOverload(*this, Args[0]))
11731     return ExprError();
11732 
11733   // If this is the assignment operator, we only perform overload resolution
11734   // if the left-hand side is a class or enumeration type. This is actually
11735   // a hack. The standard requires that we do overload resolution between the
11736   // various built-in candidates, but as DR507 points out, this can lead to
11737   // problems. So we do it this way, which pretty much follows what GCC does.
11738   // Note that we go the traditional code path for compound assignment forms.
11739   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11740     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11741 
11742   // If this is the .* operator, which is not overloadable, just
11743   // create a built-in binary operator.
11744   if (Opc == BO_PtrMemD)
11745     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11746 
11747   // Build an empty overload set.
11748   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11749 
11750   // Add the candidates from the given function set.
11751   AddFunctionCandidates(Fns, Args, CandidateSet);
11752 
11753   // Add operator candidates that are member functions.
11754   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11755 
11756   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11757   // performed for an assignment operator (nor for operator[] nor operator->,
11758   // which don't get here).
11759   if (Opc != BO_Assign)
11760     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11761                                          /*ExplicitTemplateArgs*/ nullptr,
11762                                          CandidateSet);
11763 
11764   // Add builtin operator candidates.
11765   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11766 
11767   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11768 
11769   // Perform overload resolution.
11770   OverloadCandidateSet::iterator Best;
11771   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11772     case OR_Success: {
11773       // We found a built-in operator or an overloaded operator.
11774       FunctionDecl *FnDecl = Best->Function;
11775 
11776       if (FnDecl) {
11777         // We matched an overloaded operator. Build a call to that
11778         // operator.
11779 
11780         // Convert the arguments.
11781         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11782           // Best->Access is only meaningful for class members.
11783           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11784 
11785           ExprResult Arg1 =
11786             PerformCopyInitialization(
11787               InitializedEntity::InitializeParameter(Context,
11788                                                      FnDecl->getParamDecl(0)),
11789               SourceLocation(), Args[1]);
11790           if (Arg1.isInvalid())
11791             return ExprError();
11792 
11793           ExprResult Arg0 =
11794             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11795                                                 Best->FoundDecl, Method);
11796           if (Arg0.isInvalid())
11797             return ExprError();
11798           Args[0] = Arg0.getAs<Expr>();
11799           Args[1] = RHS = Arg1.getAs<Expr>();
11800         } else {
11801           // Convert the arguments.
11802           ExprResult Arg0 = PerformCopyInitialization(
11803             InitializedEntity::InitializeParameter(Context,
11804                                                    FnDecl->getParamDecl(0)),
11805             SourceLocation(), Args[0]);
11806           if (Arg0.isInvalid())
11807             return ExprError();
11808 
11809           ExprResult Arg1 =
11810             PerformCopyInitialization(
11811               InitializedEntity::InitializeParameter(Context,
11812                                                      FnDecl->getParamDecl(1)),
11813               SourceLocation(), Args[1]);
11814           if (Arg1.isInvalid())
11815             return ExprError();
11816           Args[0] = LHS = Arg0.getAs<Expr>();
11817           Args[1] = RHS = Arg1.getAs<Expr>();
11818         }
11819 
11820         // Build the actual expression node.
11821         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11822                                                   Best->FoundDecl,
11823                                                   HadMultipleCandidates, OpLoc);
11824         if (FnExpr.isInvalid())
11825           return ExprError();
11826 
11827         // Determine the result type.
11828         QualType ResultTy = FnDecl->getReturnType();
11829         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11830         ResultTy = ResultTy.getNonLValueExprType(Context);
11831 
11832         CXXOperatorCallExpr *TheCall =
11833           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11834                                             Args, ResultTy, VK, OpLoc,
11835                                             FPFeatures.fp_contract);
11836 
11837         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11838                                 FnDecl))
11839           return ExprError();
11840 
11841         ArrayRef<const Expr *> ArgsArray(Args, 2);
11842         // Cut off the implicit 'this'.
11843         if (isa<CXXMethodDecl>(FnDecl))
11844           ArgsArray = ArgsArray.slice(1);
11845 
11846         // Check for a self move.
11847         if (Op == OO_Equal)
11848           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11849 
11850         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11851                   TheCall->getSourceRange(), VariadicDoesNotApply);
11852 
11853         return MaybeBindToTemporary(TheCall);
11854       } else {
11855         // We matched a built-in operator. Convert the arguments, then
11856         // break out so that we will build the appropriate built-in
11857         // operator node.
11858         ExprResult ArgsRes0 =
11859           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11860                                     Best->Conversions[0], AA_Passing);
11861         if (ArgsRes0.isInvalid())
11862           return ExprError();
11863         Args[0] = ArgsRes0.get();
11864 
11865         ExprResult ArgsRes1 =
11866           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11867                                     Best->Conversions[1], AA_Passing);
11868         if (ArgsRes1.isInvalid())
11869           return ExprError();
11870         Args[1] = ArgsRes1.get();
11871         break;
11872       }
11873     }
11874 
11875     case OR_No_Viable_Function: {
11876       // C++ [over.match.oper]p9:
11877       //   If the operator is the operator , [...] and there are no
11878       //   viable functions, then the operator is assumed to be the
11879       //   built-in operator and interpreted according to clause 5.
11880       if (Opc == BO_Comma)
11881         break;
11882 
11883       // For class as left operand for assignment or compound assigment
11884       // operator do not fall through to handling in built-in, but report that
11885       // no overloaded assignment operator found
11886       ExprResult Result = ExprError();
11887       if (Args[0]->getType()->isRecordType() &&
11888           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11889         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11890              << BinaryOperator::getOpcodeStr(Opc)
11891              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11892         if (Args[0]->getType()->isIncompleteType()) {
11893           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11894             << Args[0]->getType()
11895             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11896         }
11897       } else {
11898         // This is an erroneous use of an operator which can be overloaded by
11899         // a non-member function. Check for non-member operators which were
11900         // defined too late to be candidates.
11901         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11902           // FIXME: Recover by calling the found function.
11903           return ExprError();
11904 
11905         // No viable function; try to create a built-in operation, which will
11906         // produce an error. Then, show the non-viable candidates.
11907         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11908       }
11909       assert(Result.isInvalid() &&
11910              "C++ binary operator overloading is missing candidates!");
11911       if (Result.isInvalid())
11912         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11913                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11914       return Result;
11915     }
11916 
11917     case OR_Ambiguous:
11918       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11919           << BinaryOperator::getOpcodeStr(Opc)
11920           << Args[0]->getType() << Args[1]->getType()
11921           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11922       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11923                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11924       return ExprError();
11925 
11926     case OR_Deleted:
11927       if (isImplicitlyDeleted(Best->Function)) {
11928         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11929         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11930           << Context.getRecordType(Method->getParent())
11931           << getSpecialMember(Method);
11932 
11933         // The user probably meant to call this special member. Just
11934         // explain why it's deleted.
11935         NoteDeletedFunction(Method);
11936         return ExprError();
11937       } else {
11938         Diag(OpLoc, diag::err_ovl_deleted_oper)
11939           << Best->Function->isDeleted()
11940           << BinaryOperator::getOpcodeStr(Opc)
11941           << getDeletedOrUnavailableSuffix(Best->Function)
11942           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11943       }
11944       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11945                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11946       return ExprError();
11947   }
11948 
11949   // We matched a built-in operator; build it.
11950   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11951 }
11952 
11953 ExprResult
11954 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11955                                          SourceLocation RLoc,
11956                                          Expr *Base, Expr *Idx) {
11957   Expr *Args[2] = { Base, Idx };
11958   DeclarationName OpName =
11959       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11960 
11961   // If either side is type-dependent, create an appropriate dependent
11962   // expression.
11963   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11964 
11965     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11966     // CHECKME: no 'operator' keyword?
11967     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11968     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11969     UnresolvedLookupExpr *Fn
11970       = UnresolvedLookupExpr::Create(Context, NamingClass,
11971                                      NestedNameSpecifierLoc(), OpNameInfo,
11972                                      /*ADL*/ true, /*Overloaded*/ false,
11973                                      UnresolvedSetIterator(),
11974                                      UnresolvedSetIterator());
11975     // Can't add any actual overloads yet
11976 
11977     return new (Context)
11978         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11979                             Context.DependentTy, VK_RValue, RLoc, false);
11980   }
11981 
11982   // Handle placeholders on both operands.
11983   if (checkPlaceholderForOverload(*this, Args[0]))
11984     return ExprError();
11985   if (checkPlaceholderForOverload(*this, Args[1]))
11986     return ExprError();
11987 
11988   // Build an empty overload set.
11989   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11990 
11991   // Subscript can only be overloaded as a member function.
11992 
11993   // Add operator candidates that are member functions.
11994   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11995 
11996   // Add builtin operator candidates.
11997   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11998 
11999   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12000 
12001   // Perform overload resolution.
12002   OverloadCandidateSet::iterator Best;
12003   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12004     case OR_Success: {
12005       // We found a built-in operator or an overloaded operator.
12006       FunctionDecl *FnDecl = Best->Function;
12007 
12008       if (FnDecl) {
12009         // We matched an overloaded operator. Build a call to that
12010         // operator.
12011 
12012         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12013 
12014         // Convert the arguments.
12015         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12016         ExprResult Arg0 =
12017           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12018                                               Best->FoundDecl, Method);
12019         if (Arg0.isInvalid())
12020           return ExprError();
12021         Args[0] = Arg0.get();
12022 
12023         // Convert the arguments.
12024         ExprResult InputInit
12025           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12026                                                       Context,
12027                                                       FnDecl->getParamDecl(0)),
12028                                       SourceLocation(),
12029                                       Args[1]);
12030         if (InputInit.isInvalid())
12031           return ExprError();
12032 
12033         Args[1] = InputInit.getAs<Expr>();
12034 
12035         // Build the actual expression node.
12036         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12037         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12038         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12039                                                   Best->FoundDecl,
12040                                                   HadMultipleCandidates,
12041                                                   OpLocInfo.getLoc(),
12042                                                   OpLocInfo.getInfo());
12043         if (FnExpr.isInvalid())
12044           return ExprError();
12045 
12046         // Determine the result type
12047         QualType ResultTy = FnDecl->getReturnType();
12048         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12049         ResultTy = ResultTy.getNonLValueExprType(Context);
12050 
12051         CXXOperatorCallExpr *TheCall =
12052           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12053                                             FnExpr.get(), Args,
12054                                             ResultTy, VK, RLoc,
12055                                             false);
12056 
12057         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12058           return ExprError();
12059 
12060         return MaybeBindToTemporary(TheCall);
12061       } else {
12062         // We matched a built-in operator. Convert the arguments, then
12063         // break out so that we will build the appropriate built-in
12064         // operator node.
12065         ExprResult ArgsRes0 =
12066           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12067                                     Best->Conversions[0], AA_Passing);
12068         if (ArgsRes0.isInvalid())
12069           return ExprError();
12070         Args[0] = ArgsRes0.get();
12071 
12072         ExprResult ArgsRes1 =
12073           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12074                                     Best->Conversions[1], AA_Passing);
12075         if (ArgsRes1.isInvalid())
12076           return ExprError();
12077         Args[1] = ArgsRes1.get();
12078 
12079         break;
12080       }
12081     }
12082 
12083     case OR_No_Viable_Function: {
12084       if (CandidateSet.empty())
12085         Diag(LLoc, diag::err_ovl_no_oper)
12086           << Args[0]->getType() << /*subscript*/ 0
12087           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12088       else
12089         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12090           << Args[0]->getType()
12091           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12092       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12093                                   "[]", LLoc);
12094       return ExprError();
12095     }
12096 
12097     case OR_Ambiguous:
12098       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12099           << "[]"
12100           << Args[0]->getType() << Args[1]->getType()
12101           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12102       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12103                                   "[]", LLoc);
12104       return ExprError();
12105 
12106     case OR_Deleted:
12107       Diag(LLoc, diag::err_ovl_deleted_oper)
12108         << Best->Function->isDeleted() << "[]"
12109         << getDeletedOrUnavailableSuffix(Best->Function)
12110         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12111       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12112                                   "[]", LLoc);
12113       return ExprError();
12114     }
12115 
12116   // We matched a built-in operator; build it.
12117   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12118 }
12119 
12120 /// BuildCallToMemberFunction - Build a call to a member
12121 /// function. MemExpr is the expression that refers to the member
12122 /// function (and includes the object parameter), Args/NumArgs are the
12123 /// arguments to the function call (not including the object
12124 /// parameter). The caller needs to validate that the member
12125 /// expression refers to a non-static member function or an overloaded
12126 /// member function.
12127 ExprResult
12128 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12129                                 SourceLocation LParenLoc,
12130                                 MultiExprArg Args,
12131                                 SourceLocation RParenLoc) {
12132   assert(MemExprE->getType() == Context.BoundMemberTy ||
12133          MemExprE->getType() == Context.OverloadTy);
12134 
12135   // Dig out the member expression. This holds both the object
12136   // argument and the member function we're referring to.
12137   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12138 
12139   // Determine whether this is a call to a pointer-to-member function.
12140   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12141     assert(op->getType() == Context.BoundMemberTy);
12142     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12143 
12144     QualType fnType =
12145       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12146 
12147     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12148     QualType resultType = proto->getCallResultType(Context);
12149     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12150 
12151     // Check that the object type isn't more qualified than the
12152     // member function we're calling.
12153     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12154 
12155     QualType objectType = op->getLHS()->getType();
12156     if (op->getOpcode() == BO_PtrMemI)
12157       objectType = objectType->castAs<PointerType>()->getPointeeType();
12158     Qualifiers objectQuals = objectType.getQualifiers();
12159 
12160     Qualifiers difference = objectQuals - funcQuals;
12161     difference.removeObjCGCAttr();
12162     difference.removeAddressSpace();
12163     if (difference) {
12164       std::string qualsString = difference.getAsString();
12165       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12166         << fnType.getUnqualifiedType()
12167         << qualsString
12168         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12169     }
12170 
12171     CXXMemberCallExpr *call
12172       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12173                                         resultType, valueKind, RParenLoc);
12174 
12175     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12176                             call, nullptr))
12177       return ExprError();
12178 
12179     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12180       return ExprError();
12181 
12182     if (CheckOtherCall(call, proto))
12183       return ExprError();
12184 
12185     return MaybeBindToTemporary(call);
12186   }
12187 
12188   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12189     return new (Context)
12190         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12191 
12192   UnbridgedCastsSet UnbridgedCasts;
12193   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12194     return ExprError();
12195 
12196   MemberExpr *MemExpr;
12197   CXXMethodDecl *Method = nullptr;
12198   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12199   NestedNameSpecifier *Qualifier = nullptr;
12200   if (isa<MemberExpr>(NakedMemExpr)) {
12201     MemExpr = cast<MemberExpr>(NakedMemExpr);
12202     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12203     FoundDecl = MemExpr->getFoundDecl();
12204     Qualifier = MemExpr->getQualifier();
12205     UnbridgedCasts.restore();
12206   } else {
12207     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12208     Qualifier = UnresExpr->getQualifier();
12209 
12210     QualType ObjectType = UnresExpr->getBaseType();
12211     Expr::Classification ObjectClassification
12212       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12213                             : UnresExpr->getBase()->Classify(Context);
12214 
12215     // Add overload candidates
12216     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12217                                       OverloadCandidateSet::CSK_Normal);
12218 
12219     // FIXME: avoid copy.
12220     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12221     if (UnresExpr->hasExplicitTemplateArgs()) {
12222       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12223       TemplateArgs = &TemplateArgsBuffer;
12224     }
12225 
12226     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12227            E = UnresExpr->decls_end(); I != E; ++I) {
12228 
12229       NamedDecl *Func = *I;
12230       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12231       if (isa<UsingShadowDecl>(Func))
12232         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12233 
12234 
12235       // Microsoft supports direct constructor calls.
12236       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12237         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12238                              Args, CandidateSet);
12239       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12240         // If explicit template arguments were provided, we can't call a
12241         // non-template member function.
12242         if (TemplateArgs)
12243           continue;
12244 
12245         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12246                            ObjectClassification, Args, CandidateSet,
12247                            /*SuppressUserConversions=*/false);
12248       } else {
12249         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12250                                    I.getPair(), ActingDC, TemplateArgs,
12251                                    ObjectType,  ObjectClassification,
12252                                    Args, CandidateSet,
12253                                    /*SuppressUsedConversions=*/false);
12254       }
12255     }
12256 
12257     DeclarationName DeclName = UnresExpr->getMemberName();
12258 
12259     UnbridgedCasts.restore();
12260 
12261     OverloadCandidateSet::iterator Best;
12262     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12263                                             Best)) {
12264     case OR_Success:
12265       Method = cast<CXXMethodDecl>(Best->Function);
12266       FoundDecl = Best->FoundDecl;
12267       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12268       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12269         return ExprError();
12270       // If FoundDecl is different from Method (such as if one is a template
12271       // and the other a specialization), make sure DiagnoseUseOfDecl is
12272       // called on both.
12273       // FIXME: This would be more comprehensively addressed by modifying
12274       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12275       // being used.
12276       if (Method != FoundDecl.getDecl() &&
12277                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12278         return ExprError();
12279       break;
12280 
12281     case OR_No_Viable_Function:
12282       Diag(UnresExpr->getMemberLoc(),
12283            diag::err_ovl_no_viable_member_function_in_call)
12284         << DeclName << MemExprE->getSourceRange();
12285       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12286       // FIXME: Leaking incoming expressions!
12287       return ExprError();
12288 
12289     case OR_Ambiguous:
12290       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12291         << DeclName << MemExprE->getSourceRange();
12292       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12293       // FIXME: Leaking incoming expressions!
12294       return ExprError();
12295 
12296     case OR_Deleted:
12297       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12298         << Best->Function->isDeleted()
12299         << DeclName
12300         << getDeletedOrUnavailableSuffix(Best->Function)
12301         << MemExprE->getSourceRange();
12302       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12303       // FIXME: Leaking incoming expressions!
12304       return ExprError();
12305     }
12306 
12307     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12308 
12309     // If overload resolution picked a static member, build a
12310     // non-member call based on that function.
12311     if (Method->isStatic()) {
12312       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12313                                    RParenLoc);
12314     }
12315 
12316     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12317   }
12318 
12319   QualType ResultType = Method->getReturnType();
12320   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12321   ResultType = ResultType.getNonLValueExprType(Context);
12322 
12323   assert(Method && "Member call to something that isn't a method?");
12324   CXXMemberCallExpr *TheCall =
12325     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12326                                     ResultType, VK, RParenLoc);
12327 
12328   // (CUDA B.1): Check for invalid calls between targets.
12329   if (getLangOpts().CUDA) {
12330     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12331       if (CheckCUDATarget(Caller, Method)) {
12332         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12333             << IdentifyCUDATarget(Method) << Method->getIdentifier()
12334             << IdentifyCUDATarget(Caller);
12335         return ExprError();
12336       }
12337     }
12338   }
12339 
12340   // Check for a valid return type.
12341   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12342                           TheCall, Method))
12343     return ExprError();
12344 
12345   // Convert the object argument (for a non-static member function call).
12346   // We only need to do this if there was actually an overload; otherwise
12347   // it was done at lookup.
12348   if (!Method->isStatic()) {
12349     ExprResult ObjectArg =
12350       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12351                                           FoundDecl, Method);
12352     if (ObjectArg.isInvalid())
12353       return ExprError();
12354     MemExpr->setBase(ObjectArg.get());
12355   }
12356 
12357   // Convert the rest of the arguments
12358   const FunctionProtoType *Proto =
12359     Method->getType()->getAs<FunctionProtoType>();
12360   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12361                               RParenLoc))
12362     return ExprError();
12363 
12364   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12365 
12366   if (CheckFunctionCall(Method, TheCall, Proto))
12367     return ExprError();
12368 
12369   // In the case the method to call was not selected by the overloading
12370   // resolution process, we still need to handle the enable_if attribute. Do
12371   // that here, so it will not hide previous -- and more relevant -- errors
12372   if (isa<MemberExpr>(NakedMemExpr)) {
12373     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12374       Diag(MemExprE->getLocStart(),
12375            diag::err_ovl_no_viable_member_function_in_call)
12376           << Method << Method->getSourceRange();
12377       Diag(Method->getLocation(),
12378            diag::note_ovl_candidate_disabled_by_enable_if_attr)
12379           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12380       return ExprError();
12381     }
12382   }
12383 
12384   if ((isa<CXXConstructorDecl>(CurContext) ||
12385        isa<CXXDestructorDecl>(CurContext)) &&
12386       TheCall->getMethodDecl()->isPure()) {
12387     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12388 
12389     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12390         MemExpr->performsVirtualDispatch(getLangOpts())) {
12391       Diag(MemExpr->getLocStart(),
12392            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12393         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12394         << MD->getParent()->getDeclName();
12395 
12396       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12397       if (getLangOpts().AppleKext)
12398         Diag(MemExpr->getLocStart(),
12399              diag::note_pure_qualified_call_kext)
12400              << MD->getParent()->getDeclName()
12401              << MD->getDeclName();
12402     }
12403   }
12404 
12405   if (CXXDestructorDecl *DD =
12406           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12407     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12408     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12409     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12410                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12411                          MemExpr->getMemberLoc());
12412   }
12413 
12414   return MaybeBindToTemporary(TheCall);
12415 }
12416 
12417 /// BuildCallToObjectOfClassType - Build a call to an object of class
12418 /// type (C++ [over.call.object]), which can end up invoking an
12419 /// overloaded function call operator (@c operator()) or performing a
12420 /// user-defined conversion on the object argument.
12421 ExprResult
12422 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12423                                    SourceLocation LParenLoc,
12424                                    MultiExprArg Args,
12425                                    SourceLocation RParenLoc) {
12426   if (checkPlaceholderForOverload(*this, Obj))
12427     return ExprError();
12428   ExprResult Object = Obj;
12429 
12430   UnbridgedCastsSet UnbridgedCasts;
12431   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12432     return ExprError();
12433 
12434   assert(Object.get()->getType()->isRecordType() &&
12435          "Requires object type argument");
12436   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12437 
12438   // C++ [over.call.object]p1:
12439   //  If the primary-expression E in the function call syntax
12440   //  evaluates to a class object of type "cv T", then the set of
12441   //  candidate functions includes at least the function call
12442   //  operators of T. The function call operators of T are obtained by
12443   //  ordinary lookup of the name operator() in the context of
12444   //  (E).operator().
12445   OverloadCandidateSet CandidateSet(LParenLoc,
12446                                     OverloadCandidateSet::CSK_Operator);
12447   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12448 
12449   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12450                           diag::err_incomplete_object_call, Object.get()))
12451     return true;
12452 
12453   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12454   LookupQualifiedName(R, Record->getDecl());
12455   R.suppressDiagnostics();
12456 
12457   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12458        Oper != OperEnd; ++Oper) {
12459     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12460                        Object.get()->Classify(Context),
12461                        Args, CandidateSet,
12462                        /*SuppressUserConversions=*/ false);
12463   }
12464 
12465   // C++ [over.call.object]p2:
12466   //   In addition, for each (non-explicit in C++0x) conversion function
12467   //   declared in T of the form
12468   //
12469   //        operator conversion-type-id () cv-qualifier;
12470   //
12471   //   where cv-qualifier is the same cv-qualification as, or a
12472   //   greater cv-qualification than, cv, and where conversion-type-id
12473   //   denotes the type "pointer to function of (P1,...,Pn) returning
12474   //   R", or the type "reference to pointer to function of
12475   //   (P1,...,Pn) returning R", or the type "reference to function
12476   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12477   //   is also considered as a candidate function. Similarly,
12478   //   surrogate call functions are added to the set of candidate
12479   //   functions for each conversion function declared in an
12480   //   accessible base class provided the function is not hidden
12481   //   within T by another intervening declaration.
12482   const auto &Conversions =
12483       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12484   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12485     NamedDecl *D = *I;
12486     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12487     if (isa<UsingShadowDecl>(D))
12488       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12489 
12490     // Skip over templated conversion functions; they aren't
12491     // surrogates.
12492     if (isa<FunctionTemplateDecl>(D))
12493       continue;
12494 
12495     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12496     if (!Conv->isExplicit()) {
12497       // Strip the reference type (if any) and then the pointer type (if
12498       // any) to get down to what might be a function type.
12499       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12500       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12501         ConvType = ConvPtrType->getPointeeType();
12502 
12503       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12504       {
12505         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12506                               Object.get(), Args, CandidateSet);
12507       }
12508     }
12509   }
12510 
12511   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12512 
12513   // Perform overload resolution.
12514   OverloadCandidateSet::iterator Best;
12515   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12516                              Best)) {
12517   case OR_Success:
12518     // Overload resolution succeeded; we'll build the appropriate call
12519     // below.
12520     break;
12521 
12522   case OR_No_Viable_Function:
12523     if (CandidateSet.empty())
12524       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12525         << Object.get()->getType() << /*call*/ 1
12526         << Object.get()->getSourceRange();
12527     else
12528       Diag(Object.get()->getLocStart(),
12529            diag::err_ovl_no_viable_object_call)
12530         << Object.get()->getType() << Object.get()->getSourceRange();
12531     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12532     break;
12533 
12534   case OR_Ambiguous:
12535     Diag(Object.get()->getLocStart(),
12536          diag::err_ovl_ambiguous_object_call)
12537       << Object.get()->getType() << Object.get()->getSourceRange();
12538     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12539     break;
12540 
12541   case OR_Deleted:
12542     Diag(Object.get()->getLocStart(),
12543          diag::err_ovl_deleted_object_call)
12544       << Best->Function->isDeleted()
12545       << Object.get()->getType()
12546       << getDeletedOrUnavailableSuffix(Best->Function)
12547       << Object.get()->getSourceRange();
12548     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12549     break;
12550   }
12551 
12552   if (Best == CandidateSet.end())
12553     return true;
12554 
12555   UnbridgedCasts.restore();
12556 
12557   if (Best->Function == nullptr) {
12558     // Since there is no function declaration, this is one of the
12559     // surrogate candidates. Dig out the conversion function.
12560     CXXConversionDecl *Conv
12561       = cast<CXXConversionDecl>(
12562                          Best->Conversions[0].UserDefined.ConversionFunction);
12563 
12564     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12565                               Best->FoundDecl);
12566     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12567       return ExprError();
12568     assert(Conv == Best->FoundDecl.getDecl() &&
12569              "Found Decl & conversion-to-functionptr should be same, right?!");
12570     // We selected one of the surrogate functions that converts the
12571     // object parameter to a function pointer. Perform the conversion
12572     // on the object argument, then let ActOnCallExpr finish the job.
12573 
12574     // Create an implicit member expr to refer to the conversion operator.
12575     // and then call it.
12576     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12577                                              Conv, HadMultipleCandidates);
12578     if (Call.isInvalid())
12579       return ExprError();
12580     // Record usage of conversion in an implicit cast.
12581     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12582                                     CK_UserDefinedConversion, Call.get(),
12583                                     nullptr, VK_RValue);
12584 
12585     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12586   }
12587 
12588   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12589 
12590   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12591   // that calls this method, using Object for the implicit object
12592   // parameter and passing along the remaining arguments.
12593   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12594 
12595   // An error diagnostic has already been printed when parsing the declaration.
12596   if (Method->isInvalidDecl())
12597     return ExprError();
12598 
12599   const FunctionProtoType *Proto =
12600     Method->getType()->getAs<FunctionProtoType>();
12601 
12602   unsigned NumParams = Proto->getNumParams();
12603 
12604   DeclarationNameInfo OpLocInfo(
12605                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12606   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12607   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12608                                            HadMultipleCandidates,
12609                                            OpLocInfo.getLoc(),
12610                                            OpLocInfo.getInfo());
12611   if (NewFn.isInvalid())
12612     return true;
12613 
12614   // Build the full argument list for the method call (the implicit object
12615   // parameter is placed at the beginning of the list).
12616   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12617   MethodArgs[0] = Object.get();
12618   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12619 
12620   // Once we've built TheCall, all of the expressions are properly
12621   // owned.
12622   QualType ResultTy = Method->getReturnType();
12623   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12624   ResultTy = ResultTy.getNonLValueExprType(Context);
12625 
12626   CXXOperatorCallExpr *TheCall = new (Context)
12627       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12628                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12629                           ResultTy, VK, RParenLoc, false);
12630   MethodArgs.reset();
12631 
12632   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12633     return true;
12634 
12635   // We may have default arguments. If so, we need to allocate more
12636   // slots in the call for them.
12637   if (Args.size() < NumParams)
12638     TheCall->setNumArgs(Context, NumParams + 1);
12639 
12640   bool IsError = false;
12641 
12642   // Initialize the implicit object parameter.
12643   ExprResult ObjRes =
12644     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12645                                         Best->FoundDecl, Method);
12646   if (ObjRes.isInvalid())
12647     IsError = true;
12648   else
12649     Object = ObjRes;
12650   TheCall->setArg(0, Object.get());
12651 
12652   // Check the argument types.
12653   for (unsigned i = 0; i != NumParams; i++) {
12654     Expr *Arg;
12655     if (i < Args.size()) {
12656       Arg = Args[i];
12657 
12658       // Pass the argument.
12659 
12660       ExprResult InputInit
12661         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12662                                                     Context,
12663                                                     Method->getParamDecl(i)),
12664                                     SourceLocation(), Arg);
12665 
12666       IsError |= InputInit.isInvalid();
12667       Arg = InputInit.getAs<Expr>();
12668     } else {
12669       ExprResult DefArg
12670         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12671       if (DefArg.isInvalid()) {
12672         IsError = true;
12673         break;
12674       }
12675 
12676       Arg = DefArg.getAs<Expr>();
12677     }
12678 
12679     TheCall->setArg(i + 1, Arg);
12680   }
12681 
12682   // If this is a variadic call, handle args passed through "...".
12683   if (Proto->isVariadic()) {
12684     // Promote the arguments (C99 6.5.2.2p7).
12685     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12686       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12687                                                         nullptr);
12688       IsError |= Arg.isInvalid();
12689       TheCall->setArg(i + 1, Arg.get());
12690     }
12691   }
12692 
12693   if (IsError) return true;
12694 
12695   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12696 
12697   if (CheckFunctionCall(Method, TheCall, Proto))
12698     return true;
12699 
12700   return MaybeBindToTemporary(TheCall);
12701 }
12702 
12703 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12704 ///  (if one exists), where @c Base is an expression of class type and
12705 /// @c Member is the name of the member we're trying to find.
12706 ExprResult
12707 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12708                                bool *NoArrowOperatorFound) {
12709   assert(Base->getType()->isRecordType() &&
12710          "left-hand side must have class type");
12711 
12712   if (checkPlaceholderForOverload(*this, Base))
12713     return ExprError();
12714 
12715   SourceLocation Loc = Base->getExprLoc();
12716 
12717   // C++ [over.ref]p1:
12718   //
12719   //   [...] An expression x->m is interpreted as (x.operator->())->m
12720   //   for a class object x of type T if T::operator->() exists and if
12721   //   the operator is selected as the best match function by the
12722   //   overload resolution mechanism (13.3).
12723   DeclarationName OpName =
12724     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12725   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12726   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12727 
12728   if (RequireCompleteType(Loc, Base->getType(),
12729                           diag::err_typecheck_incomplete_tag, Base))
12730     return ExprError();
12731 
12732   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12733   LookupQualifiedName(R, BaseRecord->getDecl());
12734   R.suppressDiagnostics();
12735 
12736   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12737        Oper != OperEnd; ++Oper) {
12738     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12739                        None, CandidateSet, /*SuppressUserConversions=*/false);
12740   }
12741 
12742   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12743 
12744   // Perform overload resolution.
12745   OverloadCandidateSet::iterator Best;
12746   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12747   case OR_Success:
12748     // Overload resolution succeeded; we'll build the call below.
12749     break;
12750 
12751   case OR_No_Viable_Function:
12752     if (CandidateSet.empty()) {
12753       QualType BaseType = Base->getType();
12754       if (NoArrowOperatorFound) {
12755         // Report this specific error to the caller instead of emitting a
12756         // diagnostic, as requested.
12757         *NoArrowOperatorFound = true;
12758         return ExprError();
12759       }
12760       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12761         << BaseType << Base->getSourceRange();
12762       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12763         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12764           << FixItHint::CreateReplacement(OpLoc, ".");
12765       }
12766     } else
12767       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12768         << "operator->" << Base->getSourceRange();
12769     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12770     return ExprError();
12771 
12772   case OR_Ambiguous:
12773     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12774       << "->" << Base->getType() << Base->getSourceRange();
12775     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12776     return ExprError();
12777 
12778   case OR_Deleted:
12779     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12780       << Best->Function->isDeleted()
12781       << "->"
12782       << getDeletedOrUnavailableSuffix(Best->Function)
12783       << Base->getSourceRange();
12784     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12785     return ExprError();
12786   }
12787 
12788   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12789 
12790   // Convert the object parameter.
12791   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12792   ExprResult BaseResult =
12793     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12794                                         Best->FoundDecl, Method);
12795   if (BaseResult.isInvalid())
12796     return ExprError();
12797   Base = BaseResult.get();
12798 
12799   // Build the operator call.
12800   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12801                                             HadMultipleCandidates, OpLoc);
12802   if (FnExpr.isInvalid())
12803     return ExprError();
12804 
12805   QualType ResultTy = Method->getReturnType();
12806   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12807   ResultTy = ResultTy.getNonLValueExprType(Context);
12808   CXXOperatorCallExpr *TheCall =
12809     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12810                                       Base, ResultTy, VK, OpLoc, false);
12811 
12812   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12813           return ExprError();
12814 
12815   return MaybeBindToTemporary(TheCall);
12816 }
12817 
12818 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12819 /// a literal operator described by the provided lookup results.
12820 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12821                                           DeclarationNameInfo &SuffixInfo,
12822                                           ArrayRef<Expr*> Args,
12823                                           SourceLocation LitEndLoc,
12824                                        TemplateArgumentListInfo *TemplateArgs) {
12825   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12826 
12827   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12828                                     OverloadCandidateSet::CSK_Normal);
12829   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12830                         /*SuppressUserConversions=*/true);
12831 
12832   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12833 
12834   // Perform overload resolution. This will usually be trivial, but might need
12835   // to perform substitutions for a literal operator template.
12836   OverloadCandidateSet::iterator Best;
12837   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12838   case OR_Success:
12839   case OR_Deleted:
12840     break;
12841 
12842   case OR_No_Viable_Function:
12843     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12844       << R.getLookupName();
12845     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12846     return ExprError();
12847 
12848   case OR_Ambiguous:
12849     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12850     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12851     return ExprError();
12852   }
12853 
12854   FunctionDecl *FD = Best->Function;
12855   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12856                                         HadMultipleCandidates,
12857                                         SuffixInfo.getLoc(),
12858                                         SuffixInfo.getInfo());
12859   if (Fn.isInvalid())
12860     return true;
12861 
12862   // Check the argument types. This should almost always be a no-op, except
12863   // that array-to-pointer decay is applied to string literals.
12864   Expr *ConvArgs[2];
12865   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12866     ExprResult InputInit = PerformCopyInitialization(
12867       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12868       SourceLocation(), Args[ArgIdx]);
12869     if (InputInit.isInvalid())
12870       return true;
12871     ConvArgs[ArgIdx] = InputInit.get();
12872   }
12873 
12874   QualType ResultTy = FD->getReturnType();
12875   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12876   ResultTy = ResultTy.getNonLValueExprType(Context);
12877 
12878   UserDefinedLiteral *UDL =
12879     new (Context) UserDefinedLiteral(Context, Fn.get(),
12880                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12881                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12882 
12883   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12884     return ExprError();
12885 
12886   if (CheckFunctionCall(FD, UDL, nullptr))
12887     return ExprError();
12888 
12889   return MaybeBindToTemporary(UDL);
12890 }
12891 
12892 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12893 /// given LookupResult is non-empty, it is assumed to describe a member which
12894 /// will be invoked. Otherwise, the function will be found via argument
12895 /// dependent lookup.
12896 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12897 /// otherwise CallExpr is set to ExprError() and some non-success value
12898 /// is returned.
12899 Sema::ForRangeStatus
12900 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12901                                 SourceLocation RangeLoc,
12902                                 const DeclarationNameInfo &NameInfo,
12903                                 LookupResult &MemberLookup,
12904                                 OverloadCandidateSet *CandidateSet,
12905                                 Expr *Range, ExprResult *CallExpr) {
12906   Scope *S = nullptr;
12907 
12908   CandidateSet->clear();
12909   if (!MemberLookup.empty()) {
12910     ExprResult MemberRef =
12911         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12912                                  /*IsPtr=*/false, CXXScopeSpec(),
12913                                  /*TemplateKWLoc=*/SourceLocation(),
12914                                  /*FirstQualifierInScope=*/nullptr,
12915                                  MemberLookup,
12916                                  /*TemplateArgs=*/nullptr, S);
12917     if (MemberRef.isInvalid()) {
12918       *CallExpr = ExprError();
12919       return FRS_DiagnosticIssued;
12920     }
12921     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12922     if (CallExpr->isInvalid()) {
12923       *CallExpr = ExprError();
12924       return FRS_DiagnosticIssued;
12925     }
12926   } else {
12927     UnresolvedSet<0> FoundNames;
12928     UnresolvedLookupExpr *Fn =
12929       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12930                                    NestedNameSpecifierLoc(), NameInfo,
12931                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12932                                    FoundNames.begin(), FoundNames.end());
12933 
12934     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12935                                                     CandidateSet, CallExpr);
12936     if (CandidateSet->empty() || CandidateSetError) {
12937       *CallExpr = ExprError();
12938       return FRS_NoViableFunction;
12939     }
12940     OverloadCandidateSet::iterator Best;
12941     OverloadingResult OverloadResult =
12942         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12943 
12944     if (OverloadResult == OR_No_Viable_Function) {
12945       *CallExpr = ExprError();
12946       return FRS_NoViableFunction;
12947     }
12948     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12949                                          Loc, nullptr, CandidateSet, &Best,
12950                                          OverloadResult,
12951                                          /*AllowTypoCorrection=*/false);
12952     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12953       *CallExpr = ExprError();
12954       return FRS_DiagnosticIssued;
12955     }
12956   }
12957   return FRS_Success;
12958 }
12959 
12960 
12961 /// FixOverloadedFunctionReference - E is an expression that refers to
12962 /// a C++ overloaded function (possibly with some parentheses and
12963 /// perhaps a '&' around it). We have resolved the overloaded function
12964 /// to the function declaration Fn, so patch up the expression E to
12965 /// refer (possibly indirectly) to Fn. Returns the new expr.
12966 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12967                                            FunctionDecl *Fn) {
12968   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12969     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12970                                                    Found, Fn);
12971     if (SubExpr == PE->getSubExpr())
12972       return PE;
12973 
12974     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12975   }
12976 
12977   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12978     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12979                                                    Found, Fn);
12980     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12981                                SubExpr->getType()) &&
12982            "Implicit cast type cannot be determined from overload");
12983     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12984     if (SubExpr == ICE->getSubExpr())
12985       return ICE;
12986 
12987     return ImplicitCastExpr::Create(Context, ICE->getType(),
12988                                     ICE->getCastKind(),
12989                                     SubExpr, nullptr,
12990                                     ICE->getValueKind());
12991   }
12992 
12993   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12994     assert(UnOp->getOpcode() == UO_AddrOf &&
12995            "Can only take the address of an overloaded function");
12996     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12997       if (Method->isStatic()) {
12998         // Do nothing: static member functions aren't any different
12999         // from non-member functions.
13000       } else {
13001         // Fix the subexpression, which really has to be an
13002         // UnresolvedLookupExpr holding an overloaded member function
13003         // or template.
13004         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13005                                                        Found, Fn);
13006         if (SubExpr == UnOp->getSubExpr())
13007           return UnOp;
13008 
13009         assert(isa<DeclRefExpr>(SubExpr)
13010                && "fixed to something other than a decl ref");
13011         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13012                && "fixed to a member ref with no nested name qualifier");
13013 
13014         // We have taken the address of a pointer to member
13015         // function. Perform the computation here so that we get the
13016         // appropriate pointer to member type.
13017         QualType ClassType
13018           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13019         QualType MemPtrType
13020           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13021         // Under the MS ABI, lock down the inheritance model now.
13022         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13023           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13024 
13025         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13026                                            VK_RValue, OK_Ordinary,
13027                                            UnOp->getOperatorLoc());
13028       }
13029     }
13030     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13031                                                    Found, Fn);
13032     if (SubExpr == UnOp->getSubExpr())
13033       return UnOp;
13034 
13035     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13036                                      Context.getPointerType(SubExpr->getType()),
13037                                        VK_RValue, OK_Ordinary,
13038                                        UnOp->getOperatorLoc());
13039   }
13040 
13041   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13042     // FIXME: avoid copy.
13043     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13044     if (ULE->hasExplicitTemplateArgs()) {
13045       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13046       TemplateArgs = &TemplateArgsBuffer;
13047     }
13048 
13049     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13050                                            ULE->getQualifierLoc(),
13051                                            ULE->getTemplateKeywordLoc(),
13052                                            Fn,
13053                                            /*enclosing*/ false, // FIXME?
13054                                            ULE->getNameLoc(),
13055                                            Fn->getType(),
13056                                            VK_LValue,
13057                                            Found.getDecl(),
13058                                            TemplateArgs);
13059     MarkDeclRefReferenced(DRE);
13060     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13061     return DRE;
13062   }
13063 
13064   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13065     // FIXME: avoid copy.
13066     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13067     if (MemExpr->hasExplicitTemplateArgs()) {
13068       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13069       TemplateArgs = &TemplateArgsBuffer;
13070     }
13071 
13072     Expr *Base;
13073 
13074     // If we're filling in a static method where we used to have an
13075     // implicit member access, rewrite to a simple decl ref.
13076     if (MemExpr->isImplicitAccess()) {
13077       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13078         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13079                                                MemExpr->getQualifierLoc(),
13080                                                MemExpr->getTemplateKeywordLoc(),
13081                                                Fn,
13082                                                /*enclosing*/ false,
13083                                                MemExpr->getMemberLoc(),
13084                                                Fn->getType(),
13085                                                VK_LValue,
13086                                                Found.getDecl(),
13087                                                TemplateArgs);
13088         MarkDeclRefReferenced(DRE);
13089         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13090         return DRE;
13091       } else {
13092         SourceLocation Loc = MemExpr->getMemberLoc();
13093         if (MemExpr->getQualifier())
13094           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13095         CheckCXXThisCapture(Loc);
13096         Base = new (Context) CXXThisExpr(Loc,
13097                                          MemExpr->getBaseType(),
13098                                          /*isImplicit=*/true);
13099       }
13100     } else
13101       Base = MemExpr->getBase();
13102 
13103     ExprValueKind valueKind;
13104     QualType type;
13105     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13106       valueKind = VK_LValue;
13107       type = Fn->getType();
13108     } else {
13109       valueKind = VK_RValue;
13110       type = Context.BoundMemberTy;
13111     }
13112 
13113     MemberExpr *ME = MemberExpr::Create(
13114         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13115         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13116         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13117         OK_Ordinary);
13118     ME->setHadMultipleCandidates(true);
13119     MarkMemberReferenced(ME);
13120     return ME;
13121   }
13122 
13123   llvm_unreachable("Invalid reference to overloaded function");
13124 }
13125 
13126 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13127                                                 DeclAccessPair Found,
13128                                                 FunctionDecl *Fn) {
13129   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13130 }
13131