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(), [](const ParmVarDecl *P) {
43     return P->hasAttr<PassObjectSizeAttr>();
44   });
45 }
46 
47 /// A convenience routine for creating a decayed reference to a function.
48 static ExprResult
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50                       bool HadMultipleCandidates,
51                       SourceLocation Loc = SourceLocation(),
52                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54     return ExprError();
55   // If FoundDecl is different from Fn (such as if one is a template
56   // and the other a specialization), make sure DiagnoseUseOfDecl is
57   // called on both.
58   // FIXME: This would be more comprehensively addressed by modifying
59   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60   // being used.
61   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62     return ExprError();
63   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64     S.ResolveExceptionSpec(Loc, FPT);
65   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
66                                                  VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE);
71   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72                              CK_FunctionToPointerDecay);
73 }
74 
75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76                                  bool InOverloadResolution,
77                                  StandardConversionSequence &SCS,
78                                  bool CStyle,
79                                  bool AllowObjCWritebackConversion);
80 
81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82                                                  QualType &ToType,
83                                                  bool InOverloadResolution,
84                                                  StandardConversionSequence &SCS,
85                                                  bool CStyle);
86 static OverloadingResult
87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88                         UserDefinedConversionSequence& User,
89                         OverloadCandidateSet& Conversions,
90                         bool AllowExplicit,
91                         bool AllowObjCConversionOnExplicit);
92 
93 
94 static ImplicitConversionSequence::CompareKind
95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96                                    const StandardConversionSequence& SCS1,
97                                    const StandardConversionSequence& SCS2);
98 
99 static ImplicitConversionSequence::CompareKind
100 CompareQualificationConversions(Sema &S,
101                                 const StandardConversionSequence& SCS1,
102                                 const StandardConversionSequence& SCS2);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106                                 const StandardConversionSequence& SCS1,
107                                 const StandardConversionSequence& SCS2);
108 
109 /// GetConversionRank - Retrieve the implicit conversion rank
110 /// corresponding to the given implicit conversion kind.
111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112   static const ImplicitConversionRank
113     Rank[(int)ICK_Num_Conversion_Kinds] = {
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Promotion,
121     ICR_Promotion,
122     ICR_Promotion,
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_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Complex_Real_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Writeback_Conversion,
138     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139                      // it was omitted by the patch that added
140                      // ICK_Zero_Event_Conversion
141     ICR_C_Conversion,
142     ICR_C_Conversion_Extension
143   };
144   return Rank[(int)Kind];
145 }
146 
147 /// GetImplicitConversionName - Return the name of this kind of
148 /// implicit conversion.
149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
151     "No conversion",
152     "Lvalue-to-rvalue",
153     "Array-to-pointer",
154     "Function-to-pointer",
155     "Function pointer conversion",
156     "Qualification",
157     "Integral promotion",
158     "Floating point promotion",
159     "Complex promotion",
160     "Integral conversion",
161     "Floating conversion",
162     "Complex conversion",
163     "Floating-integral conversion",
164     "Pointer conversion",
165     "Pointer-to-member conversion",
166     "Boolean conversion",
167     "Compatible-types conversion",
168     "Derived-to-base conversion",
169     "Vector conversion",
170     "Vector splat",
171     "Complex-real conversion",
172     "Block Pointer conversion",
173     "Transparent Union Conversion",
174     "Writeback conversion",
175     "OpenCL Zero Event Conversion",
176     "C specific type conversion",
177     "Incompatible pointer conversion"
178   };
179   return Name[Kind];
180 }
181 
182 /// StandardConversionSequence - Set the standard conversion
183 /// sequence to the identity conversion.
184 void StandardConversionSequence::setAsIdentityConversion() {
185   First = ICK_Identity;
186   Second = ICK_Identity;
187   Third = ICK_Identity;
188   DeprecatedStringLiteralToCharPtr = false;
189   QualificationIncludesObjCLifetime = false;
190   ReferenceBinding = false;
191   DirectBinding = false;
192   IsLvalueReference = true;
193   BindsToFunctionLvalue = false;
194   BindsToRvalue = false;
195   BindsImplicitObjectArgumentWithoutRefQualifier = false;
196   ObjCLifetimeConversionBinding = false;
197   CopyConstructor = nullptr;
198 }
199 
200 /// getRank - Retrieve the rank of this standard conversion sequence
201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202 /// implicit conversions.
203 ImplicitConversionRank StandardConversionSequence::getRank() const {
204   ImplicitConversionRank Rank = ICR_Exact_Match;
205   if  (GetConversionRank(First) > Rank)
206     Rank = GetConversionRank(First);
207   if  (GetConversionRank(Second) > Rank)
208     Rank = GetConversionRank(Second);
209   if  (GetConversionRank(Third) > Rank)
210     Rank = GetConversionRank(Third);
211   return Rank;
212 }
213 
214 /// isPointerConversionToBool - Determines whether this conversion is
215 /// a conversion of a pointer or pointer-to-member to bool. This is
216 /// used as part of the ranking of standard conversion sequences
217 /// (C++ 13.3.3.2p4).
218 bool StandardConversionSequence::isPointerConversionToBool() const {
219   // Note that FromType has not necessarily been transformed by the
220   // array-to-pointer or function-to-pointer implicit conversions, so
221   // check for their presence as well as checking whether FromType is
222   // a pointer.
223   if (getToType(1)->isBooleanType() &&
224       (getFromType()->isPointerType() ||
225        getFromType()->isObjCObjectPointerType() ||
226        getFromType()->isBlockPointerType() ||
227        getFromType()->isNullPtrType() ||
228        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
229     return true;
230 
231   return false;
232 }
233 
234 /// isPointerConversionToVoidPointer - Determines whether this
235 /// conversion is a conversion of a pointer to a void pointer. This is
236 /// used as part of the ranking of standard conversion sequences (C++
237 /// 13.3.3.2p4).
238 bool
239 StandardConversionSequence::
240 isPointerConversionToVoidPointer(ASTContext& Context) const {
241   QualType FromType = getFromType();
242   QualType ToType = getToType(1);
243 
244   // Note that FromType has not necessarily been transformed by the
245   // array-to-pointer implicit conversion, so check for its presence
246   // and redo the conversion to get a pointer.
247   if (First == ICK_Array_To_Pointer)
248     FromType = Context.getArrayDecayedType(FromType);
249 
250   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
251     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
252       return ToPtrType->getPointeeType()->isVoidType();
253 
254   return false;
255 }
256 
257 /// Skip any implicit casts which could be either part of a narrowing conversion
258 /// or after one in an implicit conversion.
259 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
260   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
261     switch (ICE->getCastKind()) {
262     case CK_NoOp:
263     case CK_IntegralCast:
264     case CK_IntegralToBoolean:
265     case CK_IntegralToFloating:
266     case CK_BooleanToSignedIntegral:
267     case CK_FloatingToIntegral:
268     case CK_FloatingToBoolean:
269     case CK_FloatingCast:
270       Converted = ICE->getSubExpr();
271       continue;
272 
273     default:
274       return Converted;
275     }
276   }
277 
278   return Converted;
279 }
280 
281 /// Check if this standard conversion sequence represents a narrowing
282 /// conversion, according to C++11 [dcl.init.list]p7.
283 ///
284 /// \param Ctx  The AST context.
285 /// \param Converted  The result of applying this standard conversion sequence.
286 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
287 ///        value of the expression prior to the narrowing conversion.
288 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
289 ///        type of the expression prior to the narrowing conversion.
290 NarrowingKind
291 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
292                                              const Expr *Converted,
293                                              APValue &ConstantValue,
294                                              QualType &ConstantType) const {
295   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
296 
297   // C++11 [dcl.init.list]p7:
298   //   A narrowing conversion is an implicit conversion ...
299   QualType FromType = getToType(0);
300   QualType ToType = getToType(1);
301 
302   // A conversion to an enumeration type is narrowing if the conversion to
303   // the underlying type is narrowing. This only arises for expressions of
304   // the form 'Enum{init}'.
305   if (auto *ET = ToType->getAs<EnumType>())
306     ToType = ET->getDecl()->getIntegerType();
307 
308   switch (Second) {
309   // 'bool' is an integral type; dispatch to the right place to handle it.
310   case ICK_Boolean_Conversion:
311     if (FromType->isRealFloatingType())
312       goto FloatingIntegralConversion;
313     if (FromType->isIntegralOrUnscopedEnumerationType())
314       goto IntegralConversion;
315     // Boolean conversions can be from pointers and pointers to members
316     // [conv.bool], and those aren't considered narrowing conversions.
317     return NK_Not_Narrowing;
318 
319   // -- from a floating-point type to an integer type, or
320   //
321   // -- from an integer type or unscoped enumeration type to a floating-point
322   //    type, except where the source is a constant expression and the actual
323   //    value after conversion will fit into the target type and will produce
324   //    the original value when converted back to the original type, or
325   case ICK_Floating_Integral:
326   FloatingIntegralConversion:
327     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328       return NK_Type_Narrowing;
329     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330       llvm::APSInt IntConstantValue;
331       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
332       if (Initializer &&
333           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334         // Convert the integer to the floating type.
335         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337                                 llvm::APFloat::rmNearestTiesToEven);
338         // And back.
339         llvm::APSInt ConvertedValue = IntConstantValue;
340         bool ignored;
341         Result.convertToInteger(ConvertedValue,
342                                 llvm::APFloat::rmTowardZero, &ignored);
343         // If the resulting value is different, this was a narrowing conversion.
344         if (IntConstantValue != ConvertedValue) {
345           ConstantValue = APValue(IntConstantValue);
346           ConstantType = Initializer->getType();
347           return NK_Constant_Narrowing;
348         }
349       } else {
350         // Variables are always narrowings.
351         return NK_Variable_Narrowing;
352       }
353     }
354     return NK_Not_Narrowing;
355 
356   // -- from long double to double or float, or from double to float, except
357   //    where the source is a constant expression and the actual value after
358   //    conversion is within the range of values that can be represented (even
359   //    if it cannot be represented exactly), or
360   case ICK_Floating_Conversion:
361     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363       // FromType is larger than ToType.
364       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366         // Constant!
367         assert(ConstantValue.isFloat());
368         llvm::APFloat FloatVal = ConstantValue.getFloat();
369         // Convert the source value into the target type.
370         bool ignored;
371         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372           Ctx.getFloatTypeSemantics(ToType),
373           llvm::APFloat::rmNearestTiesToEven, &ignored);
374         // If there was no overflow, the source value is within the range of
375         // values that can be represented.
376         if (ConvertStatus & llvm::APFloat::opOverflow) {
377           ConstantType = Initializer->getType();
378           return NK_Constant_Narrowing;
379         }
380       } else {
381         return NK_Variable_Narrowing;
382       }
383     }
384     return NK_Not_Narrowing;
385 
386   // -- from an integer type or unscoped enumeration type to an integer type
387   //    that cannot represent all the values of the original type, except where
388   //    the source is a constant expression and the actual value after
389   //    conversion will fit into the target type and will produce the original
390   //    value when converted back to the original type.
391   case ICK_Integral_Conversion:
392   IntegralConversion: {
393     assert(FromType->isIntegralOrUnscopedEnumerationType());
394     assert(ToType->isIntegralOrUnscopedEnumerationType());
395     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
396     const unsigned FromWidth = Ctx.getIntWidth(FromType);
397     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
398     const unsigned ToWidth = Ctx.getIntWidth(ToType);
399 
400     if (FromWidth > ToWidth ||
401         (FromWidth == ToWidth && FromSigned != ToSigned) ||
402         (FromSigned && !ToSigned)) {
403       // Not all values of FromType can be represented in ToType.
404       llvm::APSInt InitializerValue;
405       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
406       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
407         // Such conversions on variables are always narrowing.
408         return NK_Variable_Narrowing;
409       }
410       bool Narrowing = false;
411       if (FromWidth < ToWidth) {
412         // Negative -> unsigned is narrowing. Otherwise, more bits is never
413         // narrowing.
414         if (InitializerValue.isSigned() && InitializerValue.isNegative())
415           Narrowing = true;
416       } else {
417         // Add a bit to the InitializerValue so we don't have to worry about
418         // signed vs. unsigned comparisons.
419         InitializerValue = InitializerValue.extend(
420           InitializerValue.getBitWidth() + 1);
421         // Convert the initializer to and from the target width and signed-ness.
422         llvm::APSInt ConvertedValue = InitializerValue;
423         ConvertedValue = ConvertedValue.trunc(ToWidth);
424         ConvertedValue.setIsSigned(ToSigned);
425         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
426         ConvertedValue.setIsSigned(InitializerValue.isSigned());
427         // If the result is different, this was a narrowing conversion.
428         if (ConvertedValue != InitializerValue)
429           Narrowing = true;
430       }
431       if (Narrowing) {
432         ConstantType = Initializer->getType();
433         ConstantValue = APValue(InitializerValue);
434         return NK_Constant_Narrowing;
435       }
436     }
437     return NK_Not_Narrowing;
438   }
439 
440   default:
441     // Other kinds of conversions are not narrowings.
442     return NK_Not_Narrowing;
443   }
444 }
445 
446 /// dump - Print this standard conversion sequence to standard
447 /// error. Useful for debugging overloading issues.
448 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
449   raw_ostream &OS = llvm::errs();
450   bool PrintedSomething = false;
451   if (First != ICK_Identity) {
452     OS << GetImplicitConversionName(First);
453     PrintedSomething = true;
454   }
455 
456   if (Second != ICK_Identity) {
457     if (PrintedSomething) {
458       OS << " -> ";
459     }
460     OS << GetImplicitConversionName(Second);
461 
462     if (CopyConstructor) {
463       OS << " (by copy constructor)";
464     } else if (DirectBinding) {
465       OS << " (direct reference binding)";
466     } else if (ReferenceBinding) {
467       OS << " (reference binding)";
468     }
469     PrintedSomething = true;
470   }
471 
472   if (Third != ICK_Identity) {
473     if (PrintedSomething) {
474       OS << " -> ";
475     }
476     OS << GetImplicitConversionName(Third);
477     PrintedSomething = true;
478   }
479 
480   if (!PrintedSomething) {
481     OS << "No conversions required";
482   }
483 }
484 
485 /// dump - Print this user-defined conversion sequence to standard
486 /// error. Useful for debugging overloading issues.
487 void UserDefinedConversionSequence::dump() const {
488   raw_ostream &OS = llvm::errs();
489   if (Before.First || Before.Second || Before.Third) {
490     Before.dump();
491     OS << " -> ";
492   }
493   if (ConversionFunction)
494     OS << '\'' << *ConversionFunction << '\'';
495   else
496     OS << "aggregate initialization";
497   if (After.First || After.Second || After.Third) {
498     OS << " -> ";
499     After.dump();
500   }
501 }
502 
503 /// dump - Print this implicit conversion sequence to standard
504 /// error. Useful for debugging overloading issues.
505 void ImplicitConversionSequence::dump() const {
506   raw_ostream &OS = llvm::errs();
507   if (isStdInitializerListElement())
508     OS << "Worst std::initializer_list element conversion: ";
509   switch (ConversionKind) {
510   case StandardConversion:
511     OS << "Standard conversion: ";
512     Standard.dump();
513     break;
514   case UserDefinedConversion:
515     OS << "User-defined conversion: ";
516     UserDefined.dump();
517     break;
518   case EllipsisConversion:
519     OS << "Ellipsis conversion";
520     break;
521   case AmbiguousConversion:
522     OS << "Ambiguous conversion";
523     break;
524   case BadConversion:
525     OS << "Bad conversion";
526     break;
527   }
528 
529   OS << "\n";
530 }
531 
532 void AmbiguousConversionSequence::construct() {
533   new (&conversions()) ConversionSet();
534 }
535 
536 void AmbiguousConversionSequence::destruct() {
537   conversions().~ConversionSet();
538 }
539 
540 void
541 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
542   FromTypePtr = O.FromTypePtr;
543   ToTypePtr = O.ToTypePtr;
544   new (&conversions()) ConversionSet(O.conversions());
545 }
546 
547 namespace {
548   // Structure used by DeductionFailureInfo to store
549   // template argument information.
550   struct DFIArguments {
551     TemplateArgument FirstArg;
552     TemplateArgument SecondArg;
553   };
554   // Structure used by DeductionFailureInfo to store
555   // template parameter and template argument information.
556   struct DFIParamWithArguments : DFIArguments {
557     TemplateParameter Param;
558   };
559   // Structure used by DeductionFailureInfo to store template argument
560   // information and the index of the problematic call argument.
561   struct DFIDeducedMismatchArgs : DFIArguments {
562     TemplateArgumentList *TemplateArgs;
563     unsigned CallArgIndex;
564   };
565 }
566 
567 /// \brief Convert from Sema's representation of template deduction information
568 /// to the form used in overload-candidate information.
569 DeductionFailureInfo
570 clang::MakeDeductionFailureInfo(ASTContext &Context,
571                                 Sema::TemplateDeductionResult TDK,
572                                 TemplateDeductionInfo &Info) {
573   DeductionFailureInfo Result;
574   Result.Result = static_cast<unsigned>(TDK);
575   Result.HasDiagnostic = false;
576   switch (TDK) {
577   case Sema::TDK_Success:
578   case Sema::TDK_Invalid:
579   case Sema::TDK_InstantiationDepth:
580   case Sema::TDK_TooManyArguments:
581   case Sema::TDK_TooFewArguments:
582   case Sema::TDK_MiscellaneousDeductionFailure:
583     Result.Data = nullptr;
584     break;
585 
586   case Sema::TDK_Incomplete:
587   case Sema::TDK_InvalidExplicitArguments:
588     Result.Data = Info.Param.getOpaqueValue();
589     break;
590 
591   case Sema::TDK_DeducedMismatch: {
592     // FIXME: Should allocate from normal heap so that we can free this later.
593     auto *Saved = new (Context) DFIDeducedMismatchArgs;
594     Saved->FirstArg = Info.FirstArg;
595     Saved->SecondArg = Info.SecondArg;
596     Saved->TemplateArgs = Info.take();
597     Saved->CallArgIndex = Info.CallArgIndex;
598     Result.Data = Saved;
599     break;
600   }
601 
602   case Sema::TDK_NonDeducedMismatch: {
603     // FIXME: Should allocate from normal heap so that we can free this later.
604     DFIArguments *Saved = new (Context) DFIArguments;
605     Saved->FirstArg = Info.FirstArg;
606     Saved->SecondArg = Info.SecondArg;
607     Result.Data = Saved;
608     break;
609   }
610 
611   case Sema::TDK_Inconsistent:
612   case Sema::TDK_Underqualified: {
613     // FIXME: Should allocate from normal heap so that we can free this later.
614     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
615     Saved->Param = Info.Param;
616     Saved->FirstArg = Info.FirstArg;
617     Saved->SecondArg = Info.SecondArg;
618     Result.Data = Saved;
619     break;
620   }
621 
622   case Sema::TDK_SubstitutionFailure:
623     Result.Data = Info.take();
624     if (Info.hasSFINAEDiagnostic()) {
625       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
626           SourceLocation(), PartialDiagnostic::NullDiagnostic());
627       Info.takeSFINAEDiagnostic(*Diag);
628       Result.HasDiagnostic = true;
629     }
630     break;
631 
632   case Sema::TDK_FailedOverloadResolution:
633     Result.Data = Info.Expression;
634     break;
635   }
636 
637   return Result;
638 }
639 
640 void DeductionFailureInfo::Destroy() {
641   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
642   case Sema::TDK_Success:
643   case Sema::TDK_Invalid:
644   case Sema::TDK_InstantiationDepth:
645   case Sema::TDK_Incomplete:
646   case Sema::TDK_TooManyArguments:
647   case Sema::TDK_TooFewArguments:
648   case Sema::TDK_InvalidExplicitArguments:
649   case Sema::TDK_FailedOverloadResolution:
650     break;
651 
652   case Sema::TDK_Inconsistent:
653   case Sema::TDK_Underqualified:
654   case Sema::TDK_DeducedMismatch:
655   case Sema::TDK_NonDeducedMismatch:
656     // FIXME: Destroy the data?
657     Data = nullptr;
658     break;
659 
660   case Sema::TDK_SubstitutionFailure:
661     // FIXME: Destroy the template argument list?
662     Data = nullptr;
663     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
664       Diag->~PartialDiagnosticAt();
665       HasDiagnostic = false;
666     }
667     break;
668 
669   // Unhandled
670   case Sema::TDK_MiscellaneousDeductionFailure:
671     break;
672   }
673 }
674 
675 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
676   if (HasDiagnostic)
677     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
678   return nullptr;
679 }
680 
681 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
682   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
683   case Sema::TDK_Success:
684   case Sema::TDK_Invalid:
685   case Sema::TDK_InstantiationDepth:
686   case Sema::TDK_TooManyArguments:
687   case Sema::TDK_TooFewArguments:
688   case Sema::TDK_SubstitutionFailure:
689   case Sema::TDK_DeducedMismatch:
690   case Sema::TDK_NonDeducedMismatch:
691   case Sema::TDK_FailedOverloadResolution:
692     return TemplateParameter();
693 
694   case Sema::TDK_Incomplete:
695   case Sema::TDK_InvalidExplicitArguments:
696     return TemplateParameter::getFromOpaqueValue(Data);
697 
698   case Sema::TDK_Inconsistent:
699   case Sema::TDK_Underqualified:
700     return static_cast<DFIParamWithArguments*>(Data)->Param;
701 
702   // Unhandled
703   case Sema::TDK_MiscellaneousDeductionFailure:
704     break;
705   }
706 
707   return TemplateParameter();
708 }
709 
710 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
711   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
712   case Sema::TDK_Success:
713   case Sema::TDK_Invalid:
714   case Sema::TDK_InstantiationDepth:
715   case Sema::TDK_TooManyArguments:
716   case Sema::TDK_TooFewArguments:
717   case Sema::TDK_Incomplete:
718   case Sema::TDK_InvalidExplicitArguments:
719   case Sema::TDK_Inconsistent:
720   case Sema::TDK_Underqualified:
721   case Sema::TDK_NonDeducedMismatch:
722   case Sema::TDK_FailedOverloadResolution:
723     return nullptr;
724 
725   case Sema::TDK_DeducedMismatch:
726     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
727 
728   case Sema::TDK_SubstitutionFailure:
729     return static_cast<TemplateArgumentList*>(Data);
730 
731   // Unhandled
732   case Sema::TDK_MiscellaneousDeductionFailure:
733     break;
734   }
735 
736   return nullptr;
737 }
738 
739 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
740   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741   case Sema::TDK_Success:
742   case Sema::TDK_Invalid:
743   case Sema::TDK_InstantiationDepth:
744   case Sema::TDK_Incomplete:
745   case Sema::TDK_TooManyArguments:
746   case Sema::TDK_TooFewArguments:
747   case Sema::TDK_InvalidExplicitArguments:
748   case Sema::TDK_SubstitutionFailure:
749   case Sema::TDK_FailedOverloadResolution:
750     return nullptr;
751 
752   case Sema::TDK_Inconsistent:
753   case Sema::TDK_Underqualified:
754   case Sema::TDK_DeducedMismatch:
755   case Sema::TDK_NonDeducedMismatch:
756     return &static_cast<DFIArguments*>(Data)->FirstArg;
757 
758   // Unhandled
759   case Sema::TDK_MiscellaneousDeductionFailure:
760     break;
761   }
762 
763   return nullptr;
764 }
765 
766 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
767   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
768   case Sema::TDK_Success:
769   case Sema::TDK_Invalid:
770   case Sema::TDK_InstantiationDepth:
771   case Sema::TDK_Incomplete:
772   case Sema::TDK_TooManyArguments:
773   case Sema::TDK_TooFewArguments:
774   case Sema::TDK_InvalidExplicitArguments:
775   case Sema::TDK_SubstitutionFailure:
776   case Sema::TDK_FailedOverloadResolution:
777     return nullptr;
778 
779   case Sema::TDK_Inconsistent:
780   case Sema::TDK_Underqualified:
781   case Sema::TDK_DeducedMismatch:
782   case Sema::TDK_NonDeducedMismatch:
783     return &static_cast<DFIArguments*>(Data)->SecondArg;
784 
785   // Unhandled
786   case Sema::TDK_MiscellaneousDeductionFailure:
787     break;
788   }
789 
790   return nullptr;
791 }
792 
793 Expr *DeductionFailureInfo::getExpr() {
794   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
795         Sema::TDK_FailedOverloadResolution)
796     return static_cast<Expr*>(Data);
797 
798   return nullptr;
799 }
800 
801 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
802   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
803         Sema::TDK_DeducedMismatch)
804     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
805 
806   return llvm::None;
807 }
808 
809 void OverloadCandidateSet::destroyCandidates() {
810   for (iterator i = begin(), e = end(); i != e; ++i) {
811     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
812       i->Conversions[ii].~ImplicitConversionSequence();
813     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
814       i->DeductionFailure.Destroy();
815   }
816 }
817 
818 void OverloadCandidateSet::clear() {
819   destroyCandidates();
820   NumInlineSequences = 0;
821   Candidates.clear();
822   Functions.clear();
823 }
824 
825 namespace {
826   class UnbridgedCastsSet {
827     struct Entry {
828       Expr **Addr;
829       Expr *Saved;
830     };
831     SmallVector<Entry, 2> Entries;
832 
833   public:
834     void save(Sema &S, Expr *&E) {
835       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
836       Entry entry = { &E, E };
837       Entries.push_back(entry);
838       E = S.stripARCUnbridgedCast(E);
839     }
840 
841     void restore() {
842       for (SmallVectorImpl<Entry>::iterator
843              i = Entries.begin(), e = Entries.end(); i != e; ++i)
844         *i->Addr = i->Saved;
845     }
846   };
847 }
848 
849 /// checkPlaceholderForOverload - Do any interesting placeholder-like
850 /// preprocessing on the given expression.
851 ///
852 /// \param unbridgedCasts a collection to which to add unbridged casts;
853 ///   without this, they will be immediately diagnosed as errors
854 ///
855 /// Return true on unrecoverable error.
856 static bool
857 checkPlaceholderForOverload(Sema &S, Expr *&E,
858                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
859   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
860     // We can't handle overloaded expressions here because overload
861     // resolution might reasonably tweak them.
862     if (placeholder->getKind() == BuiltinType::Overload) return false;
863 
864     // If the context potentially accepts unbridged ARC casts, strip
865     // the unbridged cast and add it to the collection for later restoration.
866     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
867         unbridgedCasts) {
868       unbridgedCasts->save(S, E);
869       return false;
870     }
871 
872     // Go ahead and check everything else.
873     ExprResult result = S.CheckPlaceholderExpr(E);
874     if (result.isInvalid())
875       return true;
876 
877     E = result.get();
878     return false;
879   }
880 
881   // Nothing to do.
882   return false;
883 }
884 
885 /// checkArgPlaceholdersForOverload - Check a set of call operands for
886 /// placeholders.
887 static bool checkArgPlaceholdersForOverload(Sema &S,
888                                             MultiExprArg Args,
889                                             UnbridgedCastsSet &unbridged) {
890   for (unsigned i = 0, e = Args.size(); i != e; ++i)
891     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
892       return true;
893 
894   return false;
895 }
896 
897 // IsOverload - Determine whether the given New declaration is an
898 // overload of the declarations in Old. This routine returns false if
899 // New and Old cannot be overloaded, e.g., if New has the same
900 // signature as some function in Old (C++ 1.3.10) or if the Old
901 // declarations aren't functions (or function templates) at all. When
902 // it does return false, MatchedDecl will point to the decl that New
903 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
904 // top of the underlying declaration.
905 //
906 // Example: Given the following input:
907 //
908 //   void f(int, float); // #1
909 //   void f(int, int); // #2
910 //   int f(int, int); // #3
911 //
912 // When we process #1, there is no previous declaration of "f",
913 // so IsOverload will not be used.
914 //
915 // When we process #2, Old contains only the FunctionDecl for #1.  By
916 // comparing the parameter types, we see that #1 and #2 are overloaded
917 // (since they have different signatures), so this routine returns
918 // false; MatchedDecl is unchanged.
919 //
920 // When we process #3, Old is an overload set containing #1 and #2. We
921 // compare the signatures of #3 to #1 (they're overloaded, so we do
922 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
923 // identical (return types of functions are not part of the
924 // signature), IsOverload returns false and MatchedDecl will be set to
925 // point to the FunctionDecl for #2.
926 //
927 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
928 // into a class by a using declaration.  The rules for whether to hide
929 // shadow declarations ignore some properties which otherwise figure
930 // into a function template's signature.
931 Sema::OverloadKind
932 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
933                     NamedDecl *&Match, bool NewIsUsingDecl) {
934   for (LookupResult::iterator I = Old.begin(), E = Old.end();
935          I != E; ++I) {
936     NamedDecl *OldD = *I;
937 
938     bool OldIsUsingDecl = false;
939     if (isa<UsingShadowDecl>(OldD)) {
940       OldIsUsingDecl = true;
941 
942       // We can always introduce two using declarations into the same
943       // context, even if they have identical signatures.
944       if (NewIsUsingDecl) continue;
945 
946       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
947     }
948 
949     // A using-declaration does not conflict with another declaration
950     // if one of them is hidden.
951     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
952       continue;
953 
954     // If either declaration was introduced by a using declaration,
955     // we'll need to use slightly different rules for matching.
956     // Essentially, these rules are the normal rules, except that
957     // function templates hide function templates with different
958     // return types or template parameter lists.
959     bool UseMemberUsingDeclRules =
960       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
961       !New->getFriendObjectKind();
962 
963     if (FunctionDecl *OldF = OldD->getAsFunction()) {
964       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
965         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
966           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
967           continue;
968         }
969 
970         if (!isa<FunctionTemplateDecl>(OldD) &&
971             !shouldLinkPossiblyHiddenDecl(*I, New))
972           continue;
973 
974         Match = *I;
975         return Ovl_Match;
976       }
977     } else if (isa<UsingDecl>(OldD)) {
978       // We can overload with these, which can show up when doing
979       // redeclaration checks for UsingDecls.
980       assert(Old.getLookupKind() == LookupUsingDeclName);
981     } else if (isa<TagDecl>(OldD)) {
982       // We can always overload with tags by hiding them.
983     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
984       // Optimistically assume that an unresolved using decl will
985       // overload; if it doesn't, we'll have to diagnose during
986       // template instantiation.
987     } else {
988       // (C++ 13p1):
989       //   Only function declarations can be overloaded; object and type
990       //   declarations cannot be overloaded.
991       Match = *I;
992       return Ovl_NonFunction;
993     }
994   }
995 
996   return Ovl_Overload;
997 }
998 
999 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1000                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1001   // C++ [basic.start.main]p2: This function shall not be overloaded.
1002   if (New->isMain())
1003     return false;
1004 
1005   // MSVCRT user defined entry points cannot be overloaded.
1006   if (New->isMSVCRTEntryPoint())
1007     return false;
1008 
1009   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1010   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1011 
1012   // C++ [temp.fct]p2:
1013   //   A function template can be overloaded with other function templates
1014   //   and with normal (non-template) functions.
1015   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1016     return true;
1017 
1018   // Is the function New an overload of the function Old?
1019   QualType OldQType = Context.getCanonicalType(Old->getType());
1020   QualType NewQType = Context.getCanonicalType(New->getType());
1021 
1022   // Compare the signatures (C++ 1.3.10) of the two functions to
1023   // determine whether they are overloads. If we find any mismatch
1024   // in the signature, they are overloads.
1025 
1026   // If either of these functions is a K&R-style function (no
1027   // prototype), then we consider them to have matching signatures.
1028   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1029       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1030     return false;
1031 
1032   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1033   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1034 
1035   // The signature of a function includes the types of its
1036   // parameters (C++ 1.3.10), which includes the presence or absence
1037   // of the ellipsis; see C++ DR 357).
1038   if (OldQType != NewQType &&
1039       (OldType->getNumParams() != NewType->getNumParams() ||
1040        OldType->isVariadic() != NewType->isVariadic() ||
1041        !FunctionParamTypesAreEqual(OldType, NewType)))
1042     return true;
1043 
1044   // C++ [temp.over.link]p4:
1045   //   The signature of a function template consists of its function
1046   //   signature, its return type and its template parameter list. The names
1047   //   of the template parameters are significant only for establishing the
1048   //   relationship between the template parameters and the rest of the
1049   //   signature.
1050   //
1051   // We check the return type and template parameter lists for function
1052   // templates first; the remaining checks follow.
1053   //
1054   // However, we don't consider either of these when deciding whether
1055   // a member introduced by a shadow declaration is hidden.
1056   if (!UseMemberUsingDeclRules && NewTemplate &&
1057       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1058                                        OldTemplate->getTemplateParameters(),
1059                                        false, TPL_TemplateMatch) ||
1060        OldType->getReturnType() != NewType->getReturnType()))
1061     return true;
1062 
1063   // If the function is a class member, its signature includes the
1064   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1065   //
1066   // As part of this, also check whether one of the member functions
1067   // is static, in which case they are not overloads (C++
1068   // 13.1p2). While not part of the definition of the signature,
1069   // this check is important to determine whether these functions
1070   // can be overloaded.
1071   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1072   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1073   if (OldMethod && NewMethod &&
1074       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1075     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1076       if (!UseMemberUsingDeclRules &&
1077           (OldMethod->getRefQualifier() == RQ_None ||
1078            NewMethod->getRefQualifier() == RQ_None)) {
1079         // C++0x [over.load]p2:
1080         //   - Member function declarations with the same name and the same
1081         //     parameter-type-list as well as member function template
1082         //     declarations with the same name, the same parameter-type-list, and
1083         //     the same template parameter lists cannot be overloaded if any of
1084         //     them, but not all, have a ref-qualifier (8.3.5).
1085         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1086           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1087         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1088       }
1089       return true;
1090     }
1091 
1092     // We may not have applied the implicit const for a constexpr member
1093     // function yet (because we haven't yet resolved whether this is a static
1094     // or non-static member function). Add it now, on the assumption that this
1095     // is a redeclaration of OldMethod.
1096     unsigned OldQuals = OldMethod->getTypeQualifiers();
1097     unsigned NewQuals = NewMethod->getTypeQualifiers();
1098     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1099         !isa<CXXConstructorDecl>(NewMethod))
1100       NewQuals |= Qualifiers::Const;
1101 
1102     // We do not allow overloading based off of '__restrict'.
1103     OldQuals &= ~Qualifiers::Restrict;
1104     NewQuals &= ~Qualifiers::Restrict;
1105     if (OldQuals != NewQuals)
1106       return true;
1107   }
1108 
1109   // Though pass_object_size is placed on parameters and takes an argument, we
1110   // consider it to be a function-level modifier for the sake of function
1111   // identity. Either the function has one or more parameters with
1112   // pass_object_size or it doesn't.
1113   if (functionHasPassObjectSizeParams(New) !=
1114       functionHasPassObjectSizeParams(Old))
1115     return true;
1116 
1117   // enable_if attributes are an order-sensitive part of the signature.
1118   for (specific_attr_iterator<EnableIfAttr>
1119          NewI = New->specific_attr_begin<EnableIfAttr>(),
1120          NewE = New->specific_attr_end<EnableIfAttr>(),
1121          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1122          OldE = Old->specific_attr_end<EnableIfAttr>();
1123        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1124     if (NewI == NewE || OldI == OldE)
1125       return true;
1126     llvm::FoldingSetNodeID NewID, OldID;
1127     NewI->getCond()->Profile(NewID, Context, true);
1128     OldI->getCond()->Profile(OldID, Context, true);
1129     if (NewID != OldID)
1130       return true;
1131   }
1132 
1133   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1134     // Don't allow overloading of destructors.  (In theory we could, but it
1135     // would be a giant change to clang.)
1136     if (isa<CXXDestructorDecl>(New))
1137       return false;
1138 
1139     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1140                        OldTarget = IdentifyCUDATarget(Old);
1141     if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1142       return false;
1143 
1144     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1145 
1146     // Don't allow HD and global functions to overload other functions with the
1147     // same signature.  We allow overloading based on CUDA attributes so that
1148     // functions can have different implementations on the host and device, but
1149     // HD/global functions "exist" in some sense on both the host and device, so
1150     // should have the same implementation on both sides.
1151     if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1152         (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
1153       return false;
1154 
1155     // Allow overloading of functions with same signature and different CUDA
1156     // target attributes.
1157     return NewTarget != OldTarget;
1158   }
1159 
1160   // The signatures match; this is not an overload.
1161   return false;
1162 }
1163 
1164 /// \brief Checks availability of the function depending on the current
1165 /// function context. Inside an unavailable function, unavailability is ignored.
1166 ///
1167 /// \returns true if \arg FD is unavailable and current context is inside
1168 /// an available function, false otherwise.
1169 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1170   if (!FD->isUnavailable())
1171     return false;
1172 
1173   // Walk up the context of the caller.
1174   Decl *C = cast<Decl>(CurContext);
1175   do {
1176     if (C->isUnavailable())
1177       return false;
1178   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1179   return true;
1180 }
1181 
1182 /// \brief Tries a user-defined conversion from From to ToType.
1183 ///
1184 /// Produces an implicit conversion sequence for when a standard conversion
1185 /// is not an option. See TryImplicitConversion for more information.
1186 static ImplicitConversionSequence
1187 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1188                          bool SuppressUserConversions,
1189                          bool AllowExplicit,
1190                          bool InOverloadResolution,
1191                          bool CStyle,
1192                          bool AllowObjCWritebackConversion,
1193                          bool AllowObjCConversionOnExplicit) {
1194   ImplicitConversionSequence ICS;
1195 
1196   if (SuppressUserConversions) {
1197     // We're not in the case above, so there is no conversion that
1198     // we can perform.
1199     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1200     return ICS;
1201   }
1202 
1203   // Attempt user-defined conversion.
1204   OverloadCandidateSet Conversions(From->getExprLoc(),
1205                                    OverloadCandidateSet::CSK_Normal);
1206   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1207                                   Conversions, AllowExplicit,
1208                                   AllowObjCConversionOnExplicit)) {
1209   case OR_Success:
1210   case OR_Deleted:
1211     ICS.setUserDefined();
1212     // C++ [over.ics.user]p4:
1213     //   A conversion of an expression of class type to the same class
1214     //   type is given Exact Match rank, and a conversion of an
1215     //   expression of class type to a base class of that type is
1216     //   given Conversion rank, in spite of the fact that a copy
1217     //   constructor (i.e., a user-defined conversion function) is
1218     //   called for those cases.
1219     if (CXXConstructorDecl *Constructor
1220           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1221       QualType FromCanon
1222         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1223       QualType ToCanon
1224         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1225       if (Constructor->isCopyConstructor() &&
1226           (FromCanon == ToCanon ||
1227            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1228         // Turn this into a "standard" conversion sequence, so that it
1229         // gets ranked with standard conversion sequences.
1230         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1231         ICS.setStandard();
1232         ICS.Standard.setAsIdentityConversion();
1233         ICS.Standard.setFromType(From->getType());
1234         ICS.Standard.setAllToTypes(ToType);
1235         ICS.Standard.CopyConstructor = Constructor;
1236         ICS.Standard.FoundCopyConstructor = Found;
1237         if (ToCanon != FromCanon)
1238           ICS.Standard.Second = ICK_Derived_To_Base;
1239       }
1240     }
1241     break;
1242 
1243   case OR_Ambiguous:
1244     ICS.setAmbiguous();
1245     ICS.Ambiguous.setFromType(From->getType());
1246     ICS.Ambiguous.setToType(ToType);
1247     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1248          Cand != Conversions.end(); ++Cand)
1249       if (Cand->Viable)
1250         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1251     break;
1252 
1253     // Fall through.
1254   case OR_No_Viable_Function:
1255     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1256     break;
1257   }
1258 
1259   return ICS;
1260 }
1261 
1262 /// TryImplicitConversion - Attempt to perform an implicit conversion
1263 /// from the given expression (Expr) to the given type (ToType). This
1264 /// function returns an implicit conversion sequence that can be used
1265 /// to perform the initialization. Given
1266 ///
1267 ///   void f(float f);
1268 ///   void g(int i) { f(i); }
1269 ///
1270 /// this routine would produce an implicit conversion sequence to
1271 /// describe the initialization of f from i, which will be a standard
1272 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1273 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1274 //
1275 /// Note that this routine only determines how the conversion can be
1276 /// performed; it does not actually perform the conversion. As such,
1277 /// it will not produce any diagnostics if no conversion is available,
1278 /// but will instead return an implicit conversion sequence of kind
1279 /// "BadConversion".
1280 ///
1281 /// If @p SuppressUserConversions, then user-defined conversions are
1282 /// not permitted.
1283 /// If @p AllowExplicit, then explicit user-defined conversions are
1284 /// permitted.
1285 ///
1286 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1287 /// writeback conversion, which allows __autoreleasing id* parameters to
1288 /// be initialized with __strong id* or __weak id* arguments.
1289 static ImplicitConversionSequence
1290 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1291                       bool SuppressUserConversions,
1292                       bool AllowExplicit,
1293                       bool InOverloadResolution,
1294                       bool CStyle,
1295                       bool AllowObjCWritebackConversion,
1296                       bool AllowObjCConversionOnExplicit) {
1297   ImplicitConversionSequence ICS;
1298   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1299                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1300     ICS.setStandard();
1301     return ICS;
1302   }
1303 
1304   if (!S.getLangOpts().CPlusPlus) {
1305     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1306     return ICS;
1307   }
1308 
1309   // C++ [over.ics.user]p4:
1310   //   A conversion of an expression of class type to the same class
1311   //   type is given Exact Match rank, and a conversion of an
1312   //   expression of class type to a base class of that type is
1313   //   given Conversion rank, in spite of the fact that a copy/move
1314   //   constructor (i.e., a user-defined conversion function) is
1315   //   called for those cases.
1316   QualType FromType = From->getType();
1317   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1318       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1319        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1320     ICS.setStandard();
1321     ICS.Standard.setAsIdentityConversion();
1322     ICS.Standard.setFromType(FromType);
1323     ICS.Standard.setAllToTypes(ToType);
1324 
1325     // We don't actually check at this point whether there is a valid
1326     // copy/move constructor, since overloading just assumes that it
1327     // exists. When we actually perform initialization, we'll find the
1328     // appropriate constructor to copy the returned object, if needed.
1329     ICS.Standard.CopyConstructor = nullptr;
1330 
1331     // Determine whether this is considered a derived-to-base conversion.
1332     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1333       ICS.Standard.Second = ICK_Derived_To_Base;
1334 
1335     return ICS;
1336   }
1337 
1338   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1339                                   AllowExplicit, InOverloadResolution, CStyle,
1340                                   AllowObjCWritebackConversion,
1341                                   AllowObjCConversionOnExplicit);
1342 }
1343 
1344 ImplicitConversionSequence
1345 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1346                             bool SuppressUserConversions,
1347                             bool AllowExplicit,
1348                             bool InOverloadResolution,
1349                             bool CStyle,
1350                             bool AllowObjCWritebackConversion) {
1351   return ::TryImplicitConversion(*this, From, ToType,
1352                                  SuppressUserConversions, AllowExplicit,
1353                                  InOverloadResolution, CStyle,
1354                                  AllowObjCWritebackConversion,
1355                                  /*AllowObjCConversionOnExplicit=*/false);
1356 }
1357 
1358 /// PerformImplicitConversion - Perform an implicit conversion of the
1359 /// expression From to the type ToType. Returns the
1360 /// converted expression. Flavor is the kind of conversion we're
1361 /// performing, used in the error message. If @p AllowExplicit,
1362 /// explicit user-defined conversions are permitted.
1363 ExprResult
1364 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1365                                 AssignmentAction Action, bool AllowExplicit) {
1366   ImplicitConversionSequence ICS;
1367   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1368 }
1369 
1370 ExprResult
1371 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1372                                 AssignmentAction Action, bool AllowExplicit,
1373                                 ImplicitConversionSequence& ICS) {
1374   if (checkPlaceholderForOverload(*this, From))
1375     return ExprError();
1376 
1377   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1378   bool AllowObjCWritebackConversion
1379     = getLangOpts().ObjCAutoRefCount &&
1380       (Action == AA_Passing || Action == AA_Sending);
1381   if (getLangOpts().ObjC1)
1382     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1383                                       ToType, From->getType(), From);
1384   ICS = ::TryImplicitConversion(*this, From, ToType,
1385                                 /*SuppressUserConversions=*/false,
1386                                 AllowExplicit,
1387                                 /*InOverloadResolution=*/false,
1388                                 /*CStyle=*/false,
1389                                 AllowObjCWritebackConversion,
1390                                 /*AllowObjCConversionOnExplicit=*/false);
1391   return PerformImplicitConversion(From, ToType, ICS, Action);
1392 }
1393 
1394 /// \brief Determine whether the conversion from FromType to ToType is a valid
1395 /// conversion that strips "noexcept" or "noreturn" off the nested function
1396 /// type.
1397 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1398                                 QualType &ResultTy) {
1399   if (Context.hasSameUnqualifiedType(FromType, ToType))
1400     return false;
1401 
1402   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1403   //                    or F(t noexcept) -> F(t)
1404   // where F adds one of the following at most once:
1405   //   - a pointer
1406   //   - a member pointer
1407   //   - a block pointer
1408   // Changes here need matching changes in FindCompositePointerType.
1409   CanQualType CanTo = Context.getCanonicalType(ToType);
1410   CanQualType CanFrom = Context.getCanonicalType(FromType);
1411   Type::TypeClass TyClass = CanTo->getTypeClass();
1412   if (TyClass != CanFrom->getTypeClass()) return false;
1413   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1414     if (TyClass == Type::Pointer) {
1415       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1416       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1417     } else if (TyClass == Type::BlockPointer) {
1418       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1419       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1420     } else if (TyClass == Type::MemberPointer) {
1421       auto ToMPT = CanTo.getAs<MemberPointerType>();
1422       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1423       // A function pointer conversion cannot change the class of the function.
1424       if (ToMPT->getClass() != FromMPT->getClass())
1425         return false;
1426       CanTo = ToMPT->getPointeeType();
1427       CanFrom = FromMPT->getPointeeType();
1428     } else {
1429       return false;
1430     }
1431 
1432     TyClass = CanTo->getTypeClass();
1433     if (TyClass != CanFrom->getTypeClass()) return false;
1434     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1435       return false;
1436   }
1437 
1438   const auto *FromFn = cast<FunctionType>(CanFrom);
1439   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1440 
1441   const auto *ToFn = cast<FunctionType>(CanTo);
1442   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1443 
1444   bool Changed = false;
1445 
1446   // Drop 'noreturn' if not present in target type.
1447   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1448     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1449     Changed = true;
1450   }
1451 
1452   // Drop 'noexcept' if not present in target type.
1453   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1454     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1455     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1456       FromFn = cast<FunctionType>(
1457           Context.getFunctionType(FromFPT->getReturnType(),
1458                                   FromFPT->getParamTypes(),
1459                                   FromFPT->getExtProtoInfo().withExceptionSpec(
1460                                       FunctionProtoType::ExceptionSpecInfo()))
1461                  .getTypePtr());
1462       Changed = true;
1463     }
1464   }
1465 
1466   if (!Changed)
1467     return false;
1468 
1469   assert(QualType(FromFn, 0).isCanonical());
1470   if (QualType(FromFn, 0) != CanTo) return false;
1471 
1472   ResultTy = ToType;
1473   return true;
1474 }
1475 
1476 /// \brief Determine whether the conversion from FromType to ToType is a valid
1477 /// vector conversion.
1478 ///
1479 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1480 /// conversion.
1481 static bool IsVectorConversion(Sema &S, QualType FromType,
1482                                QualType ToType, ImplicitConversionKind &ICK) {
1483   // We need at least one of these types to be a vector type to have a vector
1484   // conversion.
1485   if (!ToType->isVectorType() && !FromType->isVectorType())
1486     return false;
1487 
1488   // Identical types require no conversions.
1489   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1490     return false;
1491 
1492   // There are no conversions between extended vector types, only identity.
1493   if (ToType->isExtVectorType()) {
1494     // There are no conversions between extended vector types other than the
1495     // identity conversion.
1496     if (FromType->isExtVectorType())
1497       return false;
1498 
1499     // Vector splat from any arithmetic type to a vector.
1500     if (FromType->isArithmeticType()) {
1501       ICK = ICK_Vector_Splat;
1502       return true;
1503     }
1504   }
1505 
1506   // We can perform the conversion between vector types in the following cases:
1507   // 1)vector types are equivalent AltiVec and GCC vector types
1508   // 2)lax vector conversions are permitted and the vector types are of the
1509   //   same size
1510   if (ToType->isVectorType() && FromType->isVectorType()) {
1511     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1512         S.isLaxVectorConversion(FromType, ToType)) {
1513       ICK = ICK_Vector_Conversion;
1514       return true;
1515     }
1516   }
1517 
1518   return false;
1519 }
1520 
1521 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1522                                 bool InOverloadResolution,
1523                                 StandardConversionSequence &SCS,
1524                                 bool CStyle);
1525 
1526 /// IsStandardConversion - Determines whether there is a standard
1527 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1528 /// expression From to the type ToType. Standard conversion sequences
1529 /// only consider non-class types; for conversions that involve class
1530 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1531 /// contain the standard conversion sequence required to perform this
1532 /// conversion and this routine will return true. Otherwise, this
1533 /// routine will return false and the value of SCS is unspecified.
1534 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1535                                  bool InOverloadResolution,
1536                                  StandardConversionSequence &SCS,
1537                                  bool CStyle,
1538                                  bool AllowObjCWritebackConversion) {
1539   QualType FromType = From->getType();
1540 
1541   // Standard conversions (C++ [conv])
1542   SCS.setAsIdentityConversion();
1543   SCS.IncompatibleObjC = false;
1544   SCS.setFromType(FromType);
1545   SCS.CopyConstructor = nullptr;
1546 
1547   // There are no standard conversions for class types in C++, so
1548   // abort early. When overloading in C, however, we do permit them.
1549   if (S.getLangOpts().CPlusPlus &&
1550       (FromType->isRecordType() || ToType->isRecordType()))
1551     return false;
1552 
1553   // The first conversion can be an lvalue-to-rvalue conversion,
1554   // array-to-pointer conversion, or function-to-pointer conversion
1555   // (C++ 4p1).
1556 
1557   if (FromType == S.Context.OverloadTy) {
1558     DeclAccessPair AccessPair;
1559     if (FunctionDecl *Fn
1560           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1561                                                  AccessPair)) {
1562       // We were able to resolve the address of the overloaded function,
1563       // so we can convert to the type of that function.
1564       FromType = Fn->getType();
1565       SCS.setFromType(FromType);
1566 
1567       // we can sometimes resolve &foo<int> regardless of ToType, so check
1568       // if the type matches (identity) or we are converting to bool
1569       if (!S.Context.hasSameUnqualifiedType(
1570                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1571         QualType resultTy;
1572         // if the function type matches except for [[noreturn]], it's ok
1573         if (!S.IsFunctionConversion(FromType,
1574               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1575           // otherwise, only a boolean conversion is standard
1576           if (!ToType->isBooleanType())
1577             return false;
1578       }
1579 
1580       // Check if the "from" expression is taking the address of an overloaded
1581       // function and recompute the FromType accordingly. Take advantage of the
1582       // fact that non-static member functions *must* have such an address-of
1583       // expression.
1584       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1585       if (Method && !Method->isStatic()) {
1586         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1587                "Non-unary operator on non-static member address");
1588         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1589                == UO_AddrOf &&
1590                "Non-address-of operator on non-static member address");
1591         const Type *ClassType
1592           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1593         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1594       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1595         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1596                UO_AddrOf &&
1597                "Non-address-of operator for overloaded function expression");
1598         FromType = S.Context.getPointerType(FromType);
1599       }
1600 
1601       // Check that we've computed the proper type after overload resolution.
1602       assert(S.Context.hasSameType(
1603         FromType,
1604         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1605     } else {
1606       return false;
1607     }
1608   }
1609   // Lvalue-to-rvalue conversion (C++11 4.1):
1610   //   A glvalue (3.10) of a non-function, non-array type T can
1611   //   be converted to a prvalue.
1612   bool argIsLValue = From->isGLValue();
1613   if (argIsLValue &&
1614       !FromType->isFunctionType() && !FromType->isArrayType() &&
1615       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1616     SCS.First = ICK_Lvalue_To_Rvalue;
1617 
1618     // C11 6.3.2.1p2:
1619     //   ... if the lvalue has atomic type, the value has the non-atomic version
1620     //   of the type of the lvalue ...
1621     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1622       FromType = Atomic->getValueType();
1623 
1624     // If T is a non-class type, the type of the rvalue is the
1625     // cv-unqualified version of T. Otherwise, the type of the rvalue
1626     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1627     // just strip the qualifiers because they don't matter.
1628     FromType = FromType.getUnqualifiedType();
1629   } else if (FromType->isArrayType()) {
1630     // Array-to-pointer conversion (C++ 4.2)
1631     SCS.First = ICK_Array_To_Pointer;
1632 
1633     // An lvalue or rvalue of type "array of N T" or "array of unknown
1634     // bound of T" can be converted to an rvalue of type "pointer to
1635     // T" (C++ 4.2p1).
1636     FromType = S.Context.getArrayDecayedType(FromType);
1637 
1638     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1639       // This conversion is deprecated in C++03 (D.4)
1640       SCS.DeprecatedStringLiteralToCharPtr = true;
1641 
1642       // For the purpose of ranking in overload resolution
1643       // (13.3.3.1.1), this conversion is considered an
1644       // array-to-pointer conversion followed by a qualification
1645       // conversion (4.4). (C++ 4.2p2)
1646       SCS.Second = ICK_Identity;
1647       SCS.Third = ICK_Qualification;
1648       SCS.QualificationIncludesObjCLifetime = false;
1649       SCS.setAllToTypes(FromType);
1650       return true;
1651     }
1652   } else if (FromType->isFunctionType() && argIsLValue) {
1653     // Function-to-pointer conversion (C++ 4.3).
1654     SCS.First = ICK_Function_To_Pointer;
1655 
1656     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1657       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1658         if (!S.checkAddressOfFunctionIsAvailable(FD))
1659           return false;
1660 
1661     // An lvalue of function type T can be converted to an rvalue of
1662     // type "pointer to T." The result is a pointer to the
1663     // function. (C++ 4.3p1).
1664     FromType = S.Context.getPointerType(FromType);
1665   } else {
1666     // We don't require any conversions for the first step.
1667     SCS.First = ICK_Identity;
1668   }
1669   SCS.setToType(0, FromType);
1670 
1671   // The second conversion can be an integral promotion, floating
1672   // point promotion, integral conversion, floating point conversion,
1673   // floating-integral conversion, pointer conversion,
1674   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1675   // For overloading in C, this can also be a "compatible-type"
1676   // conversion.
1677   bool IncompatibleObjC = false;
1678   ImplicitConversionKind SecondICK = ICK_Identity;
1679   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1680     // The unqualified versions of the types are the same: there's no
1681     // conversion to do.
1682     SCS.Second = ICK_Identity;
1683   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1684     // Integral promotion (C++ 4.5).
1685     SCS.Second = ICK_Integral_Promotion;
1686     FromType = ToType.getUnqualifiedType();
1687   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1688     // Floating point promotion (C++ 4.6).
1689     SCS.Second = ICK_Floating_Promotion;
1690     FromType = ToType.getUnqualifiedType();
1691   } else if (S.IsComplexPromotion(FromType, ToType)) {
1692     // Complex promotion (Clang extension)
1693     SCS.Second = ICK_Complex_Promotion;
1694     FromType = ToType.getUnqualifiedType();
1695   } else if (ToType->isBooleanType() &&
1696              (FromType->isArithmeticType() ||
1697               FromType->isAnyPointerType() ||
1698               FromType->isBlockPointerType() ||
1699               FromType->isMemberPointerType() ||
1700               FromType->isNullPtrType())) {
1701     // Boolean conversions (C++ 4.12).
1702     SCS.Second = ICK_Boolean_Conversion;
1703     FromType = S.Context.BoolTy;
1704   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1705              ToType->isIntegralType(S.Context)) {
1706     // Integral conversions (C++ 4.7).
1707     SCS.Second = ICK_Integral_Conversion;
1708     FromType = ToType.getUnqualifiedType();
1709   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1710     // Complex conversions (C99 6.3.1.6)
1711     SCS.Second = ICK_Complex_Conversion;
1712     FromType = ToType.getUnqualifiedType();
1713   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1714              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1715     // Complex-real conversions (C99 6.3.1.7)
1716     SCS.Second = ICK_Complex_Real;
1717     FromType = ToType.getUnqualifiedType();
1718   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1719     // FIXME: disable conversions between long double and __float128 if
1720     // their representation is different until there is back end support
1721     // We of course allow this conversion if long double is really double.
1722     if (&S.Context.getFloatTypeSemantics(FromType) !=
1723         &S.Context.getFloatTypeSemantics(ToType)) {
1724       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1725                                     ToType == S.Context.LongDoubleTy) ||
1726                                    (FromType == S.Context.LongDoubleTy &&
1727                                     ToType == S.Context.Float128Ty));
1728       if (Float128AndLongDouble &&
1729           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1730            &llvm::APFloat::IEEEdouble))
1731         return false;
1732     }
1733     // Floating point conversions (C++ 4.8).
1734     SCS.Second = ICK_Floating_Conversion;
1735     FromType = ToType.getUnqualifiedType();
1736   } else if ((FromType->isRealFloatingType() &&
1737               ToType->isIntegralType(S.Context)) ||
1738              (FromType->isIntegralOrUnscopedEnumerationType() &&
1739               ToType->isRealFloatingType())) {
1740     // Floating-integral conversions (C++ 4.9).
1741     SCS.Second = ICK_Floating_Integral;
1742     FromType = ToType.getUnqualifiedType();
1743   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1744     SCS.Second = ICK_Block_Pointer_Conversion;
1745   } else if (AllowObjCWritebackConversion &&
1746              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1747     SCS.Second = ICK_Writeback_Conversion;
1748   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1749                                    FromType, IncompatibleObjC)) {
1750     // Pointer conversions (C++ 4.10).
1751     SCS.Second = ICK_Pointer_Conversion;
1752     SCS.IncompatibleObjC = IncompatibleObjC;
1753     FromType = FromType.getUnqualifiedType();
1754   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1755                                          InOverloadResolution, FromType)) {
1756     // Pointer to member conversions (4.11).
1757     SCS.Second = ICK_Pointer_Member;
1758   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1759     SCS.Second = SecondICK;
1760     FromType = ToType.getUnqualifiedType();
1761   } else if (!S.getLangOpts().CPlusPlus &&
1762              S.Context.typesAreCompatible(ToType, FromType)) {
1763     // Compatible conversions (Clang extension for C function overloading)
1764     SCS.Second = ICK_Compatible_Conversion;
1765     FromType = ToType.getUnqualifiedType();
1766   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1767                                              InOverloadResolution,
1768                                              SCS, CStyle)) {
1769     SCS.Second = ICK_TransparentUnionConversion;
1770     FromType = ToType;
1771   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1772                                  CStyle)) {
1773     // tryAtomicConversion has updated the standard conversion sequence
1774     // appropriately.
1775     return true;
1776   } else if (ToType->isEventT() &&
1777              From->isIntegerConstantExpr(S.getASTContext()) &&
1778              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1779     SCS.Second = ICK_Zero_Event_Conversion;
1780     FromType = ToType;
1781   } else {
1782     // No second conversion required.
1783     SCS.Second = ICK_Identity;
1784   }
1785   SCS.setToType(1, FromType);
1786 
1787   // The third conversion can be a function pointer conversion or a
1788   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1789   bool ObjCLifetimeConversion;
1790   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1791     // Function pointer conversions (removing 'noexcept') including removal of
1792     // 'noreturn' (Clang extension).
1793     SCS.Third = ICK_Function_Conversion;
1794   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1795                                          ObjCLifetimeConversion)) {
1796     SCS.Third = ICK_Qualification;
1797     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1798     FromType = ToType;
1799   } else {
1800     // No conversion required
1801     SCS.Third = ICK_Identity;
1802   }
1803 
1804   // C++ [over.best.ics]p6:
1805   //   [...] Any difference in top-level cv-qualification is
1806   //   subsumed by the initialization itself and does not constitute
1807   //   a conversion. [...]
1808   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1809   QualType CanonTo = S.Context.getCanonicalType(ToType);
1810   if (CanonFrom.getLocalUnqualifiedType()
1811                                      == CanonTo.getLocalUnqualifiedType() &&
1812       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1813     FromType = ToType;
1814     CanonFrom = CanonTo;
1815   }
1816 
1817   SCS.setToType(2, FromType);
1818 
1819   if (CanonFrom == CanonTo)
1820     return true;
1821 
1822   // If we have not converted the argument type to the parameter type,
1823   // this is a bad conversion sequence, unless we're resolving an overload in C.
1824   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1825     return false;
1826 
1827   ExprResult ER = ExprResult{From};
1828   Sema::AssignConvertType Conv =
1829       S.CheckSingleAssignmentConstraints(ToType, ER,
1830                                          /*Diagnose=*/false,
1831                                          /*DiagnoseCFAudited=*/false,
1832                                          /*ConvertRHS=*/false);
1833   ImplicitConversionKind SecondConv;
1834   switch (Conv) {
1835   case Sema::Compatible:
1836     SecondConv = ICK_C_Only_Conversion;
1837     break;
1838   // For our purposes, discarding qualifiers is just as bad as using an
1839   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1840   // qualifiers, as well.
1841   case Sema::CompatiblePointerDiscardsQualifiers:
1842   case Sema::IncompatiblePointer:
1843   case Sema::IncompatiblePointerSign:
1844     SecondConv = ICK_Incompatible_Pointer_Conversion;
1845     break;
1846   default:
1847     return false;
1848   }
1849 
1850   // First can only be an lvalue conversion, so we pretend that this was the
1851   // second conversion. First should already be valid from earlier in the
1852   // function.
1853   SCS.Second = SecondConv;
1854   SCS.setToType(1, ToType);
1855 
1856   // Third is Identity, because Second should rank us worse than any other
1857   // conversion. This could also be ICK_Qualification, but it's simpler to just
1858   // lump everything in with the second conversion, and we don't gain anything
1859   // from making this ICK_Qualification.
1860   SCS.Third = ICK_Identity;
1861   SCS.setToType(2, ToType);
1862   return true;
1863 }
1864 
1865 static bool
1866 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1867                                      QualType &ToType,
1868                                      bool InOverloadResolution,
1869                                      StandardConversionSequence &SCS,
1870                                      bool CStyle) {
1871 
1872   const RecordType *UT = ToType->getAsUnionType();
1873   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1874     return false;
1875   // The field to initialize within the transparent union.
1876   RecordDecl *UD = UT->getDecl();
1877   // It's compatible if the expression matches any of the fields.
1878   for (const auto *it : UD->fields()) {
1879     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1880                              CStyle, /*ObjCWritebackConversion=*/false)) {
1881       ToType = it->getType();
1882       return true;
1883     }
1884   }
1885   return false;
1886 }
1887 
1888 /// IsIntegralPromotion - Determines whether the conversion from the
1889 /// expression From (whose potentially-adjusted type is FromType) to
1890 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1891 /// sets PromotedType to the promoted type.
1892 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1893   const BuiltinType *To = ToType->getAs<BuiltinType>();
1894   // All integers are built-in.
1895   if (!To) {
1896     return false;
1897   }
1898 
1899   // An rvalue of type char, signed char, unsigned char, short int, or
1900   // unsigned short int can be converted to an rvalue of type int if
1901   // int can represent all the values of the source type; otherwise,
1902   // the source rvalue can be converted to an rvalue of type unsigned
1903   // int (C++ 4.5p1).
1904   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1905       !FromType->isEnumeralType()) {
1906     if (// We can promote any signed, promotable integer type to an int
1907         (FromType->isSignedIntegerType() ||
1908          // We can promote any unsigned integer type whose size is
1909          // less than int to an int.
1910          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1911       return To->getKind() == BuiltinType::Int;
1912     }
1913 
1914     return To->getKind() == BuiltinType::UInt;
1915   }
1916 
1917   // C++11 [conv.prom]p3:
1918   //   A prvalue of an unscoped enumeration type whose underlying type is not
1919   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1920   //   following types that can represent all the values of the enumeration
1921   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1922   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1923   //   long long int. If none of the types in that list can represent all the
1924   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1925   //   type can be converted to an rvalue a prvalue of the extended integer type
1926   //   with lowest integer conversion rank (4.13) greater than the rank of long
1927   //   long in which all the values of the enumeration can be represented. If
1928   //   there are two such extended types, the signed one is chosen.
1929   // C++11 [conv.prom]p4:
1930   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1931   //   can be converted to a prvalue of its underlying type. Moreover, if
1932   //   integral promotion can be applied to its underlying type, a prvalue of an
1933   //   unscoped enumeration type whose underlying type is fixed can also be
1934   //   converted to a prvalue of the promoted underlying type.
1935   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1936     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1937     // provided for a scoped enumeration.
1938     if (FromEnumType->getDecl()->isScoped())
1939       return false;
1940 
1941     // We can perform an integral promotion to the underlying type of the enum,
1942     // even if that's not the promoted type. Note that the check for promoting
1943     // the underlying type is based on the type alone, and does not consider
1944     // the bitfield-ness of the actual source expression.
1945     if (FromEnumType->getDecl()->isFixed()) {
1946       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1947       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1948              IsIntegralPromotion(nullptr, Underlying, ToType);
1949     }
1950 
1951     // We have already pre-calculated the promotion type, so this is trivial.
1952     if (ToType->isIntegerType() &&
1953         isCompleteType(From->getLocStart(), FromType))
1954       return Context.hasSameUnqualifiedType(
1955           ToType, FromEnumType->getDecl()->getPromotionType());
1956   }
1957 
1958   // C++0x [conv.prom]p2:
1959   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1960   //   to an rvalue a prvalue of the first of the following types that can
1961   //   represent all the values of its underlying type: int, unsigned int,
1962   //   long int, unsigned long int, long long int, or unsigned long long int.
1963   //   If none of the types in that list can represent all the values of its
1964   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1965   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1966   //   type.
1967   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1968       ToType->isIntegerType()) {
1969     // Determine whether the type we're converting from is signed or
1970     // unsigned.
1971     bool FromIsSigned = FromType->isSignedIntegerType();
1972     uint64_t FromSize = Context.getTypeSize(FromType);
1973 
1974     // The types we'll try to promote to, in the appropriate
1975     // order. Try each of these types.
1976     QualType PromoteTypes[6] = {
1977       Context.IntTy, Context.UnsignedIntTy,
1978       Context.LongTy, Context.UnsignedLongTy ,
1979       Context.LongLongTy, Context.UnsignedLongLongTy
1980     };
1981     for (int Idx = 0; Idx < 6; ++Idx) {
1982       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1983       if (FromSize < ToSize ||
1984           (FromSize == ToSize &&
1985            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1986         // We found the type that we can promote to. If this is the
1987         // type we wanted, we have a promotion. Otherwise, no
1988         // promotion.
1989         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1990       }
1991     }
1992   }
1993 
1994   // An rvalue for an integral bit-field (9.6) can be converted to an
1995   // rvalue of type int if int can represent all the values of the
1996   // bit-field; otherwise, it can be converted to unsigned int if
1997   // unsigned int can represent all the values of the bit-field. If
1998   // the bit-field is larger yet, no integral promotion applies to
1999   // it. If the bit-field has an enumerated type, it is treated as any
2000   // other value of that type for promotion purposes (C++ 4.5p3).
2001   // FIXME: We should delay checking of bit-fields until we actually perform the
2002   // conversion.
2003   if (From) {
2004     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2005       llvm::APSInt BitWidth;
2006       if (FromType->isIntegralType(Context) &&
2007           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2008         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2009         ToSize = Context.getTypeSize(ToType);
2010 
2011         // Are we promoting to an int from a bitfield that fits in an int?
2012         if (BitWidth < ToSize ||
2013             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2014           return To->getKind() == BuiltinType::Int;
2015         }
2016 
2017         // Are we promoting to an unsigned int from an unsigned bitfield
2018         // that fits into an unsigned int?
2019         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2020           return To->getKind() == BuiltinType::UInt;
2021         }
2022 
2023         return false;
2024       }
2025     }
2026   }
2027 
2028   // An rvalue of type bool can be converted to an rvalue of type int,
2029   // with false becoming zero and true becoming one (C++ 4.5p4).
2030   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2031     return true;
2032   }
2033 
2034   return false;
2035 }
2036 
2037 /// IsFloatingPointPromotion - Determines whether the conversion from
2038 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2039 /// returns true and sets PromotedType to the promoted type.
2040 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2041   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2042     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2043       /// An rvalue of type float can be converted to an rvalue of type
2044       /// double. (C++ 4.6p1).
2045       if (FromBuiltin->getKind() == BuiltinType::Float &&
2046           ToBuiltin->getKind() == BuiltinType::Double)
2047         return true;
2048 
2049       // C99 6.3.1.5p1:
2050       //   When a float is promoted to double or long double, or a
2051       //   double is promoted to long double [...].
2052       if (!getLangOpts().CPlusPlus &&
2053           (FromBuiltin->getKind() == BuiltinType::Float ||
2054            FromBuiltin->getKind() == BuiltinType::Double) &&
2055           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2056            ToBuiltin->getKind() == BuiltinType::Float128))
2057         return true;
2058 
2059       // Half can be promoted to float.
2060       if (!getLangOpts().NativeHalfType &&
2061            FromBuiltin->getKind() == BuiltinType::Half &&
2062           ToBuiltin->getKind() == BuiltinType::Float)
2063         return true;
2064     }
2065 
2066   return false;
2067 }
2068 
2069 /// \brief Determine if a conversion is a complex promotion.
2070 ///
2071 /// A complex promotion is defined as a complex -> complex conversion
2072 /// where the conversion between the underlying real types is a
2073 /// floating-point or integral promotion.
2074 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2075   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2076   if (!FromComplex)
2077     return false;
2078 
2079   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2080   if (!ToComplex)
2081     return false;
2082 
2083   return IsFloatingPointPromotion(FromComplex->getElementType(),
2084                                   ToComplex->getElementType()) ||
2085     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2086                         ToComplex->getElementType());
2087 }
2088 
2089 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2090 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2091 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2092 /// if non-empty, will be a pointer to ToType that may or may not have
2093 /// the right set of qualifiers on its pointee.
2094 ///
2095 static QualType
2096 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2097                                    QualType ToPointee, QualType ToType,
2098                                    ASTContext &Context,
2099                                    bool StripObjCLifetime = false) {
2100   assert((FromPtr->getTypeClass() == Type::Pointer ||
2101           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2102          "Invalid similarly-qualified pointer type");
2103 
2104   /// Conversions to 'id' subsume cv-qualifier conversions.
2105   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2106     return ToType.getUnqualifiedType();
2107 
2108   QualType CanonFromPointee
2109     = Context.getCanonicalType(FromPtr->getPointeeType());
2110   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2111   Qualifiers Quals = CanonFromPointee.getQualifiers();
2112 
2113   if (StripObjCLifetime)
2114     Quals.removeObjCLifetime();
2115 
2116   // Exact qualifier match -> return the pointer type we're converting to.
2117   if (CanonToPointee.getLocalQualifiers() == Quals) {
2118     // ToType is exactly what we need. Return it.
2119     if (!ToType.isNull())
2120       return ToType.getUnqualifiedType();
2121 
2122     // Build a pointer to ToPointee. It has the right qualifiers
2123     // already.
2124     if (isa<ObjCObjectPointerType>(ToType))
2125       return Context.getObjCObjectPointerType(ToPointee);
2126     return Context.getPointerType(ToPointee);
2127   }
2128 
2129   // Just build a canonical type that has the right qualifiers.
2130   QualType QualifiedCanonToPointee
2131     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2132 
2133   if (isa<ObjCObjectPointerType>(ToType))
2134     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2135   return Context.getPointerType(QualifiedCanonToPointee);
2136 }
2137 
2138 static bool isNullPointerConstantForConversion(Expr *Expr,
2139                                                bool InOverloadResolution,
2140                                                ASTContext &Context) {
2141   // Handle value-dependent integral null pointer constants correctly.
2142   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2143   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2144       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2145     return !InOverloadResolution;
2146 
2147   return Expr->isNullPointerConstant(Context,
2148                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2149                                         : Expr::NPC_ValueDependentIsNull);
2150 }
2151 
2152 /// IsPointerConversion - Determines whether the conversion of the
2153 /// expression From, which has the (possibly adjusted) type FromType,
2154 /// can be converted to the type ToType via a pointer conversion (C++
2155 /// 4.10). If so, returns true and places the converted type (that
2156 /// might differ from ToType in its cv-qualifiers at some level) into
2157 /// ConvertedType.
2158 ///
2159 /// This routine also supports conversions to and from block pointers
2160 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2161 /// pointers to interfaces. FIXME: Once we've determined the
2162 /// appropriate overloading rules for Objective-C, we may want to
2163 /// split the Objective-C checks into a different routine; however,
2164 /// GCC seems to consider all of these conversions to be pointer
2165 /// conversions, so for now they live here. IncompatibleObjC will be
2166 /// set if the conversion is an allowed Objective-C conversion that
2167 /// should result in a warning.
2168 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2169                                bool InOverloadResolution,
2170                                QualType& ConvertedType,
2171                                bool &IncompatibleObjC) {
2172   IncompatibleObjC = false;
2173   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2174                               IncompatibleObjC))
2175     return true;
2176 
2177   // Conversion from a null pointer constant to any Objective-C pointer type.
2178   if (ToType->isObjCObjectPointerType() &&
2179       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2180     ConvertedType = ToType;
2181     return true;
2182   }
2183 
2184   // Blocks: Block pointers can be converted to void*.
2185   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2186       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2187     ConvertedType = ToType;
2188     return true;
2189   }
2190   // Blocks: A null pointer constant can be converted to a block
2191   // pointer type.
2192   if (ToType->isBlockPointerType() &&
2193       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2194     ConvertedType = ToType;
2195     return true;
2196   }
2197 
2198   // If the left-hand-side is nullptr_t, the right side can be a null
2199   // pointer constant.
2200   if (ToType->isNullPtrType() &&
2201       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2202     ConvertedType = ToType;
2203     return true;
2204   }
2205 
2206   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2207   if (!ToTypePtr)
2208     return false;
2209 
2210   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2211   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2212     ConvertedType = ToType;
2213     return true;
2214   }
2215 
2216   // Beyond this point, both types need to be pointers
2217   // , including objective-c pointers.
2218   QualType ToPointeeType = ToTypePtr->getPointeeType();
2219   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2220       !getLangOpts().ObjCAutoRefCount) {
2221     ConvertedType = BuildSimilarlyQualifiedPointerType(
2222                                       FromType->getAs<ObjCObjectPointerType>(),
2223                                                        ToPointeeType,
2224                                                        ToType, Context);
2225     return true;
2226   }
2227   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2228   if (!FromTypePtr)
2229     return false;
2230 
2231   QualType FromPointeeType = FromTypePtr->getPointeeType();
2232 
2233   // If the unqualified pointee types are the same, this can't be a
2234   // pointer conversion, so don't do all of the work below.
2235   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2236     return false;
2237 
2238   // An rvalue of type "pointer to cv T," where T is an object type,
2239   // can be converted to an rvalue of type "pointer to cv void" (C++
2240   // 4.10p2).
2241   if (FromPointeeType->isIncompleteOrObjectType() &&
2242       ToPointeeType->isVoidType()) {
2243     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2244                                                        ToPointeeType,
2245                                                        ToType, Context,
2246                                                    /*StripObjCLifetime=*/true);
2247     return true;
2248   }
2249 
2250   // MSVC allows implicit function to void* type conversion.
2251   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2252       ToPointeeType->isVoidType()) {
2253     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2254                                                        ToPointeeType,
2255                                                        ToType, Context);
2256     return true;
2257   }
2258 
2259   // When we're overloading in C, we allow a special kind of pointer
2260   // conversion for compatible-but-not-identical pointee types.
2261   if (!getLangOpts().CPlusPlus &&
2262       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2263     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2264                                                        ToPointeeType,
2265                                                        ToType, Context);
2266     return true;
2267   }
2268 
2269   // C++ [conv.ptr]p3:
2270   //
2271   //   An rvalue of type "pointer to cv D," where D is a class type,
2272   //   can be converted to an rvalue of type "pointer to cv B," where
2273   //   B is a base class (clause 10) of D. If B is an inaccessible
2274   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2275   //   necessitates this conversion is ill-formed. The result of the
2276   //   conversion is a pointer to the base class sub-object of the
2277   //   derived class object. The null pointer value is converted to
2278   //   the null pointer value of the destination type.
2279   //
2280   // Note that we do not check for ambiguity or inaccessibility
2281   // here. That is handled by CheckPointerConversion.
2282   if (getLangOpts().CPlusPlus &&
2283       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2284       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2285       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2286     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2287                                                        ToPointeeType,
2288                                                        ToType, Context);
2289     return true;
2290   }
2291 
2292   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2293       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2294     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2295                                                        ToPointeeType,
2296                                                        ToType, Context);
2297     return true;
2298   }
2299 
2300   return false;
2301 }
2302 
2303 /// \brief Adopt the given qualifiers for the given type.
2304 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2305   Qualifiers TQs = T.getQualifiers();
2306 
2307   // Check whether qualifiers already match.
2308   if (TQs == Qs)
2309     return T;
2310 
2311   if (Qs.compatiblyIncludes(TQs))
2312     return Context.getQualifiedType(T, Qs);
2313 
2314   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2315 }
2316 
2317 /// isObjCPointerConversion - Determines whether this is an
2318 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2319 /// with the same arguments and return values.
2320 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2321                                    QualType& ConvertedType,
2322                                    bool &IncompatibleObjC) {
2323   if (!getLangOpts().ObjC1)
2324     return false;
2325 
2326   // The set of qualifiers on the type we're converting from.
2327   Qualifiers FromQualifiers = FromType.getQualifiers();
2328 
2329   // First, we handle all conversions on ObjC object pointer types.
2330   const ObjCObjectPointerType* ToObjCPtr =
2331     ToType->getAs<ObjCObjectPointerType>();
2332   const ObjCObjectPointerType *FromObjCPtr =
2333     FromType->getAs<ObjCObjectPointerType>();
2334 
2335   if (ToObjCPtr && FromObjCPtr) {
2336     // If the pointee types are the same (ignoring qualifications),
2337     // then this is not a pointer conversion.
2338     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2339                                        FromObjCPtr->getPointeeType()))
2340       return false;
2341 
2342     // Conversion between Objective-C pointers.
2343     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2344       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2345       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2346       if (getLangOpts().CPlusPlus && LHS && RHS &&
2347           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2348                                                 FromObjCPtr->getPointeeType()))
2349         return false;
2350       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2351                                                    ToObjCPtr->getPointeeType(),
2352                                                          ToType, Context);
2353       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2354       return true;
2355     }
2356 
2357     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2358       // Okay: this is some kind of implicit downcast of Objective-C
2359       // interfaces, which is permitted. However, we're going to
2360       // complain about it.
2361       IncompatibleObjC = true;
2362       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2363                                                    ToObjCPtr->getPointeeType(),
2364                                                          ToType, Context);
2365       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2366       return true;
2367     }
2368   }
2369   // Beyond this point, both types need to be C pointers or block pointers.
2370   QualType ToPointeeType;
2371   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2372     ToPointeeType = ToCPtr->getPointeeType();
2373   else if (const BlockPointerType *ToBlockPtr =
2374             ToType->getAs<BlockPointerType>()) {
2375     // Objective C++: We're able to convert from a pointer to any object
2376     // to a block pointer type.
2377     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2378       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2379       return true;
2380     }
2381     ToPointeeType = ToBlockPtr->getPointeeType();
2382   }
2383   else if (FromType->getAs<BlockPointerType>() &&
2384            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2385     // Objective C++: We're able to convert from a block pointer type to a
2386     // pointer to any object.
2387     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2388     return true;
2389   }
2390   else
2391     return false;
2392 
2393   QualType FromPointeeType;
2394   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2395     FromPointeeType = FromCPtr->getPointeeType();
2396   else if (const BlockPointerType *FromBlockPtr =
2397            FromType->getAs<BlockPointerType>())
2398     FromPointeeType = FromBlockPtr->getPointeeType();
2399   else
2400     return false;
2401 
2402   // If we have pointers to pointers, recursively check whether this
2403   // is an Objective-C conversion.
2404   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2405       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2406                               IncompatibleObjC)) {
2407     // We always complain about this conversion.
2408     IncompatibleObjC = true;
2409     ConvertedType = Context.getPointerType(ConvertedType);
2410     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2411     return true;
2412   }
2413   // Allow conversion of pointee being objective-c pointer to another one;
2414   // as in I* to id.
2415   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2416       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2417       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2418                               IncompatibleObjC)) {
2419 
2420     ConvertedType = Context.getPointerType(ConvertedType);
2421     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2422     return true;
2423   }
2424 
2425   // If we have pointers to functions or blocks, check whether the only
2426   // differences in the argument and result types are in Objective-C
2427   // pointer conversions. If so, we permit the conversion (but
2428   // complain about it).
2429   const FunctionProtoType *FromFunctionType
2430     = FromPointeeType->getAs<FunctionProtoType>();
2431   const FunctionProtoType *ToFunctionType
2432     = ToPointeeType->getAs<FunctionProtoType>();
2433   if (FromFunctionType && ToFunctionType) {
2434     // If the function types are exactly the same, this isn't an
2435     // Objective-C pointer conversion.
2436     if (Context.getCanonicalType(FromPointeeType)
2437           == Context.getCanonicalType(ToPointeeType))
2438       return false;
2439 
2440     // Perform the quick checks that will tell us whether these
2441     // function types are obviously different.
2442     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2443         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2444         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2445       return false;
2446 
2447     bool HasObjCConversion = false;
2448     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2449         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2450       // Okay, the types match exactly. Nothing to do.
2451     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2452                                        ToFunctionType->getReturnType(),
2453                                        ConvertedType, IncompatibleObjC)) {
2454       // Okay, we have an Objective-C pointer conversion.
2455       HasObjCConversion = true;
2456     } else {
2457       // Function types are too different. Abort.
2458       return false;
2459     }
2460 
2461     // Check argument types.
2462     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2463          ArgIdx != NumArgs; ++ArgIdx) {
2464       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2465       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2466       if (Context.getCanonicalType(FromArgType)
2467             == Context.getCanonicalType(ToArgType)) {
2468         // Okay, the types match exactly. Nothing to do.
2469       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2470                                          ConvertedType, IncompatibleObjC)) {
2471         // Okay, we have an Objective-C pointer conversion.
2472         HasObjCConversion = true;
2473       } else {
2474         // Argument types are too different. Abort.
2475         return false;
2476       }
2477     }
2478 
2479     if (HasObjCConversion) {
2480       // We had an Objective-C conversion. Allow this pointer
2481       // conversion, but complain about it.
2482       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2483       IncompatibleObjC = true;
2484       return true;
2485     }
2486   }
2487 
2488   return false;
2489 }
2490 
2491 /// \brief Determine whether this is an Objective-C writeback conversion,
2492 /// used for parameter passing when performing automatic reference counting.
2493 ///
2494 /// \param FromType The type we're converting form.
2495 ///
2496 /// \param ToType The type we're converting to.
2497 ///
2498 /// \param ConvertedType The type that will be produced after applying
2499 /// this conversion.
2500 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2501                                      QualType &ConvertedType) {
2502   if (!getLangOpts().ObjCAutoRefCount ||
2503       Context.hasSameUnqualifiedType(FromType, ToType))
2504     return false;
2505 
2506   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2507   QualType ToPointee;
2508   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2509     ToPointee = ToPointer->getPointeeType();
2510   else
2511     return false;
2512 
2513   Qualifiers ToQuals = ToPointee.getQualifiers();
2514   if (!ToPointee->isObjCLifetimeType() ||
2515       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2516       !ToQuals.withoutObjCLifetime().empty())
2517     return false;
2518 
2519   // Argument must be a pointer to __strong to __weak.
2520   QualType FromPointee;
2521   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2522     FromPointee = FromPointer->getPointeeType();
2523   else
2524     return false;
2525 
2526   Qualifiers FromQuals = FromPointee.getQualifiers();
2527   if (!FromPointee->isObjCLifetimeType() ||
2528       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2529        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2530     return false;
2531 
2532   // Make sure that we have compatible qualifiers.
2533   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2534   if (!ToQuals.compatiblyIncludes(FromQuals))
2535     return false;
2536 
2537   // Remove qualifiers from the pointee type we're converting from; they
2538   // aren't used in the compatibility check belong, and we'll be adding back
2539   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2540   FromPointee = FromPointee.getUnqualifiedType();
2541 
2542   // The unqualified form of the pointee types must be compatible.
2543   ToPointee = ToPointee.getUnqualifiedType();
2544   bool IncompatibleObjC;
2545   if (Context.typesAreCompatible(FromPointee, ToPointee))
2546     FromPointee = ToPointee;
2547   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2548                                     IncompatibleObjC))
2549     return false;
2550 
2551   /// \brief Construct the type we're converting to, which is a pointer to
2552   /// __autoreleasing pointee.
2553   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2554   ConvertedType = Context.getPointerType(FromPointee);
2555   return true;
2556 }
2557 
2558 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2559                                     QualType& ConvertedType) {
2560   QualType ToPointeeType;
2561   if (const BlockPointerType *ToBlockPtr =
2562         ToType->getAs<BlockPointerType>())
2563     ToPointeeType = ToBlockPtr->getPointeeType();
2564   else
2565     return false;
2566 
2567   QualType FromPointeeType;
2568   if (const BlockPointerType *FromBlockPtr =
2569       FromType->getAs<BlockPointerType>())
2570     FromPointeeType = FromBlockPtr->getPointeeType();
2571   else
2572     return false;
2573   // We have pointer to blocks, check whether the only
2574   // differences in the argument and result types are in Objective-C
2575   // pointer conversions. If so, we permit the conversion.
2576 
2577   const FunctionProtoType *FromFunctionType
2578     = FromPointeeType->getAs<FunctionProtoType>();
2579   const FunctionProtoType *ToFunctionType
2580     = ToPointeeType->getAs<FunctionProtoType>();
2581 
2582   if (!FromFunctionType || !ToFunctionType)
2583     return false;
2584 
2585   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2586     return true;
2587 
2588   // Perform the quick checks that will tell us whether these
2589   // function types are obviously different.
2590   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2591       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2592     return false;
2593 
2594   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2595   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2596   if (FromEInfo != ToEInfo)
2597     return false;
2598 
2599   bool IncompatibleObjC = false;
2600   if (Context.hasSameType(FromFunctionType->getReturnType(),
2601                           ToFunctionType->getReturnType())) {
2602     // Okay, the types match exactly. Nothing to do.
2603   } else {
2604     QualType RHS = FromFunctionType->getReturnType();
2605     QualType LHS = ToFunctionType->getReturnType();
2606     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2607         !RHS.hasQualifiers() && LHS.hasQualifiers())
2608        LHS = LHS.getUnqualifiedType();
2609 
2610      if (Context.hasSameType(RHS,LHS)) {
2611        // OK exact match.
2612      } else if (isObjCPointerConversion(RHS, LHS,
2613                                         ConvertedType, IncompatibleObjC)) {
2614      if (IncompatibleObjC)
2615        return false;
2616      // Okay, we have an Objective-C pointer conversion.
2617      }
2618      else
2619        return false;
2620    }
2621 
2622    // Check argument types.
2623    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2624         ArgIdx != NumArgs; ++ArgIdx) {
2625      IncompatibleObjC = false;
2626      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2627      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2628      if (Context.hasSameType(FromArgType, ToArgType)) {
2629        // Okay, the types match exactly. Nothing to do.
2630      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2631                                         ConvertedType, IncompatibleObjC)) {
2632        if (IncompatibleObjC)
2633          return false;
2634        // Okay, we have an Objective-C pointer conversion.
2635      } else
2636        // Argument types are too different. Abort.
2637        return false;
2638    }
2639    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2640                                                         ToFunctionType))
2641      return false;
2642 
2643    ConvertedType = ToType;
2644    return true;
2645 }
2646 
2647 enum {
2648   ft_default,
2649   ft_different_class,
2650   ft_parameter_arity,
2651   ft_parameter_mismatch,
2652   ft_return_type,
2653   ft_qualifer_mismatch,
2654   ft_noexcept
2655 };
2656 
2657 /// Attempts to get the FunctionProtoType from a Type. Handles
2658 /// MemberFunctionPointers properly.
2659 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2660   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2661     return FPT;
2662 
2663   if (auto *MPT = FromType->getAs<MemberPointerType>())
2664     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2665 
2666   return nullptr;
2667 }
2668 
2669 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2670 /// function types.  Catches different number of parameter, mismatch in
2671 /// parameter types, and different return types.
2672 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2673                                       QualType FromType, QualType ToType) {
2674   // If either type is not valid, include no extra info.
2675   if (FromType.isNull() || ToType.isNull()) {
2676     PDiag << ft_default;
2677     return;
2678   }
2679 
2680   // Get the function type from the pointers.
2681   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2682     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2683                             *ToMember = ToType->getAs<MemberPointerType>();
2684     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2685       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2686             << QualType(FromMember->getClass(), 0);
2687       return;
2688     }
2689     FromType = FromMember->getPointeeType();
2690     ToType = ToMember->getPointeeType();
2691   }
2692 
2693   if (FromType->isPointerType())
2694     FromType = FromType->getPointeeType();
2695   if (ToType->isPointerType())
2696     ToType = ToType->getPointeeType();
2697 
2698   // Remove references.
2699   FromType = FromType.getNonReferenceType();
2700   ToType = ToType.getNonReferenceType();
2701 
2702   // Don't print extra info for non-specialized template functions.
2703   if (FromType->isInstantiationDependentType() &&
2704       !FromType->getAs<TemplateSpecializationType>()) {
2705     PDiag << ft_default;
2706     return;
2707   }
2708 
2709   // No extra info for same types.
2710   if (Context.hasSameType(FromType, ToType)) {
2711     PDiag << ft_default;
2712     return;
2713   }
2714 
2715   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2716                           *ToFunction = tryGetFunctionProtoType(ToType);
2717 
2718   // Both types need to be function types.
2719   if (!FromFunction || !ToFunction) {
2720     PDiag << ft_default;
2721     return;
2722   }
2723 
2724   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2725     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2726           << FromFunction->getNumParams();
2727     return;
2728   }
2729 
2730   // Handle different parameter types.
2731   unsigned ArgPos;
2732   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2733     PDiag << ft_parameter_mismatch << ArgPos + 1
2734           << ToFunction->getParamType(ArgPos)
2735           << FromFunction->getParamType(ArgPos);
2736     return;
2737   }
2738 
2739   // Handle different return type.
2740   if (!Context.hasSameType(FromFunction->getReturnType(),
2741                            ToFunction->getReturnType())) {
2742     PDiag << ft_return_type << ToFunction->getReturnType()
2743           << FromFunction->getReturnType();
2744     return;
2745   }
2746 
2747   unsigned FromQuals = FromFunction->getTypeQuals(),
2748            ToQuals = ToFunction->getTypeQuals();
2749   if (FromQuals != ToQuals) {
2750     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2751     return;
2752   }
2753 
2754   // Handle exception specification differences on canonical type (in C++17
2755   // onwards).
2756   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2757           ->isNothrow(Context) !=
2758       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2759           ->isNothrow(Context)) {
2760     PDiag << ft_noexcept;
2761     return;
2762   }
2763 
2764   // Unable to find a difference, so add no extra info.
2765   PDiag << ft_default;
2766 }
2767 
2768 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2769 /// for equality of their argument types. Caller has already checked that
2770 /// they have same number of arguments.  If the parameters are different,
2771 /// ArgPos will have the parameter index of the first different parameter.
2772 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2773                                       const FunctionProtoType *NewType,
2774                                       unsigned *ArgPos) {
2775   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2776                                               N = NewType->param_type_begin(),
2777                                               E = OldType->param_type_end();
2778        O && (O != E); ++O, ++N) {
2779     if (!Context.hasSameType(O->getUnqualifiedType(),
2780                              N->getUnqualifiedType())) {
2781       if (ArgPos)
2782         *ArgPos = O - OldType->param_type_begin();
2783       return false;
2784     }
2785   }
2786   return true;
2787 }
2788 
2789 /// CheckPointerConversion - Check the pointer conversion from the
2790 /// expression From to the type ToType. This routine checks for
2791 /// ambiguous or inaccessible derived-to-base pointer
2792 /// conversions for which IsPointerConversion has already returned
2793 /// true. It returns true and produces a diagnostic if there was an
2794 /// error, or returns false otherwise.
2795 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2796                                   CastKind &Kind,
2797                                   CXXCastPath& BasePath,
2798                                   bool IgnoreBaseAccess,
2799                                   bool Diagnose) {
2800   QualType FromType = From->getType();
2801   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2802 
2803   Kind = CK_BitCast;
2804 
2805   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2806       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2807           Expr::NPCK_ZeroExpression) {
2808     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2809       DiagRuntimeBehavior(From->getExprLoc(), From,
2810                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2811                             << ToType << From->getSourceRange());
2812     else if (!isUnevaluatedContext())
2813       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2814         << ToType << From->getSourceRange();
2815   }
2816   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2817     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2818       QualType FromPointeeType = FromPtrType->getPointeeType(),
2819                ToPointeeType   = ToPtrType->getPointeeType();
2820 
2821       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2822           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2823         // We must have a derived-to-base conversion. Check an
2824         // ambiguous or inaccessible conversion.
2825         unsigned InaccessibleID = 0;
2826         unsigned AmbigiousID = 0;
2827         if (Diagnose) {
2828           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2829           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2830         }
2831         if (CheckDerivedToBaseConversion(
2832                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2833                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2834                 &BasePath, IgnoreBaseAccess))
2835           return true;
2836 
2837         // The conversion was successful.
2838         Kind = CK_DerivedToBase;
2839       }
2840 
2841       if (Diagnose && !IsCStyleOrFunctionalCast &&
2842           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2843         assert(getLangOpts().MSVCCompat &&
2844                "this should only be possible with MSVCCompat!");
2845         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2846             << From->getSourceRange();
2847       }
2848     }
2849   } else if (const ObjCObjectPointerType *ToPtrType =
2850                ToType->getAs<ObjCObjectPointerType>()) {
2851     if (const ObjCObjectPointerType *FromPtrType =
2852           FromType->getAs<ObjCObjectPointerType>()) {
2853       // Objective-C++ conversions are always okay.
2854       // FIXME: We should have a different class of conversions for the
2855       // Objective-C++ implicit conversions.
2856       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2857         return false;
2858     } else if (FromType->isBlockPointerType()) {
2859       Kind = CK_BlockPointerToObjCPointerCast;
2860     } else {
2861       Kind = CK_CPointerToObjCPointerCast;
2862     }
2863   } else if (ToType->isBlockPointerType()) {
2864     if (!FromType->isBlockPointerType())
2865       Kind = CK_AnyPointerToBlockPointerCast;
2866   }
2867 
2868   // We shouldn't fall into this case unless it's valid for other
2869   // reasons.
2870   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2871     Kind = CK_NullToPointer;
2872 
2873   return false;
2874 }
2875 
2876 /// IsMemberPointerConversion - Determines whether the conversion of the
2877 /// expression From, which has the (possibly adjusted) type FromType, can be
2878 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2879 /// If so, returns true and places the converted type (that might differ from
2880 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2881 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2882                                      QualType ToType,
2883                                      bool InOverloadResolution,
2884                                      QualType &ConvertedType) {
2885   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2886   if (!ToTypePtr)
2887     return false;
2888 
2889   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2890   if (From->isNullPointerConstant(Context,
2891                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2892                                         : Expr::NPC_ValueDependentIsNull)) {
2893     ConvertedType = ToType;
2894     return true;
2895   }
2896 
2897   // Otherwise, both types have to be member pointers.
2898   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2899   if (!FromTypePtr)
2900     return false;
2901 
2902   // A pointer to member of B can be converted to a pointer to member of D,
2903   // where D is derived from B (C++ 4.11p2).
2904   QualType FromClass(FromTypePtr->getClass(), 0);
2905   QualType ToClass(ToTypePtr->getClass(), 0);
2906 
2907   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2908       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2909     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2910                                                  ToClass.getTypePtr());
2911     return true;
2912   }
2913 
2914   return false;
2915 }
2916 
2917 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2918 /// expression From to the type ToType. This routine checks for ambiguous or
2919 /// virtual or inaccessible base-to-derived member pointer conversions
2920 /// for which IsMemberPointerConversion has already returned true. It returns
2921 /// true and produces a diagnostic if there was an error, or returns false
2922 /// otherwise.
2923 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2924                                         CastKind &Kind,
2925                                         CXXCastPath &BasePath,
2926                                         bool IgnoreBaseAccess) {
2927   QualType FromType = From->getType();
2928   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2929   if (!FromPtrType) {
2930     // This must be a null pointer to member pointer conversion
2931     assert(From->isNullPointerConstant(Context,
2932                                        Expr::NPC_ValueDependentIsNull) &&
2933            "Expr must be null pointer constant!");
2934     Kind = CK_NullToMemberPointer;
2935     return false;
2936   }
2937 
2938   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2939   assert(ToPtrType && "No member pointer cast has a target type "
2940                       "that is not a member pointer.");
2941 
2942   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2943   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2944 
2945   // FIXME: What about dependent types?
2946   assert(FromClass->isRecordType() && "Pointer into non-class.");
2947   assert(ToClass->isRecordType() && "Pointer into non-class.");
2948 
2949   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2950                      /*DetectVirtual=*/true);
2951   bool DerivationOkay =
2952       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2953   assert(DerivationOkay &&
2954          "Should not have been called if derivation isn't OK.");
2955   (void)DerivationOkay;
2956 
2957   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2958                                   getUnqualifiedType())) {
2959     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2960     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2961       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2962     return true;
2963   }
2964 
2965   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2966     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2967       << FromClass << ToClass << QualType(VBase, 0)
2968       << From->getSourceRange();
2969     return true;
2970   }
2971 
2972   if (!IgnoreBaseAccess)
2973     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2974                          Paths.front(),
2975                          diag::err_downcast_from_inaccessible_base);
2976 
2977   // Must be a base to derived member conversion.
2978   BuildBasePathArray(Paths, BasePath);
2979   Kind = CK_BaseToDerivedMemberPointer;
2980   return false;
2981 }
2982 
2983 /// Determine whether the lifetime conversion between the two given
2984 /// qualifiers sets is nontrivial.
2985 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2986                                                Qualifiers ToQuals) {
2987   // Converting anything to const __unsafe_unretained is trivial.
2988   if (ToQuals.hasConst() &&
2989       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2990     return false;
2991 
2992   return true;
2993 }
2994 
2995 /// IsQualificationConversion - Determines whether the conversion from
2996 /// an rvalue of type FromType to ToType is a qualification conversion
2997 /// (C++ 4.4).
2998 ///
2999 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3000 /// when the qualification conversion involves a change in the Objective-C
3001 /// object lifetime.
3002 bool
3003 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3004                                 bool CStyle, bool &ObjCLifetimeConversion) {
3005   FromType = Context.getCanonicalType(FromType);
3006   ToType = Context.getCanonicalType(ToType);
3007   ObjCLifetimeConversion = false;
3008 
3009   // If FromType and ToType are the same type, this is not a
3010   // qualification conversion.
3011   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3012     return false;
3013 
3014   // (C++ 4.4p4):
3015   //   A conversion can add cv-qualifiers at levels other than the first
3016   //   in multi-level pointers, subject to the following rules: [...]
3017   bool PreviousToQualsIncludeConst = true;
3018   bool UnwrappedAnyPointer = false;
3019   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3020     // Within each iteration of the loop, we check the qualifiers to
3021     // determine if this still looks like a qualification
3022     // conversion. Then, if all is well, we unwrap one more level of
3023     // pointers or pointers-to-members and do it all again
3024     // until there are no more pointers or pointers-to-members left to
3025     // unwrap.
3026     UnwrappedAnyPointer = true;
3027 
3028     Qualifiers FromQuals = FromType.getQualifiers();
3029     Qualifiers ToQuals = ToType.getQualifiers();
3030 
3031     // Ignore __unaligned qualifier if this type is void.
3032     if (ToType.getUnqualifiedType()->isVoidType())
3033       FromQuals.removeUnaligned();
3034 
3035     // Objective-C ARC:
3036     //   Check Objective-C lifetime conversions.
3037     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3038         UnwrappedAnyPointer) {
3039       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3040         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3041           ObjCLifetimeConversion = true;
3042         FromQuals.removeObjCLifetime();
3043         ToQuals.removeObjCLifetime();
3044       } else {
3045         // Qualification conversions cannot cast between different
3046         // Objective-C lifetime qualifiers.
3047         return false;
3048       }
3049     }
3050 
3051     // Allow addition/removal of GC attributes but not changing GC attributes.
3052     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3053         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3054       FromQuals.removeObjCGCAttr();
3055       ToQuals.removeObjCGCAttr();
3056     }
3057 
3058     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3059     //      2,j, and similarly for volatile.
3060     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3061       return false;
3062 
3063     //   -- if the cv 1,j and cv 2,j are different, then const is in
3064     //      every cv for 0 < k < j.
3065     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3066         && !PreviousToQualsIncludeConst)
3067       return false;
3068 
3069     // Keep track of whether all prior cv-qualifiers in the "to" type
3070     // include const.
3071     PreviousToQualsIncludeConst
3072       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3073   }
3074 
3075   // We are left with FromType and ToType being the pointee types
3076   // after unwrapping the original FromType and ToType the same number
3077   // of types. If we unwrapped any pointers, and if FromType and
3078   // ToType have the same unqualified type (since we checked
3079   // qualifiers above), then this is a qualification conversion.
3080   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3081 }
3082 
3083 /// \brief - Determine whether this is a conversion from a scalar type to an
3084 /// atomic type.
3085 ///
3086 /// If successful, updates \c SCS's second and third steps in the conversion
3087 /// sequence to finish the conversion.
3088 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3089                                 bool InOverloadResolution,
3090                                 StandardConversionSequence &SCS,
3091                                 bool CStyle) {
3092   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3093   if (!ToAtomic)
3094     return false;
3095 
3096   StandardConversionSequence InnerSCS;
3097   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3098                             InOverloadResolution, InnerSCS,
3099                             CStyle, /*AllowObjCWritebackConversion=*/false))
3100     return false;
3101 
3102   SCS.Second = InnerSCS.Second;
3103   SCS.setToType(1, InnerSCS.getToType(1));
3104   SCS.Third = InnerSCS.Third;
3105   SCS.QualificationIncludesObjCLifetime
3106     = InnerSCS.QualificationIncludesObjCLifetime;
3107   SCS.setToType(2, InnerSCS.getToType(2));
3108   return true;
3109 }
3110 
3111 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3112                                               CXXConstructorDecl *Constructor,
3113                                               QualType Type) {
3114   const FunctionProtoType *CtorType =
3115       Constructor->getType()->getAs<FunctionProtoType>();
3116   if (CtorType->getNumParams() > 0) {
3117     QualType FirstArg = CtorType->getParamType(0);
3118     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3119       return true;
3120   }
3121   return false;
3122 }
3123 
3124 static OverloadingResult
3125 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3126                                        CXXRecordDecl *To,
3127                                        UserDefinedConversionSequence &User,
3128                                        OverloadCandidateSet &CandidateSet,
3129                                        bool AllowExplicit) {
3130   for (auto *D : S.LookupConstructors(To)) {
3131     auto Info = getConstructorInfo(D);
3132     if (!Info)
3133       continue;
3134 
3135     bool Usable = !Info.Constructor->isInvalidDecl() &&
3136                   S.isInitListConstructor(Info.Constructor) &&
3137                   (AllowExplicit || !Info.Constructor->isExplicit());
3138     if (Usable) {
3139       // If the first argument is (a reference to) the target type,
3140       // suppress conversions.
3141       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3142           S.Context, Info.Constructor, ToType);
3143       if (Info.ConstructorTmpl)
3144         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3145                                        /*ExplicitArgs*/ nullptr, From,
3146                                        CandidateSet, SuppressUserConversions);
3147       else
3148         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3149                                CandidateSet, SuppressUserConversions);
3150     }
3151   }
3152 
3153   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3154 
3155   OverloadCandidateSet::iterator Best;
3156   switch (auto Result =
3157             CandidateSet.BestViableFunction(S, From->getLocStart(),
3158                                             Best, true)) {
3159   case OR_Deleted:
3160   case OR_Success: {
3161     // Record the standard conversion we used and the conversion function.
3162     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3163     QualType ThisType = Constructor->getThisType(S.Context);
3164     // Initializer lists don't have conversions as such.
3165     User.Before.setAsIdentityConversion();
3166     User.HadMultipleCandidates = HadMultipleCandidates;
3167     User.ConversionFunction = Constructor;
3168     User.FoundConversionFunction = Best->FoundDecl;
3169     User.After.setAsIdentityConversion();
3170     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3171     User.After.setAllToTypes(ToType);
3172     return Result;
3173   }
3174 
3175   case OR_No_Viable_Function:
3176     return OR_No_Viable_Function;
3177   case OR_Ambiguous:
3178     return OR_Ambiguous;
3179   }
3180 
3181   llvm_unreachable("Invalid OverloadResult!");
3182 }
3183 
3184 /// Determines whether there is a user-defined conversion sequence
3185 /// (C++ [over.ics.user]) that converts expression From to the type
3186 /// ToType. If such a conversion exists, User will contain the
3187 /// user-defined conversion sequence that performs such a conversion
3188 /// and this routine will return true. Otherwise, this routine returns
3189 /// false and User is unspecified.
3190 ///
3191 /// \param AllowExplicit  true if the conversion should consider C++0x
3192 /// "explicit" conversion functions as well as non-explicit conversion
3193 /// functions (C++0x [class.conv.fct]p2).
3194 ///
3195 /// \param AllowObjCConversionOnExplicit true if the conversion should
3196 /// allow an extra Objective-C pointer conversion on uses of explicit
3197 /// constructors. Requires \c AllowExplicit to also be set.
3198 static OverloadingResult
3199 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3200                         UserDefinedConversionSequence &User,
3201                         OverloadCandidateSet &CandidateSet,
3202                         bool AllowExplicit,
3203                         bool AllowObjCConversionOnExplicit) {
3204   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3205 
3206   // Whether we will only visit constructors.
3207   bool ConstructorsOnly = false;
3208 
3209   // If the type we are conversion to is a class type, enumerate its
3210   // constructors.
3211   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3212     // C++ [over.match.ctor]p1:
3213     //   When objects of class type are direct-initialized (8.5), or
3214     //   copy-initialized from an expression of the same or a
3215     //   derived class type (8.5), overload resolution selects the
3216     //   constructor. [...] For copy-initialization, the candidate
3217     //   functions are all the converting constructors (12.3.1) of
3218     //   that class. The argument list is the expression-list within
3219     //   the parentheses of the initializer.
3220     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3221         (From->getType()->getAs<RecordType>() &&
3222          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3223       ConstructorsOnly = true;
3224 
3225     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3226       // We're not going to find any constructors.
3227     } else if (CXXRecordDecl *ToRecordDecl
3228                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3229 
3230       Expr **Args = &From;
3231       unsigned NumArgs = 1;
3232       bool ListInitializing = false;
3233       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3234         // But first, see if there is an init-list-constructor that will work.
3235         OverloadingResult Result = IsInitializerListConstructorConversion(
3236             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3237         if (Result != OR_No_Viable_Function)
3238           return Result;
3239         // Never mind.
3240         CandidateSet.clear();
3241 
3242         // If we're list-initializing, we pass the individual elements as
3243         // arguments, not the entire list.
3244         Args = InitList->getInits();
3245         NumArgs = InitList->getNumInits();
3246         ListInitializing = true;
3247       }
3248 
3249       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3250         auto Info = getConstructorInfo(D);
3251         if (!Info)
3252           continue;
3253 
3254         bool Usable = !Info.Constructor->isInvalidDecl();
3255         if (ListInitializing)
3256           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3257         else
3258           Usable = Usable &&
3259                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3260         if (Usable) {
3261           bool SuppressUserConversions = !ConstructorsOnly;
3262           if (SuppressUserConversions && ListInitializing) {
3263             SuppressUserConversions = false;
3264             if (NumArgs == 1) {
3265               // If the first argument is (a reference to) the target type,
3266               // suppress conversions.
3267               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3268                   S.Context, Info.Constructor, ToType);
3269             }
3270           }
3271           if (Info.ConstructorTmpl)
3272             S.AddTemplateOverloadCandidate(
3273                 Info.ConstructorTmpl, Info.FoundDecl,
3274                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3275                 CandidateSet, SuppressUserConversions);
3276           else
3277             // Allow one user-defined conversion when user specifies a
3278             // From->ToType conversion via an static cast (c-style, etc).
3279             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3280                                    llvm::makeArrayRef(Args, NumArgs),
3281                                    CandidateSet, SuppressUserConversions);
3282         }
3283       }
3284     }
3285   }
3286 
3287   // Enumerate conversion functions, if we're allowed to.
3288   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3289   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3290     // No conversion functions from incomplete types.
3291   } else if (const RecordType *FromRecordType
3292                                    = From->getType()->getAs<RecordType>()) {
3293     if (CXXRecordDecl *FromRecordDecl
3294          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3295       // Add all of the conversion functions as candidates.
3296       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3297       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3298         DeclAccessPair FoundDecl = I.getPair();
3299         NamedDecl *D = FoundDecl.getDecl();
3300         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3301         if (isa<UsingShadowDecl>(D))
3302           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3303 
3304         CXXConversionDecl *Conv;
3305         FunctionTemplateDecl *ConvTemplate;
3306         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3307           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3308         else
3309           Conv = cast<CXXConversionDecl>(D);
3310 
3311         if (AllowExplicit || !Conv->isExplicit()) {
3312           if (ConvTemplate)
3313             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3314                                              ActingContext, From, ToType,
3315                                              CandidateSet,
3316                                              AllowObjCConversionOnExplicit);
3317           else
3318             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3319                                      From, ToType, CandidateSet,
3320                                      AllowObjCConversionOnExplicit);
3321         }
3322       }
3323     }
3324   }
3325 
3326   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3327 
3328   OverloadCandidateSet::iterator Best;
3329   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3330                                                         Best, true)) {
3331   case OR_Success:
3332   case OR_Deleted:
3333     // Record the standard conversion we used and the conversion function.
3334     if (CXXConstructorDecl *Constructor
3335           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3336       // C++ [over.ics.user]p1:
3337       //   If the user-defined conversion is specified by a
3338       //   constructor (12.3.1), the initial standard conversion
3339       //   sequence converts the source type to the type required by
3340       //   the argument of the constructor.
3341       //
3342       QualType ThisType = Constructor->getThisType(S.Context);
3343       if (isa<InitListExpr>(From)) {
3344         // Initializer lists don't have conversions as such.
3345         User.Before.setAsIdentityConversion();
3346       } else {
3347         if (Best->Conversions[0].isEllipsis())
3348           User.EllipsisConversion = true;
3349         else {
3350           User.Before = Best->Conversions[0].Standard;
3351           User.EllipsisConversion = false;
3352         }
3353       }
3354       User.HadMultipleCandidates = HadMultipleCandidates;
3355       User.ConversionFunction = Constructor;
3356       User.FoundConversionFunction = Best->FoundDecl;
3357       User.After.setAsIdentityConversion();
3358       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3359       User.After.setAllToTypes(ToType);
3360       return Result;
3361     }
3362     if (CXXConversionDecl *Conversion
3363                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3364       // C++ [over.ics.user]p1:
3365       //
3366       //   [...] If the user-defined conversion is specified by a
3367       //   conversion function (12.3.2), the initial standard
3368       //   conversion sequence converts the source type to the
3369       //   implicit object parameter of the conversion function.
3370       User.Before = Best->Conversions[0].Standard;
3371       User.HadMultipleCandidates = HadMultipleCandidates;
3372       User.ConversionFunction = Conversion;
3373       User.FoundConversionFunction = Best->FoundDecl;
3374       User.EllipsisConversion = false;
3375 
3376       // C++ [over.ics.user]p2:
3377       //   The second standard conversion sequence converts the
3378       //   result of the user-defined conversion to the target type
3379       //   for the sequence. Since an implicit conversion sequence
3380       //   is an initialization, the special rules for
3381       //   initialization by user-defined conversion apply when
3382       //   selecting the best user-defined conversion for a
3383       //   user-defined conversion sequence (see 13.3.3 and
3384       //   13.3.3.1).
3385       User.After = Best->FinalConversion;
3386       return Result;
3387     }
3388     llvm_unreachable("Not a constructor or conversion function?");
3389 
3390   case OR_No_Viable_Function:
3391     return OR_No_Viable_Function;
3392 
3393   case OR_Ambiguous:
3394     return OR_Ambiguous;
3395   }
3396 
3397   llvm_unreachable("Invalid OverloadResult!");
3398 }
3399 
3400 bool
3401 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3402   ImplicitConversionSequence ICS;
3403   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3404                                     OverloadCandidateSet::CSK_Normal);
3405   OverloadingResult OvResult =
3406     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3407                             CandidateSet, false, false);
3408   if (OvResult == OR_Ambiguous)
3409     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3410         << From->getType() << ToType << From->getSourceRange();
3411   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3412     if (!RequireCompleteType(From->getLocStart(), ToType,
3413                              diag::err_typecheck_nonviable_condition_incomplete,
3414                              From->getType(), From->getSourceRange()))
3415       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3416           << false << From->getType() << From->getSourceRange() << ToType;
3417   } else
3418     return false;
3419   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3420   return true;
3421 }
3422 
3423 /// \brief Compare the user-defined conversion functions or constructors
3424 /// of two user-defined conversion sequences to determine whether any ordering
3425 /// is possible.
3426 static ImplicitConversionSequence::CompareKind
3427 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3428                            FunctionDecl *Function2) {
3429   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3430     return ImplicitConversionSequence::Indistinguishable;
3431 
3432   // Objective-C++:
3433   //   If both conversion functions are implicitly-declared conversions from
3434   //   a lambda closure type to a function pointer and a block pointer,
3435   //   respectively, always prefer the conversion to a function pointer,
3436   //   because the function pointer is more lightweight and is more likely
3437   //   to keep code working.
3438   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3439   if (!Conv1)
3440     return ImplicitConversionSequence::Indistinguishable;
3441 
3442   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3443   if (!Conv2)
3444     return ImplicitConversionSequence::Indistinguishable;
3445 
3446   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3447     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3448     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3449     if (Block1 != Block2)
3450       return Block1 ? ImplicitConversionSequence::Worse
3451                     : ImplicitConversionSequence::Better;
3452   }
3453 
3454   return ImplicitConversionSequence::Indistinguishable;
3455 }
3456 
3457 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3458     const ImplicitConversionSequence &ICS) {
3459   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3460          (ICS.isUserDefined() &&
3461           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3462 }
3463 
3464 /// CompareImplicitConversionSequences - Compare two implicit
3465 /// conversion sequences to determine whether one is better than the
3466 /// other or if they are indistinguishable (C++ 13.3.3.2).
3467 static ImplicitConversionSequence::CompareKind
3468 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3469                                    const ImplicitConversionSequence& ICS1,
3470                                    const ImplicitConversionSequence& ICS2)
3471 {
3472   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3473   // conversion sequences (as defined in 13.3.3.1)
3474   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3475   //      conversion sequence than a user-defined conversion sequence or
3476   //      an ellipsis conversion sequence, and
3477   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3478   //      conversion sequence than an ellipsis conversion sequence
3479   //      (13.3.3.1.3).
3480   //
3481   // C++0x [over.best.ics]p10:
3482   //   For the purpose of ranking implicit conversion sequences as
3483   //   described in 13.3.3.2, the ambiguous conversion sequence is
3484   //   treated as a user-defined sequence that is indistinguishable
3485   //   from any other user-defined conversion sequence.
3486 
3487   // String literal to 'char *' conversion has been deprecated in C++03. It has
3488   // been removed from C++11. We still accept this conversion, if it happens at
3489   // the best viable function. Otherwise, this conversion is considered worse
3490   // than ellipsis conversion. Consider this as an extension; this is not in the
3491   // standard. For example:
3492   //
3493   // int &f(...);    // #1
3494   // void f(char*);  // #2
3495   // void g() { int &r = f("foo"); }
3496   //
3497   // In C++03, we pick #2 as the best viable function.
3498   // In C++11, we pick #1 as the best viable function, because ellipsis
3499   // conversion is better than string-literal to char* conversion (since there
3500   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3501   // convert arguments, #2 would be the best viable function in C++11.
3502   // If the best viable function has this conversion, a warning will be issued
3503   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3504 
3505   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3506       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3507       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3508     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3509                ? ImplicitConversionSequence::Worse
3510                : ImplicitConversionSequence::Better;
3511 
3512   if (ICS1.getKindRank() < ICS2.getKindRank())
3513     return ImplicitConversionSequence::Better;
3514   if (ICS2.getKindRank() < ICS1.getKindRank())
3515     return ImplicitConversionSequence::Worse;
3516 
3517   // The following checks require both conversion sequences to be of
3518   // the same kind.
3519   if (ICS1.getKind() != ICS2.getKind())
3520     return ImplicitConversionSequence::Indistinguishable;
3521 
3522   ImplicitConversionSequence::CompareKind Result =
3523       ImplicitConversionSequence::Indistinguishable;
3524 
3525   // Two implicit conversion sequences of the same form are
3526   // indistinguishable conversion sequences unless one of the
3527   // following rules apply: (C++ 13.3.3.2p3):
3528 
3529   // List-initialization sequence L1 is a better conversion sequence than
3530   // list-initialization sequence L2 if:
3531   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3532   //   if not that,
3533   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3534   //   and N1 is smaller than N2.,
3535   // even if one of the other rules in this paragraph would otherwise apply.
3536   if (!ICS1.isBad()) {
3537     if (ICS1.isStdInitializerListElement() &&
3538         !ICS2.isStdInitializerListElement())
3539       return ImplicitConversionSequence::Better;
3540     if (!ICS1.isStdInitializerListElement() &&
3541         ICS2.isStdInitializerListElement())
3542       return ImplicitConversionSequence::Worse;
3543   }
3544 
3545   if (ICS1.isStandard())
3546     // Standard conversion sequence S1 is a better conversion sequence than
3547     // standard conversion sequence S2 if [...]
3548     Result = CompareStandardConversionSequences(S, Loc,
3549                                                 ICS1.Standard, ICS2.Standard);
3550   else if (ICS1.isUserDefined()) {
3551     // User-defined conversion sequence U1 is a better conversion
3552     // sequence than another user-defined conversion sequence U2 if
3553     // they contain the same user-defined conversion function or
3554     // constructor and if the second standard conversion sequence of
3555     // U1 is better than the second standard conversion sequence of
3556     // U2 (C++ 13.3.3.2p3).
3557     if (ICS1.UserDefined.ConversionFunction ==
3558           ICS2.UserDefined.ConversionFunction)
3559       Result = CompareStandardConversionSequences(S, Loc,
3560                                                   ICS1.UserDefined.After,
3561                                                   ICS2.UserDefined.After);
3562     else
3563       Result = compareConversionFunctions(S,
3564                                           ICS1.UserDefined.ConversionFunction,
3565                                           ICS2.UserDefined.ConversionFunction);
3566   }
3567 
3568   return Result;
3569 }
3570 
3571 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3572   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3573     Qualifiers Quals;
3574     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3575     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3576   }
3577 
3578   return Context.hasSameUnqualifiedType(T1, T2);
3579 }
3580 
3581 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3582 // determine if one is a proper subset of the other.
3583 static ImplicitConversionSequence::CompareKind
3584 compareStandardConversionSubsets(ASTContext &Context,
3585                                  const StandardConversionSequence& SCS1,
3586                                  const StandardConversionSequence& SCS2) {
3587   ImplicitConversionSequence::CompareKind Result
3588     = ImplicitConversionSequence::Indistinguishable;
3589 
3590   // the identity conversion sequence is considered to be a subsequence of
3591   // any non-identity conversion sequence
3592   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3593     return ImplicitConversionSequence::Better;
3594   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3595     return ImplicitConversionSequence::Worse;
3596 
3597   if (SCS1.Second != SCS2.Second) {
3598     if (SCS1.Second == ICK_Identity)
3599       Result = ImplicitConversionSequence::Better;
3600     else if (SCS2.Second == ICK_Identity)
3601       Result = ImplicitConversionSequence::Worse;
3602     else
3603       return ImplicitConversionSequence::Indistinguishable;
3604   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3605     return ImplicitConversionSequence::Indistinguishable;
3606 
3607   if (SCS1.Third == SCS2.Third) {
3608     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3609                              : ImplicitConversionSequence::Indistinguishable;
3610   }
3611 
3612   if (SCS1.Third == ICK_Identity)
3613     return Result == ImplicitConversionSequence::Worse
3614              ? ImplicitConversionSequence::Indistinguishable
3615              : ImplicitConversionSequence::Better;
3616 
3617   if (SCS2.Third == ICK_Identity)
3618     return Result == ImplicitConversionSequence::Better
3619              ? ImplicitConversionSequence::Indistinguishable
3620              : ImplicitConversionSequence::Worse;
3621 
3622   return ImplicitConversionSequence::Indistinguishable;
3623 }
3624 
3625 /// \brief Determine whether one of the given reference bindings is better
3626 /// than the other based on what kind of bindings they are.
3627 static bool
3628 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3629                              const StandardConversionSequence &SCS2) {
3630   // C++0x [over.ics.rank]p3b4:
3631   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3632   //      implicit object parameter of a non-static member function declared
3633   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3634   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3635   //      lvalue reference to a function lvalue and S2 binds an rvalue
3636   //      reference*.
3637   //
3638   // FIXME: Rvalue references. We're going rogue with the above edits,
3639   // because the semantics in the current C++0x working paper (N3225 at the
3640   // time of this writing) break the standard definition of std::forward
3641   // and std::reference_wrapper when dealing with references to functions.
3642   // Proposed wording changes submitted to CWG for consideration.
3643   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3644       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3645     return false;
3646 
3647   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3648           SCS2.IsLvalueReference) ||
3649          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3650           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3651 }
3652 
3653 /// CompareStandardConversionSequences - Compare two standard
3654 /// conversion sequences to determine whether one is better than the
3655 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3656 static ImplicitConversionSequence::CompareKind
3657 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3658                                    const StandardConversionSequence& SCS1,
3659                                    const StandardConversionSequence& SCS2)
3660 {
3661   // Standard conversion sequence S1 is a better conversion sequence
3662   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3663 
3664   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3665   //     sequences in the canonical form defined by 13.3.3.1.1,
3666   //     excluding any Lvalue Transformation; the identity conversion
3667   //     sequence is considered to be a subsequence of any
3668   //     non-identity conversion sequence) or, if not that,
3669   if (ImplicitConversionSequence::CompareKind CK
3670         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3671     return CK;
3672 
3673   //  -- the rank of S1 is better than the rank of S2 (by the rules
3674   //     defined below), or, if not that,
3675   ImplicitConversionRank Rank1 = SCS1.getRank();
3676   ImplicitConversionRank Rank2 = SCS2.getRank();
3677   if (Rank1 < Rank2)
3678     return ImplicitConversionSequence::Better;
3679   else if (Rank2 < Rank1)
3680     return ImplicitConversionSequence::Worse;
3681 
3682   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3683   // are indistinguishable unless one of the following rules
3684   // applies:
3685 
3686   //   A conversion that is not a conversion of a pointer, or
3687   //   pointer to member, to bool is better than another conversion
3688   //   that is such a conversion.
3689   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3690     return SCS2.isPointerConversionToBool()
3691              ? ImplicitConversionSequence::Better
3692              : ImplicitConversionSequence::Worse;
3693 
3694   // C++ [over.ics.rank]p4b2:
3695   //
3696   //   If class B is derived directly or indirectly from class A,
3697   //   conversion of B* to A* is better than conversion of B* to
3698   //   void*, and conversion of A* to void* is better than conversion
3699   //   of B* to void*.
3700   bool SCS1ConvertsToVoid
3701     = SCS1.isPointerConversionToVoidPointer(S.Context);
3702   bool SCS2ConvertsToVoid
3703     = SCS2.isPointerConversionToVoidPointer(S.Context);
3704   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3705     // Exactly one of the conversion sequences is a conversion to
3706     // a void pointer; it's the worse conversion.
3707     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3708                               : ImplicitConversionSequence::Worse;
3709   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3710     // Neither conversion sequence converts to a void pointer; compare
3711     // their derived-to-base conversions.
3712     if (ImplicitConversionSequence::CompareKind DerivedCK
3713           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3714       return DerivedCK;
3715   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3716              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3717     // Both conversion sequences are conversions to void
3718     // pointers. Compare the source types to determine if there's an
3719     // inheritance relationship in their sources.
3720     QualType FromType1 = SCS1.getFromType();
3721     QualType FromType2 = SCS2.getFromType();
3722 
3723     // Adjust the types we're converting from via the array-to-pointer
3724     // conversion, if we need to.
3725     if (SCS1.First == ICK_Array_To_Pointer)
3726       FromType1 = S.Context.getArrayDecayedType(FromType1);
3727     if (SCS2.First == ICK_Array_To_Pointer)
3728       FromType2 = S.Context.getArrayDecayedType(FromType2);
3729 
3730     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3731     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3732 
3733     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3734       return ImplicitConversionSequence::Better;
3735     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3736       return ImplicitConversionSequence::Worse;
3737 
3738     // Objective-C++: If one interface is more specific than the
3739     // other, it is the better one.
3740     const ObjCObjectPointerType* FromObjCPtr1
3741       = FromType1->getAs<ObjCObjectPointerType>();
3742     const ObjCObjectPointerType* FromObjCPtr2
3743       = FromType2->getAs<ObjCObjectPointerType>();
3744     if (FromObjCPtr1 && FromObjCPtr2) {
3745       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3746                                                           FromObjCPtr2);
3747       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3748                                                            FromObjCPtr1);
3749       if (AssignLeft != AssignRight) {
3750         return AssignLeft? ImplicitConversionSequence::Better
3751                          : ImplicitConversionSequence::Worse;
3752       }
3753     }
3754   }
3755 
3756   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3757   // bullet 3).
3758   if (ImplicitConversionSequence::CompareKind QualCK
3759         = CompareQualificationConversions(S, SCS1, SCS2))
3760     return QualCK;
3761 
3762   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3763     // Check for a better reference binding based on the kind of bindings.
3764     if (isBetterReferenceBindingKind(SCS1, SCS2))
3765       return ImplicitConversionSequence::Better;
3766     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3767       return ImplicitConversionSequence::Worse;
3768 
3769     // C++ [over.ics.rank]p3b4:
3770     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3771     //      which the references refer are the same type except for
3772     //      top-level cv-qualifiers, and the type to which the reference
3773     //      initialized by S2 refers is more cv-qualified than the type
3774     //      to which the reference initialized by S1 refers.
3775     QualType T1 = SCS1.getToType(2);
3776     QualType T2 = SCS2.getToType(2);
3777     T1 = S.Context.getCanonicalType(T1);
3778     T2 = S.Context.getCanonicalType(T2);
3779     Qualifiers T1Quals, T2Quals;
3780     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3781     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3782     if (UnqualT1 == UnqualT2) {
3783       // Objective-C++ ARC: If the references refer to objects with different
3784       // lifetimes, prefer bindings that don't change lifetime.
3785       if (SCS1.ObjCLifetimeConversionBinding !=
3786                                           SCS2.ObjCLifetimeConversionBinding) {
3787         return SCS1.ObjCLifetimeConversionBinding
3788                                            ? ImplicitConversionSequence::Worse
3789                                            : ImplicitConversionSequence::Better;
3790       }
3791 
3792       // If the type is an array type, promote the element qualifiers to the
3793       // type for comparison.
3794       if (isa<ArrayType>(T1) && T1Quals)
3795         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3796       if (isa<ArrayType>(T2) && T2Quals)
3797         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3798       if (T2.isMoreQualifiedThan(T1))
3799         return ImplicitConversionSequence::Better;
3800       else if (T1.isMoreQualifiedThan(T2))
3801         return ImplicitConversionSequence::Worse;
3802     }
3803   }
3804 
3805   // In Microsoft mode, prefer an integral conversion to a
3806   // floating-to-integral conversion if the integral conversion
3807   // is between types of the same size.
3808   // For example:
3809   // void f(float);
3810   // void f(int);
3811   // int main {
3812   //    long a;
3813   //    f(a);
3814   // }
3815   // Here, MSVC will call f(int) instead of generating a compile error
3816   // as clang will do in standard mode.
3817   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3818       SCS2.Second == ICK_Floating_Integral &&
3819       S.Context.getTypeSize(SCS1.getFromType()) ==
3820           S.Context.getTypeSize(SCS1.getToType(2)))
3821     return ImplicitConversionSequence::Better;
3822 
3823   return ImplicitConversionSequence::Indistinguishable;
3824 }
3825 
3826 /// CompareQualificationConversions - Compares two standard conversion
3827 /// sequences to determine whether they can be ranked based on their
3828 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3829 static ImplicitConversionSequence::CompareKind
3830 CompareQualificationConversions(Sema &S,
3831                                 const StandardConversionSequence& SCS1,
3832                                 const StandardConversionSequence& SCS2) {
3833   // C++ 13.3.3.2p3:
3834   //  -- S1 and S2 differ only in their qualification conversion and
3835   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3836   //     cv-qualification signature of type T1 is a proper subset of
3837   //     the cv-qualification signature of type T2, and S1 is not the
3838   //     deprecated string literal array-to-pointer conversion (4.2).
3839   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3840       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3841     return ImplicitConversionSequence::Indistinguishable;
3842 
3843   // FIXME: the example in the standard doesn't use a qualification
3844   // conversion (!)
3845   QualType T1 = SCS1.getToType(2);
3846   QualType T2 = SCS2.getToType(2);
3847   T1 = S.Context.getCanonicalType(T1);
3848   T2 = S.Context.getCanonicalType(T2);
3849   Qualifiers T1Quals, T2Quals;
3850   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3851   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3852 
3853   // If the types are the same, we won't learn anything by unwrapped
3854   // them.
3855   if (UnqualT1 == UnqualT2)
3856     return ImplicitConversionSequence::Indistinguishable;
3857 
3858   // If the type is an array type, promote the element qualifiers to the type
3859   // for comparison.
3860   if (isa<ArrayType>(T1) && T1Quals)
3861     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3862   if (isa<ArrayType>(T2) && T2Quals)
3863     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3864 
3865   ImplicitConversionSequence::CompareKind Result
3866     = ImplicitConversionSequence::Indistinguishable;
3867 
3868   // Objective-C++ ARC:
3869   //   Prefer qualification conversions not involving a change in lifetime
3870   //   to qualification conversions that do not change lifetime.
3871   if (SCS1.QualificationIncludesObjCLifetime !=
3872                                       SCS2.QualificationIncludesObjCLifetime) {
3873     Result = SCS1.QualificationIncludesObjCLifetime
3874                ? ImplicitConversionSequence::Worse
3875                : ImplicitConversionSequence::Better;
3876   }
3877 
3878   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3879     // Within each iteration of the loop, we check the qualifiers to
3880     // determine if this still looks like a qualification
3881     // conversion. Then, if all is well, we unwrap one more level of
3882     // pointers or pointers-to-members and do it all again
3883     // until there are no more pointers or pointers-to-members left
3884     // to unwrap. This essentially mimics what
3885     // IsQualificationConversion does, but here we're checking for a
3886     // strict subset of qualifiers.
3887     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3888       // The qualifiers are the same, so this doesn't tell us anything
3889       // about how the sequences rank.
3890       ;
3891     else if (T2.isMoreQualifiedThan(T1)) {
3892       // T1 has fewer qualifiers, so it could be the better sequence.
3893       if (Result == ImplicitConversionSequence::Worse)
3894         // Neither has qualifiers that are a subset of the other's
3895         // qualifiers.
3896         return ImplicitConversionSequence::Indistinguishable;
3897 
3898       Result = ImplicitConversionSequence::Better;
3899     } else if (T1.isMoreQualifiedThan(T2)) {
3900       // T2 has fewer qualifiers, so it could be the better sequence.
3901       if (Result == ImplicitConversionSequence::Better)
3902         // Neither has qualifiers that are a subset of the other's
3903         // qualifiers.
3904         return ImplicitConversionSequence::Indistinguishable;
3905 
3906       Result = ImplicitConversionSequence::Worse;
3907     } else {
3908       // Qualifiers are disjoint.
3909       return ImplicitConversionSequence::Indistinguishable;
3910     }
3911 
3912     // If the types after this point are equivalent, we're done.
3913     if (S.Context.hasSameUnqualifiedType(T1, T2))
3914       break;
3915   }
3916 
3917   // Check that the winning standard conversion sequence isn't using
3918   // the deprecated string literal array to pointer conversion.
3919   switch (Result) {
3920   case ImplicitConversionSequence::Better:
3921     if (SCS1.DeprecatedStringLiteralToCharPtr)
3922       Result = ImplicitConversionSequence::Indistinguishable;
3923     break;
3924 
3925   case ImplicitConversionSequence::Indistinguishable:
3926     break;
3927 
3928   case ImplicitConversionSequence::Worse:
3929     if (SCS2.DeprecatedStringLiteralToCharPtr)
3930       Result = ImplicitConversionSequence::Indistinguishable;
3931     break;
3932   }
3933 
3934   return Result;
3935 }
3936 
3937 /// CompareDerivedToBaseConversions - Compares two standard conversion
3938 /// sequences to determine whether they can be ranked based on their
3939 /// various kinds of derived-to-base conversions (C++
3940 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3941 /// conversions between Objective-C interface types.
3942 static ImplicitConversionSequence::CompareKind
3943 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3944                                 const StandardConversionSequence& SCS1,
3945                                 const StandardConversionSequence& SCS2) {
3946   QualType FromType1 = SCS1.getFromType();
3947   QualType ToType1 = SCS1.getToType(1);
3948   QualType FromType2 = SCS2.getFromType();
3949   QualType ToType2 = SCS2.getToType(1);
3950 
3951   // Adjust the types we're converting from via the array-to-pointer
3952   // conversion, if we need to.
3953   if (SCS1.First == ICK_Array_To_Pointer)
3954     FromType1 = S.Context.getArrayDecayedType(FromType1);
3955   if (SCS2.First == ICK_Array_To_Pointer)
3956     FromType2 = S.Context.getArrayDecayedType(FromType2);
3957 
3958   // Canonicalize all of the types.
3959   FromType1 = S.Context.getCanonicalType(FromType1);
3960   ToType1 = S.Context.getCanonicalType(ToType1);
3961   FromType2 = S.Context.getCanonicalType(FromType2);
3962   ToType2 = S.Context.getCanonicalType(ToType2);
3963 
3964   // C++ [over.ics.rank]p4b3:
3965   //
3966   //   If class B is derived directly or indirectly from class A and
3967   //   class C is derived directly or indirectly from B,
3968   //
3969   // Compare based on pointer conversions.
3970   if (SCS1.Second == ICK_Pointer_Conversion &&
3971       SCS2.Second == ICK_Pointer_Conversion &&
3972       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3973       FromType1->isPointerType() && FromType2->isPointerType() &&
3974       ToType1->isPointerType() && ToType2->isPointerType()) {
3975     QualType FromPointee1
3976       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3977     QualType ToPointee1
3978       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3979     QualType FromPointee2
3980       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3981     QualType ToPointee2
3982       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3983 
3984     //   -- conversion of C* to B* is better than conversion of C* to A*,
3985     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3986       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3987         return ImplicitConversionSequence::Better;
3988       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3989         return ImplicitConversionSequence::Worse;
3990     }
3991 
3992     //   -- conversion of B* to A* is better than conversion of C* to A*,
3993     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3994       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3995         return ImplicitConversionSequence::Better;
3996       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3997         return ImplicitConversionSequence::Worse;
3998     }
3999   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4000              SCS2.Second == ICK_Pointer_Conversion) {
4001     const ObjCObjectPointerType *FromPtr1
4002       = FromType1->getAs<ObjCObjectPointerType>();
4003     const ObjCObjectPointerType *FromPtr2
4004       = FromType2->getAs<ObjCObjectPointerType>();
4005     const ObjCObjectPointerType *ToPtr1
4006       = ToType1->getAs<ObjCObjectPointerType>();
4007     const ObjCObjectPointerType *ToPtr2
4008       = ToType2->getAs<ObjCObjectPointerType>();
4009 
4010     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4011       // Apply the same conversion ranking rules for Objective-C pointer types
4012       // that we do for C++ pointers to class types. However, we employ the
4013       // Objective-C pseudo-subtyping relationship used for assignment of
4014       // Objective-C pointer types.
4015       bool FromAssignLeft
4016         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4017       bool FromAssignRight
4018         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4019       bool ToAssignLeft
4020         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4021       bool ToAssignRight
4022         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4023 
4024       // A conversion to an a non-id object pointer type or qualified 'id'
4025       // type is better than a conversion to 'id'.
4026       if (ToPtr1->isObjCIdType() &&
4027           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4028         return ImplicitConversionSequence::Worse;
4029       if (ToPtr2->isObjCIdType() &&
4030           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4031         return ImplicitConversionSequence::Better;
4032 
4033       // A conversion to a non-id object pointer type is better than a
4034       // conversion to a qualified 'id' type
4035       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4036         return ImplicitConversionSequence::Worse;
4037       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4038         return ImplicitConversionSequence::Better;
4039 
4040       // A conversion to an a non-Class object pointer type or qualified 'Class'
4041       // type is better than a conversion to 'Class'.
4042       if (ToPtr1->isObjCClassType() &&
4043           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4044         return ImplicitConversionSequence::Worse;
4045       if (ToPtr2->isObjCClassType() &&
4046           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4047         return ImplicitConversionSequence::Better;
4048 
4049       // A conversion to a non-Class object pointer type is better than a
4050       // conversion to a qualified 'Class' type.
4051       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4052         return ImplicitConversionSequence::Worse;
4053       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4054         return ImplicitConversionSequence::Better;
4055 
4056       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4057       if (S.Context.hasSameType(FromType1, FromType2) &&
4058           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4059           (ToAssignLeft != ToAssignRight))
4060         return ToAssignLeft? ImplicitConversionSequence::Worse
4061                            : ImplicitConversionSequence::Better;
4062 
4063       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4064       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4065           (FromAssignLeft != FromAssignRight))
4066         return FromAssignLeft? ImplicitConversionSequence::Better
4067         : ImplicitConversionSequence::Worse;
4068     }
4069   }
4070 
4071   // Ranking of member-pointer types.
4072   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4073       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4074       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4075     const MemberPointerType * FromMemPointer1 =
4076                                         FromType1->getAs<MemberPointerType>();
4077     const MemberPointerType * ToMemPointer1 =
4078                                           ToType1->getAs<MemberPointerType>();
4079     const MemberPointerType * FromMemPointer2 =
4080                                           FromType2->getAs<MemberPointerType>();
4081     const MemberPointerType * ToMemPointer2 =
4082                                           ToType2->getAs<MemberPointerType>();
4083     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4084     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4085     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4086     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4087     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4088     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4089     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4090     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4091     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4092     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4093       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4094         return ImplicitConversionSequence::Worse;
4095       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4096         return ImplicitConversionSequence::Better;
4097     }
4098     // conversion of B::* to C::* is better than conversion of A::* to C::*
4099     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4100       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4101         return ImplicitConversionSequence::Better;
4102       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4103         return ImplicitConversionSequence::Worse;
4104     }
4105   }
4106 
4107   if (SCS1.Second == ICK_Derived_To_Base) {
4108     //   -- conversion of C to B is better than conversion of C to A,
4109     //   -- binding of an expression of type C to a reference of type
4110     //      B& is better than binding an expression of type C to a
4111     //      reference of type A&,
4112     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4113         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4114       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4115         return ImplicitConversionSequence::Better;
4116       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4117         return ImplicitConversionSequence::Worse;
4118     }
4119 
4120     //   -- conversion of B to A is better than conversion of C to A.
4121     //   -- binding of an expression of type B to a reference of type
4122     //      A& is better than binding an expression of type C to a
4123     //      reference of type A&,
4124     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4125         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4126       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4127         return ImplicitConversionSequence::Better;
4128       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4129         return ImplicitConversionSequence::Worse;
4130     }
4131   }
4132 
4133   return ImplicitConversionSequence::Indistinguishable;
4134 }
4135 
4136 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4137 /// C++ class.
4138 static bool isTypeValid(QualType T) {
4139   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4140     return !Record->isInvalidDecl();
4141 
4142   return true;
4143 }
4144 
4145 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4146 /// determine whether they are reference-related,
4147 /// reference-compatible, reference-compatible with added
4148 /// qualification, or incompatible, for use in C++ initialization by
4149 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4150 /// type, and the first type (T1) is the pointee type of the reference
4151 /// type being initialized.
4152 Sema::ReferenceCompareResult
4153 Sema::CompareReferenceRelationship(SourceLocation Loc,
4154                                    QualType OrigT1, QualType OrigT2,
4155                                    bool &DerivedToBase,
4156                                    bool &ObjCConversion,
4157                                    bool &ObjCLifetimeConversion) {
4158   assert(!OrigT1->isReferenceType() &&
4159     "T1 must be the pointee type of the reference type");
4160   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4161 
4162   QualType T1 = Context.getCanonicalType(OrigT1);
4163   QualType T2 = Context.getCanonicalType(OrigT2);
4164   Qualifiers T1Quals, T2Quals;
4165   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4166   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4167 
4168   // C++ [dcl.init.ref]p4:
4169   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4170   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4171   //   T1 is a base class of T2.
4172   DerivedToBase = false;
4173   ObjCConversion = false;
4174   ObjCLifetimeConversion = false;
4175   if (UnqualT1 == UnqualT2) {
4176     // Nothing to do.
4177   } else if (isCompleteType(Loc, OrigT2) &&
4178              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4179              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4180     DerivedToBase = true;
4181   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4182            UnqualT2->isObjCObjectOrInterfaceType() &&
4183            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4184     ObjCConversion = true;
4185   else
4186     return Ref_Incompatible;
4187 
4188   // At this point, we know that T1 and T2 are reference-related (at
4189   // least).
4190 
4191   // If the type is an array type, promote the element qualifiers to the type
4192   // for comparison.
4193   if (isa<ArrayType>(T1) && T1Quals)
4194     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4195   if (isa<ArrayType>(T2) && T2Quals)
4196     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4197 
4198   // C++ [dcl.init.ref]p4:
4199   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4200   //   reference-related to T2 and cv1 is the same cv-qualification
4201   //   as, or greater cv-qualification than, cv2. For purposes of
4202   //   overload resolution, cases for which cv1 is greater
4203   //   cv-qualification than cv2 are identified as
4204   //   reference-compatible with added qualification (see 13.3.3.2).
4205   //
4206   // Note that we also require equivalence of Objective-C GC and address-space
4207   // qualifiers when performing these computations, so that e.g., an int in
4208   // address space 1 is not reference-compatible with an int in address
4209   // space 2.
4210   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4211       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4212     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4213       ObjCLifetimeConversion = true;
4214 
4215     T1Quals.removeObjCLifetime();
4216     T2Quals.removeObjCLifetime();
4217   }
4218 
4219   // MS compiler ignores __unaligned qualifier for references; do the same.
4220   T1Quals.removeUnaligned();
4221   T2Quals.removeUnaligned();
4222 
4223   if (T1Quals == T2Quals)
4224     return Ref_Compatible;
4225   else if (T1Quals.compatiblyIncludes(T2Quals))
4226     return Ref_Compatible_With_Added_Qualification;
4227   else
4228     return Ref_Related;
4229 }
4230 
4231 /// \brief Look for a user-defined conversion to an value reference-compatible
4232 ///        with DeclType. Return true if something definite is found.
4233 static bool
4234 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4235                          QualType DeclType, SourceLocation DeclLoc,
4236                          Expr *Init, QualType T2, bool AllowRvalues,
4237                          bool AllowExplicit) {
4238   assert(T2->isRecordType() && "Can only find conversions of record types.");
4239   CXXRecordDecl *T2RecordDecl
4240     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4241 
4242   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4243   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4244   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4245     NamedDecl *D = *I;
4246     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4247     if (isa<UsingShadowDecl>(D))
4248       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4249 
4250     FunctionTemplateDecl *ConvTemplate
4251       = dyn_cast<FunctionTemplateDecl>(D);
4252     CXXConversionDecl *Conv;
4253     if (ConvTemplate)
4254       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4255     else
4256       Conv = cast<CXXConversionDecl>(D);
4257 
4258     // If this is an explicit conversion, and we're not allowed to consider
4259     // explicit conversions, skip it.
4260     if (!AllowExplicit && Conv->isExplicit())
4261       continue;
4262 
4263     if (AllowRvalues) {
4264       bool DerivedToBase = false;
4265       bool ObjCConversion = false;
4266       bool ObjCLifetimeConversion = false;
4267 
4268       // If we are initializing an rvalue reference, don't permit conversion
4269       // functions that return lvalues.
4270       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4271         const ReferenceType *RefType
4272           = Conv->getConversionType()->getAs<LValueReferenceType>();
4273         if (RefType && !RefType->getPointeeType()->isFunctionType())
4274           continue;
4275       }
4276 
4277       if (!ConvTemplate &&
4278           S.CompareReferenceRelationship(
4279             DeclLoc,
4280             Conv->getConversionType().getNonReferenceType()
4281               .getUnqualifiedType(),
4282             DeclType.getNonReferenceType().getUnqualifiedType(),
4283             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4284           Sema::Ref_Incompatible)
4285         continue;
4286     } else {
4287       // If the conversion function doesn't return a reference type,
4288       // it can't be considered for this conversion. An rvalue reference
4289       // is only acceptable if its referencee is a function type.
4290 
4291       const ReferenceType *RefType =
4292         Conv->getConversionType()->getAs<ReferenceType>();
4293       if (!RefType ||
4294           (!RefType->isLValueReferenceType() &&
4295            !RefType->getPointeeType()->isFunctionType()))
4296         continue;
4297     }
4298 
4299     if (ConvTemplate)
4300       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4301                                        Init, DeclType, CandidateSet,
4302                                        /*AllowObjCConversionOnExplicit=*/false);
4303     else
4304       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4305                                DeclType, CandidateSet,
4306                                /*AllowObjCConversionOnExplicit=*/false);
4307   }
4308 
4309   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4310 
4311   OverloadCandidateSet::iterator Best;
4312   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4313   case OR_Success:
4314     // C++ [over.ics.ref]p1:
4315     //
4316     //   [...] If the parameter binds directly to the result of
4317     //   applying a conversion function to the argument
4318     //   expression, the implicit conversion sequence is a
4319     //   user-defined conversion sequence (13.3.3.1.2), with the
4320     //   second standard conversion sequence either an identity
4321     //   conversion or, if the conversion function returns an
4322     //   entity of a type that is a derived class of the parameter
4323     //   type, a derived-to-base Conversion.
4324     if (!Best->FinalConversion.DirectBinding)
4325       return false;
4326 
4327     ICS.setUserDefined();
4328     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4329     ICS.UserDefined.After = Best->FinalConversion;
4330     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4331     ICS.UserDefined.ConversionFunction = Best->Function;
4332     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4333     ICS.UserDefined.EllipsisConversion = false;
4334     assert(ICS.UserDefined.After.ReferenceBinding &&
4335            ICS.UserDefined.After.DirectBinding &&
4336            "Expected a direct reference binding!");
4337     return true;
4338 
4339   case OR_Ambiguous:
4340     ICS.setAmbiguous();
4341     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4342          Cand != CandidateSet.end(); ++Cand)
4343       if (Cand->Viable)
4344         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4345     return true;
4346 
4347   case OR_No_Viable_Function:
4348   case OR_Deleted:
4349     // There was no suitable conversion, or we found a deleted
4350     // conversion; continue with other checks.
4351     return false;
4352   }
4353 
4354   llvm_unreachable("Invalid OverloadResult!");
4355 }
4356 
4357 /// \brief Compute an implicit conversion sequence for reference
4358 /// initialization.
4359 static ImplicitConversionSequence
4360 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4361                  SourceLocation DeclLoc,
4362                  bool SuppressUserConversions,
4363                  bool AllowExplicit) {
4364   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4365 
4366   // Most paths end in a failed conversion.
4367   ImplicitConversionSequence ICS;
4368   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4369 
4370   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4371   QualType T2 = Init->getType();
4372 
4373   // If the initializer is the address of an overloaded function, try
4374   // to resolve the overloaded function. If all goes well, T2 is the
4375   // type of the resulting function.
4376   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4377     DeclAccessPair Found;
4378     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4379                                                                 false, Found))
4380       T2 = Fn->getType();
4381   }
4382 
4383   // Compute some basic properties of the types and the initializer.
4384   bool isRValRef = DeclType->isRValueReferenceType();
4385   bool DerivedToBase = false;
4386   bool ObjCConversion = false;
4387   bool ObjCLifetimeConversion = false;
4388   Expr::Classification InitCategory = Init->Classify(S.Context);
4389   Sema::ReferenceCompareResult RefRelationship
4390     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4391                                      ObjCConversion, ObjCLifetimeConversion);
4392 
4393 
4394   // C++0x [dcl.init.ref]p5:
4395   //   A reference to type "cv1 T1" is initialized by an expression
4396   //   of type "cv2 T2" as follows:
4397 
4398   //     -- If reference is an lvalue reference and the initializer expression
4399   if (!isRValRef) {
4400     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4401     //        reference-compatible with "cv2 T2," or
4402     //
4403     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4404     if (InitCategory.isLValue() &&
4405         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4406       // C++ [over.ics.ref]p1:
4407       //   When a parameter of reference type binds directly (8.5.3)
4408       //   to an argument expression, the implicit conversion sequence
4409       //   is the identity conversion, unless the argument expression
4410       //   has a type that is a derived class of the parameter type,
4411       //   in which case the implicit conversion sequence is a
4412       //   derived-to-base Conversion (13.3.3.1).
4413       ICS.setStandard();
4414       ICS.Standard.First = ICK_Identity;
4415       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4416                          : ObjCConversion? ICK_Compatible_Conversion
4417                          : ICK_Identity;
4418       ICS.Standard.Third = ICK_Identity;
4419       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4420       ICS.Standard.setToType(0, T2);
4421       ICS.Standard.setToType(1, T1);
4422       ICS.Standard.setToType(2, T1);
4423       ICS.Standard.ReferenceBinding = true;
4424       ICS.Standard.DirectBinding = true;
4425       ICS.Standard.IsLvalueReference = !isRValRef;
4426       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4427       ICS.Standard.BindsToRvalue = false;
4428       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4429       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4430       ICS.Standard.CopyConstructor = nullptr;
4431       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4432 
4433       // Nothing more to do: the inaccessibility/ambiguity check for
4434       // derived-to-base conversions is suppressed when we're
4435       // computing the implicit conversion sequence (C++
4436       // [over.best.ics]p2).
4437       return ICS;
4438     }
4439 
4440     //       -- has a class type (i.e., T2 is a class type), where T1 is
4441     //          not reference-related to T2, and can be implicitly
4442     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4443     //          is reference-compatible with "cv3 T3" 92) (this
4444     //          conversion is selected by enumerating the applicable
4445     //          conversion functions (13.3.1.6) and choosing the best
4446     //          one through overload resolution (13.3)),
4447     if (!SuppressUserConversions && T2->isRecordType() &&
4448         S.isCompleteType(DeclLoc, T2) &&
4449         RefRelationship == Sema::Ref_Incompatible) {
4450       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4451                                    Init, T2, /*AllowRvalues=*/false,
4452                                    AllowExplicit))
4453         return ICS;
4454     }
4455   }
4456 
4457   //     -- Otherwise, the reference shall be an lvalue reference to a
4458   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4459   //        shall be an rvalue reference.
4460   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4461     return ICS;
4462 
4463   //       -- If the initializer expression
4464   //
4465   //            -- is an xvalue, class prvalue, array prvalue or function
4466   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4467   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4468       (InitCategory.isXValue() ||
4469       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4470       (InitCategory.isLValue() && T2->isFunctionType()))) {
4471     ICS.setStandard();
4472     ICS.Standard.First = ICK_Identity;
4473     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4474                       : ObjCConversion? ICK_Compatible_Conversion
4475                       : ICK_Identity;
4476     ICS.Standard.Third = ICK_Identity;
4477     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4478     ICS.Standard.setToType(0, T2);
4479     ICS.Standard.setToType(1, T1);
4480     ICS.Standard.setToType(2, T1);
4481     ICS.Standard.ReferenceBinding = true;
4482     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4483     // binding unless we're binding to a class prvalue.
4484     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4485     // allow the use of rvalue references in C++98/03 for the benefit of
4486     // standard library implementors; therefore, we need the xvalue check here.
4487     ICS.Standard.DirectBinding =
4488       S.getLangOpts().CPlusPlus11 ||
4489       !(InitCategory.isPRValue() || T2->isRecordType());
4490     ICS.Standard.IsLvalueReference = !isRValRef;
4491     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4492     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4493     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4494     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4495     ICS.Standard.CopyConstructor = nullptr;
4496     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4497     return ICS;
4498   }
4499 
4500   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4501   //               reference-related to T2, and can be implicitly converted to
4502   //               an xvalue, class prvalue, or function lvalue of type
4503   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4504   //               "cv3 T3",
4505   //
4506   //          then the reference is bound to the value of the initializer
4507   //          expression in the first case and to the result of the conversion
4508   //          in the second case (or, in either case, to an appropriate base
4509   //          class subobject).
4510   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4511       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4512       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4513                                Init, T2, /*AllowRvalues=*/true,
4514                                AllowExplicit)) {
4515     // In the second case, if the reference is an rvalue reference
4516     // and the second standard conversion sequence of the
4517     // user-defined conversion sequence includes an lvalue-to-rvalue
4518     // conversion, the program is ill-formed.
4519     if (ICS.isUserDefined() && isRValRef &&
4520         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4521       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4522 
4523     return ICS;
4524   }
4525 
4526   // A temporary of function type cannot be created; don't even try.
4527   if (T1->isFunctionType())
4528     return ICS;
4529 
4530   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4531   //          initialized from the initializer expression using the
4532   //          rules for a non-reference copy initialization (8.5). The
4533   //          reference is then bound to the temporary. If T1 is
4534   //          reference-related to T2, cv1 must be the same
4535   //          cv-qualification as, or greater cv-qualification than,
4536   //          cv2; otherwise, the program is ill-formed.
4537   if (RefRelationship == Sema::Ref_Related) {
4538     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4539     // we would be reference-compatible or reference-compatible with
4540     // added qualification. But that wasn't the case, so the reference
4541     // initialization fails.
4542     //
4543     // Note that we only want to check address spaces and cvr-qualifiers here.
4544     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4545     Qualifiers T1Quals = T1.getQualifiers();
4546     Qualifiers T2Quals = T2.getQualifiers();
4547     T1Quals.removeObjCGCAttr();
4548     T1Quals.removeObjCLifetime();
4549     T2Quals.removeObjCGCAttr();
4550     T2Quals.removeObjCLifetime();
4551     // MS compiler ignores __unaligned qualifier for references; do the same.
4552     T1Quals.removeUnaligned();
4553     T2Quals.removeUnaligned();
4554     if (!T1Quals.compatiblyIncludes(T2Quals))
4555       return ICS;
4556   }
4557 
4558   // If at least one of the types is a class type, the types are not
4559   // related, and we aren't allowed any user conversions, the
4560   // reference binding fails. This case is important for breaking
4561   // recursion, since TryImplicitConversion below will attempt to
4562   // create a temporary through the use of a copy constructor.
4563   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4564       (T1->isRecordType() || T2->isRecordType()))
4565     return ICS;
4566 
4567   // If T1 is reference-related to T2 and the reference is an rvalue
4568   // reference, the initializer expression shall not be an lvalue.
4569   if (RefRelationship >= Sema::Ref_Related &&
4570       isRValRef && Init->Classify(S.Context).isLValue())
4571     return ICS;
4572 
4573   // C++ [over.ics.ref]p2:
4574   //   When a parameter of reference type is not bound directly to
4575   //   an argument expression, the conversion sequence is the one
4576   //   required to convert the argument expression to the
4577   //   underlying type of the reference according to
4578   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4579   //   to copy-initializing a temporary of the underlying type with
4580   //   the argument expression. Any difference in top-level
4581   //   cv-qualification is subsumed by the initialization itself
4582   //   and does not constitute a conversion.
4583   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4584                               /*AllowExplicit=*/false,
4585                               /*InOverloadResolution=*/false,
4586                               /*CStyle=*/false,
4587                               /*AllowObjCWritebackConversion=*/false,
4588                               /*AllowObjCConversionOnExplicit=*/false);
4589 
4590   // Of course, that's still a reference binding.
4591   if (ICS.isStandard()) {
4592     ICS.Standard.ReferenceBinding = true;
4593     ICS.Standard.IsLvalueReference = !isRValRef;
4594     ICS.Standard.BindsToFunctionLvalue = false;
4595     ICS.Standard.BindsToRvalue = true;
4596     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4597     ICS.Standard.ObjCLifetimeConversionBinding = false;
4598   } else if (ICS.isUserDefined()) {
4599     const ReferenceType *LValRefType =
4600         ICS.UserDefined.ConversionFunction->getReturnType()
4601             ->getAs<LValueReferenceType>();
4602 
4603     // C++ [over.ics.ref]p3:
4604     //   Except for an implicit object parameter, for which see 13.3.1, a
4605     //   standard conversion sequence cannot be formed if it requires [...]
4606     //   binding an rvalue reference to an lvalue other than a function
4607     //   lvalue.
4608     // Note that the function case is not possible here.
4609     if (DeclType->isRValueReferenceType() && LValRefType) {
4610       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4611       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4612       // reference to an rvalue!
4613       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4614       return ICS;
4615     }
4616 
4617     ICS.UserDefined.After.ReferenceBinding = true;
4618     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4619     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4620     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4621     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4622     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4623   }
4624 
4625   return ICS;
4626 }
4627 
4628 static ImplicitConversionSequence
4629 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4630                       bool SuppressUserConversions,
4631                       bool InOverloadResolution,
4632                       bool AllowObjCWritebackConversion,
4633                       bool AllowExplicit = false);
4634 
4635 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4636 /// initializer list From.
4637 static ImplicitConversionSequence
4638 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4639                   bool SuppressUserConversions,
4640                   bool InOverloadResolution,
4641                   bool AllowObjCWritebackConversion) {
4642   // C++11 [over.ics.list]p1:
4643   //   When an argument is an initializer list, it is not an expression and
4644   //   special rules apply for converting it to a parameter type.
4645 
4646   ImplicitConversionSequence Result;
4647   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4648 
4649   // We need a complete type for what follows. Incomplete types can never be
4650   // initialized from init lists.
4651   if (!S.isCompleteType(From->getLocStart(), ToType))
4652     return Result;
4653 
4654   // Per DR1467:
4655   //   If the parameter type is a class X and the initializer list has a single
4656   //   element of type cv U, where U is X or a class derived from X, the
4657   //   implicit conversion sequence is the one required to convert the element
4658   //   to the parameter type.
4659   //
4660   //   Otherwise, if the parameter type is a character array [... ]
4661   //   and the initializer list has a single element that is an
4662   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4663   //   implicit conversion sequence is the identity conversion.
4664   if (From->getNumInits() == 1) {
4665     if (ToType->isRecordType()) {
4666       QualType InitType = From->getInit(0)->getType();
4667       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4668           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4669         return TryCopyInitialization(S, From->getInit(0), ToType,
4670                                      SuppressUserConversions,
4671                                      InOverloadResolution,
4672                                      AllowObjCWritebackConversion);
4673     }
4674     // FIXME: Check the other conditions here: array of character type,
4675     // initializer is a string literal.
4676     if (ToType->isArrayType()) {
4677       InitializedEntity Entity =
4678         InitializedEntity::InitializeParameter(S.Context, ToType,
4679                                                /*Consumed=*/false);
4680       if (S.CanPerformCopyInitialization(Entity, From)) {
4681         Result.setStandard();
4682         Result.Standard.setAsIdentityConversion();
4683         Result.Standard.setFromType(ToType);
4684         Result.Standard.setAllToTypes(ToType);
4685         return Result;
4686       }
4687     }
4688   }
4689 
4690   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4691   // C++11 [over.ics.list]p2:
4692   //   If the parameter type is std::initializer_list<X> or "array of X" and
4693   //   all the elements can be implicitly converted to X, the implicit
4694   //   conversion sequence is the worst conversion necessary to convert an
4695   //   element of the list to X.
4696   //
4697   // C++14 [over.ics.list]p3:
4698   //   Otherwise, if the parameter type is "array of N X", if the initializer
4699   //   list has exactly N elements or if it has fewer than N elements and X is
4700   //   default-constructible, and if all the elements of the initializer list
4701   //   can be implicitly converted to X, the implicit conversion sequence is
4702   //   the worst conversion necessary to convert an element of the list to X.
4703   //
4704   // FIXME: We're missing a lot of these checks.
4705   bool toStdInitializerList = false;
4706   QualType X;
4707   if (ToType->isArrayType())
4708     X = S.Context.getAsArrayType(ToType)->getElementType();
4709   else
4710     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4711   if (!X.isNull()) {
4712     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4713       Expr *Init = From->getInit(i);
4714       ImplicitConversionSequence ICS =
4715           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4716                                 InOverloadResolution,
4717                                 AllowObjCWritebackConversion);
4718       // If a single element isn't convertible, fail.
4719       if (ICS.isBad()) {
4720         Result = ICS;
4721         break;
4722       }
4723       // Otherwise, look for the worst conversion.
4724       if (Result.isBad() ||
4725           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4726                                              Result) ==
4727               ImplicitConversionSequence::Worse)
4728         Result = ICS;
4729     }
4730 
4731     // For an empty list, we won't have computed any conversion sequence.
4732     // Introduce the identity conversion sequence.
4733     if (From->getNumInits() == 0) {
4734       Result.setStandard();
4735       Result.Standard.setAsIdentityConversion();
4736       Result.Standard.setFromType(ToType);
4737       Result.Standard.setAllToTypes(ToType);
4738     }
4739 
4740     Result.setStdInitializerListElement(toStdInitializerList);
4741     return Result;
4742   }
4743 
4744   // C++14 [over.ics.list]p4:
4745   // C++11 [over.ics.list]p3:
4746   //   Otherwise, if the parameter is a non-aggregate class X and overload
4747   //   resolution chooses a single best constructor [...] the implicit
4748   //   conversion sequence is a user-defined conversion sequence. If multiple
4749   //   constructors are viable but none is better than the others, the
4750   //   implicit conversion sequence is a user-defined conversion sequence.
4751   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4752     // This function can deal with initializer lists.
4753     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4754                                     /*AllowExplicit=*/false,
4755                                     InOverloadResolution, /*CStyle=*/false,
4756                                     AllowObjCWritebackConversion,
4757                                     /*AllowObjCConversionOnExplicit=*/false);
4758   }
4759 
4760   // C++14 [over.ics.list]p5:
4761   // C++11 [over.ics.list]p4:
4762   //   Otherwise, if the parameter has an aggregate type which can be
4763   //   initialized from the initializer list [...] the implicit conversion
4764   //   sequence is a user-defined conversion sequence.
4765   if (ToType->isAggregateType()) {
4766     // Type is an aggregate, argument is an init list. At this point it comes
4767     // down to checking whether the initialization works.
4768     // FIXME: Find out whether this parameter is consumed or not.
4769     InitializedEntity Entity =
4770         InitializedEntity::InitializeParameter(S.Context, ToType,
4771                                                /*Consumed=*/false);
4772     if (S.CanPerformCopyInitialization(Entity, From)) {
4773       Result.setUserDefined();
4774       Result.UserDefined.Before.setAsIdentityConversion();
4775       // Initializer lists don't have a type.
4776       Result.UserDefined.Before.setFromType(QualType());
4777       Result.UserDefined.Before.setAllToTypes(QualType());
4778 
4779       Result.UserDefined.After.setAsIdentityConversion();
4780       Result.UserDefined.After.setFromType(ToType);
4781       Result.UserDefined.After.setAllToTypes(ToType);
4782       Result.UserDefined.ConversionFunction = nullptr;
4783     }
4784     return Result;
4785   }
4786 
4787   // C++14 [over.ics.list]p6:
4788   // C++11 [over.ics.list]p5:
4789   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4790   if (ToType->isReferenceType()) {
4791     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4792     // mention initializer lists in any way. So we go by what list-
4793     // initialization would do and try to extrapolate from that.
4794 
4795     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4796 
4797     // If the initializer list has a single element that is reference-related
4798     // to the parameter type, we initialize the reference from that.
4799     if (From->getNumInits() == 1) {
4800       Expr *Init = From->getInit(0);
4801 
4802       QualType T2 = Init->getType();
4803 
4804       // If the initializer is the address of an overloaded function, try
4805       // to resolve the overloaded function. If all goes well, T2 is the
4806       // type of the resulting function.
4807       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4808         DeclAccessPair Found;
4809         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4810                                    Init, ToType, false, Found))
4811           T2 = Fn->getType();
4812       }
4813 
4814       // Compute some basic properties of the types and the initializer.
4815       bool dummy1 = false;
4816       bool dummy2 = false;
4817       bool dummy3 = false;
4818       Sema::ReferenceCompareResult RefRelationship
4819         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4820                                          dummy2, dummy3);
4821 
4822       if (RefRelationship >= Sema::Ref_Related) {
4823         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4824                                 SuppressUserConversions,
4825                                 /*AllowExplicit=*/false);
4826       }
4827     }
4828 
4829     // Otherwise, we bind the reference to a temporary created from the
4830     // initializer list.
4831     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4832                                InOverloadResolution,
4833                                AllowObjCWritebackConversion);
4834     if (Result.isFailure())
4835       return Result;
4836     assert(!Result.isEllipsis() &&
4837            "Sub-initialization cannot result in ellipsis conversion.");
4838 
4839     // Can we even bind to a temporary?
4840     if (ToType->isRValueReferenceType() ||
4841         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4842       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4843                                             Result.UserDefined.After;
4844       SCS.ReferenceBinding = true;
4845       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4846       SCS.BindsToRvalue = true;
4847       SCS.BindsToFunctionLvalue = false;
4848       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4849       SCS.ObjCLifetimeConversionBinding = false;
4850     } else
4851       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4852                     From, ToType);
4853     return Result;
4854   }
4855 
4856   // C++14 [over.ics.list]p7:
4857   // C++11 [over.ics.list]p6:
4858   //   Otherwise, if the parameter type is not a class:
4859   if (!ToType->isRecordType()) {
4860     //    - if the initializer list has one element that is not itself an
4861     //      initializer list, the implicit conversion sequence is the one
4862     //      required to convert the element to the parameter type.
4863     unsigned NumInits = From->getNumInits();
4864     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4865       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4866                                      SuppressUserConversions,
4867                                      InOverloadResolution,
4868                                      AllowObjCWritebackConversion);
4869     //    - if the initializer list has no elements, the implicit conversion
4870     //      sequence is the identity conversion.
4871     else if (NumInits == 0) {
4872       Result.setStandard();
4873       Result.Standard.setAsIdentityConversion();
4874       Result.Standard.setFromType(ToType);
4875       Result.Standard.setAllToTypes(ToType);
4876     }
4877     return Result;
4878   }
4879 
4880   // C++14 [over.ics.list]p8:
4881   // C++11 [over.ics.list]p7:
4882   //   In all cases other than those enumerated above, no conversion is possible
4883   return Result;
4884 }
4885 
4886 /// TryCopyInitialization - Try to copy-initialize a value of type
4887 /// ToType from the expression From. Return the implicit conversion
4888 /// sequence required to pass this argument, which may be a bad
4889 /// conversion sequence (meaning that the argument cannot be passed to
4890 /// a parameter of this type). If @p SuppressUserConversions, then we
4891 /// do not permit any user-defined conversion sequences.
4892 static ImplicitConversionSequence
4893 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4894                       bool SuppressUserConversions,
4895                       bool InOverloadResolution,
4896                       bool AllowObjCWritebackConversion,
4897                       bool AllowExplicit) {
4898   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4899     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4900                              InOverloadResolution,AllowObjCWritebackConversion);
4901 
4902   if (ToType->isReferenceType())
4903     return TryReferenceInit(S, From, ToType,
4904                             /*FIXME:*/From->getLocStart(),
4905                             SuppressUserConversions,
4906                             AllowExplicit);
4907 
4908   return TryImplicitConversion(S, From, ToType,
4909                                SuppressUserConversions,
4910                                /*AllowExplicit=*/false,
4911                                InOverloadResolution,
4912                                /*CStyle=*/false,
4913                                AllowObjCWritebackConversion,
4914                                /*AllowObjCConversionOnExplicit=*/false);
4915 }
4916 
4917 static bool TryCopyInitialization(const CanQualType FromQTy,
4918                                   const CanQualType ToQTy,
4919                                   Sema &S,
4920                                   SourceLocation Loc,
4921                                   ExprValueKind FromVK) {
4922   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4923   ImplicitConversionSequence ICS =
4924     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4925 
4926   return !ICS.isBad();
4927 }
4928 
4929 /// TryObjectArgumentInitialization - Try to initialize the object
4930 /// parameter of the given member function (@c Method) from the
4931 /// expression @p From.
4932 static ImplicitConversionSequence
4933 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4934                                 Expr::Classification FromClassification,
4935                                 CXXMethodDecl *Method,
4936                                 CXXRecordDecl *ActingContext) {
4937   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4938   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4939   //                 const volatile object.
4940   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4941     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4942   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4943 
4944   // Set up the conversion sequence as a "bad" conversion, to allow us
4945   // to exit early.
4946   ImplicitConversionSequence ICS;
4947 
4948   // We need to have an object of class type.
4949   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4950     FromType = PT->getPointeeType();
4951 
4952     // When we had a pointer, it's implicitly dereferenced, so we
4953     // better have an lvalue.
4954     assert(FromClassification.isLValue());
4955   }
4956 
4957   assert(FromType->isRecordType());
4958 
4959   // C++0x [over.match.funcs]p4:
4960   //   For non-static member functions, the type of the implicit object
4961   //   parameter is
4962   //
4963   //     - "lvalue reference to cv X" for functions declared without a
4964   //        ref-qualifier or with the & ref-qualifier
4965   //     - "rvalue reference to cv X" for functions declared with the &&
4966   //        ref-qualifier
4967   //
4968   // where X is the class of which the function is a member and cv is the
4969   // cv-qualification on the member function declaration.
4970   //
4971   // However, when finding an implicit conversion sequence for the argument, we
4972   // are not allowed to create temporaries or perform user-defined conversions
4973   // (C++ [over.match.funcs]p5). We perform a simplified version of
4974   // reference binding here, that allows class rvalues to bind to
4975   // non-constant references.
4976 
4977   // First check the qualifiers.
4978   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4979   if (ImplicitParamType.getCVRQualifiers()
4980                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4981       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4982     ICS.setBad(BadConversionSequence::bad_qualifiers,
4983                FromType, ImplicitParamType);
4984     return ICS;
4985   }
4986 
4987   // Check that we have either the same type or a derived type. It
4988   // affects the conversion rank.
4989   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4990   ImplicitConversionKind SecondKind;
4991   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4992     SecondKind = ICK_Identity;
4993   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
4994     SecondKind = ICK_Derived_To_Base;
4995   else {
4996     ICS.setBad(BadConversionSequence::unrelated_class,
4997                FromType, ImplicitParamType);
4998     return ICS;
4999   }
5000 
5001   // Check the ref-qualifier.
5002   switch (Method->getRefQualifier()) {
5003   case RQ_None:
5004     // Do nothing; we don't care about lvalueness or rvalueness.
5005     break;
5006 
5007   case RQ_LValue:
5008     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5009       // non-const lvalue reference cannot bind to an rvalue
5010       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5011                  ImplicitParamType);
5012       return ICS;
5013     }
5014     break;
5015 
5016   case RQ_RValue:
5017     if (!FromClassification.isRValue()) {
5018       // rvalue reference cannot bind to an lvalue
5019       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5020                  ImplicitParamType);
5021       return ICS;
5022     }
5023     break;
5024   }
5025 
5026   // Success. Mark this as a reference binding.
5027   ICS.setStandard();
5028   ICS.Standard.setAsIdentityConversion();
5029   ICS.Standard.Second = SecondKind;
5030   ICS.Standard.setFromType(FromType);
5031   ICS.Standard.setAllToTypes(ImplicitParamType);
5032   ICS.Standard.ReferenceBinding = true;
5033   ICS.Standard.DirectBinding = true;
5034   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5035   ICS.Standard.BindsToFunctionLvalue = false;
5036   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5037   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5038     = (Method->getRefQualifier() == RQ_None);
5039   return ICS;
5040 }
5041 
5042 /// PerformObjectArgumentInitialization - Perform initialization of
5043 /// the implicit object parameter for the given Method with the given
5044 /// expression.
5045 ExprResult
5046 Sema::PerformObjectArgumentInitialization(Expr *From,
5047                                           NestedNameSpecifier *Qualifier,
5048                                           NamedDecl *FoundDecl,
5049                                           CXXMethodDecl *Method) {
5050   QualType FromRecordType, DestType;
5051   QualType ImplicitParamRecordType  =
5052     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5053 
5054   Expr::Classification FromClassification;
5055   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5056     FromRecordType = PT->getPointeeType();
5057     DestType = Method->getThisType(Context);
5058     FromClassification = Expr::Classification::makeSimpleLValue();
5059   } else {
5060     FromRecordType = From->getType();
5061     DestType = ImplicitParamRecordType;
5062     FromClassification = From->Classify(Context);
5063   }
5064 
5065   // Note that we always use the true parent context when performing
5066   // the actual argument initialization.
5067   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5068       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5069       Method->getParent());
5070   if (ICS.isBad()) {
5071     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5072       Qualifiers FromQs = FromRecordType.getQualifiers();
5073       Qualifiers ToQs = DestType.getQualifiers();
5074       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5075       if (CVR) {
5076         Diag(From->getLocStart(),
5077              diag::err_member_function_call_bad_cvr)
5078           << Method->getDeclName() << FromRecordType << (CVR - 1)
5079           << From->getSourceRange();
5080         Diag(Method->getLocation(), diag::note_previous_decl)
5081           << Method->getDeclName();
5082         return ExprError();
5083       }
5084     }
5085 
5086     return Diag(From->getLocStart(),
5087                 diag::err_implicit_object_parameter_init)
5088        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5089   }
5090 
5091   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5092     ExprResult FromRes =
5093       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5094     if (FromRes.isInvalid())
5095       return ExprError();
5096     From = FromRes.get();
5097   }
5098 
5099   if (!Context.hasSameType(From->getType(), DestType))
5100     From = ImpCastExprToType(From, DestType, CK_NoOp,
5101                              From->getValueKind()).get();
5102   return From;
5103 }
5104 
5105 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5106 /// expression From to bool (C++0x [conv]p3).
5107 static ImplicitConversionSequence
5108 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5109   return TryImplicitConversion(S, From, S.Context.BoolTy,
5110                                /*SuppressUserConversions=*/false,
5111                                /*AllowExplicit=*/true,
5112                                /*InOverloadResolution=*/false,
5113                                /*CStyle=*/false,
5114                                /*AllowObjCWritebackConversion=*/false,
5115                                /*AllowObjCConversionOnExplicit=*/false);
5116 }
5117 
5118 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5119 /// of the expression From to bool (C++0x [conv]p3).
5120 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5121   if (checkPlaceholderForOverload(*this, From))
5122     return ExprError();
5123 
5124   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5125   if (!ICS.isBad())
5126     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5127 
5128   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5129     return Diag(From->getLocStart(),
5130                 diag::err_typecheck_bool_condition)
5131                   << From->getType() << From->getSourceRange();
5132   return ExprError();
5133 }
5134 
5135 /// Check that the specified conversion is permitted in a converted constant
5136 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5137 /// is acceptable.
5138 static bool CheckConvertedConstantConversions(Sema &S,
5139                                               StandardConversionSequence &SCS) {
5140   // Since we know that the target type is an integral or unscoped enumeration
5141   // type, most conversion kinds are impossible. All possible First and Third
5142   // conversions are fine.
5143   switch (SCS.Second) {
5144   case ICK_Identity:
5145   case ICK_Function_Conversion:
5146   case ICK_Integral_Promotion:
5147   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5148     return true;
5149 
5150   case ICK_Boolean_Conversion:
5151     // Conversion from an integral or unscoped enumeration type to bool is
5152     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5153     // conversion, so we allow it in a converted constant expression.
5154     //
5155     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5156     // a lot of popular code. We should at least add a warning for this
5157     // (non-conforming) extension.
5158     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5159            SCS.getToType(2)->isBooleanType();
5160 
5161   case ICK_Pointer_Conversion:
5162   case ICK_Pointer_Member:
5163     // C++1z: null pointer conversions and null member pointer conversions are
5164     // only permitted if the source type is std::nullptr_t.
5165     return SCS.getFromType()->isNullPtrType();
5166 
5167   case ICK_Floating_Promotion:
5168   case ICK_Complex_Promotion:
5169   case ICK_Floating_Conversion:
5170   case ICK_Complex_Conversion:
5171   case ICK_Floating_Integral:
5172   case ICK_Compatible_Conversion:
5173   case ICK_Derived_To_Base:
5174   case ICK_Vector_Conversion:
5175   case ICK_Vector_Splat:
5176   case ICK_Complex_Real:
5177   case ICK_Block_Pointer_Conversion:
5178   case ICK_TransparentUnionConversion:
5179   case ICK_Writeback_Conversion:
5180   case ICK_Zero_Event_Conversion:
5181   case ICK_C_Only_Conversion:
5182   case ICK_Incompatible_Pointer_Conversion:
5183     return false;
5184 
5185   case ICK_Lvalue_To_Rvalue:
5186   case ICK_Array_To_Pointer:
5187   case ICK_Function_To_Pointer:
5188     llvm_unreachable("found a first conversion kind in Second");
5189 
5190   case ICK_Qualification:
5191     llvm_unreachable("found a third conversion kind in Second");
5192 
5193   case ICK_Num_Conversion_Kinds:
5194     break;
5195   }
5196 
5197   llvm_unreachable("unknown conversion kind");
5198 }
5199 
5200 /// CheckConvertedConstantExpression - Check that the expression From is a
5201 /// converted constant expression of type T, perform the conversion and produce
5202 /// the converted expression, per C++11 [expr.const]p3.
5203 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5204                                                    QualType T, APValue &Value,
5205                                                    Sema::CCEKind CCE,
5206                                                    bool RequireInt) {
5207   assert(S.getLangOpts().CPlusPlus11 &&
5208          "converted constant expression outside C++11");
5209 
5210   if (checkPlaceholderForOverload(S, From))
5211     return ExprError();
5212 
5213   // C++1z [expr.const]p3:
5214   //  A converted constant expression of type T is an expression,
5215   //  implicitly converted to type T, where the converted
5216   //  expression is a constant expression and the implicit conversion
5217   //  sequence contains only [... list of conversions ...].
5218   // C++1z [stmt.if]p2:
5219   //  If the if statement is of the form if constexpr, the value of the
5220   //  condition shall be a contextually converted constant expression of type
5221   //  bool.
5222   ImplicitConversionSequence ICS =
5223       CCE == Sema::CCEK_ConstexprIf
5224           ? TryContextuallyConvertToBool(S, From)
5225           : TryCopyInitialization(S, From, T,
5226                                   /*SuppressUserConversions=*/false,
5227                                   /*InOverloadResolution=*/false,
5228                                   /*AllowObjcWritebackConversion=*/false,
5229                                   /*AllowExplicit=*/false);
5230   StandardConversionSequence *SCS = nullptr;
5231   switch (ICS.getKind()) {
5232   case ImplicitConversionSequence::StandardConversion:
5233     SCS = &ICS.Standard;
5234     break;
5235   case ImplicitConversionSequence::UserDefinedConversion:
5236     // We are converting to a non-class type, so the Before sequence
5237     // must be trivial.
5238     SCS = &ICS.UserDefined.After;
5239     break;
5240   case ImplicitConversionSequence::AmbiguousConversion:
5241   case ImplicitConversionSequence::BadConversion:
5242     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5243       return S.Diag(From->getLocStart(),
5244                     diag::err_typecheck_converted_constant_expression)
5245                 << From->getType() << From->getSourceRange() << T;
5246     return ExprError();
5247 
5248   case ImplicitConversionSequence::EllipsisConversion:
5249     llvm_unreachable("ellipsis conversion in converted constant expression");
5250   }
5251 
5252   // Check that we would only use permitted conversions.
5253   if (!CheckConvertedConstantConversions(S, *SCS)) {
5254     return S.Diag(From->getLocStart(),
5255                   diag::err_typecheck_converted_constant_expression_disallowed)
5256              << From->getType() << From->getSourceRange() << T;
5257   }
5258   // [...] and where the reference binding (if any) binds directly.
5259   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5260     return S.Diag(From->getLocStart(),
5261                   diag::err_typecheck_converted_constant_expression_indirect)
5262              << From->getType() << From->getSourceRange() << T;
5263   }
5264 
5265   ExprResult Result =
5266       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5267   if (Result.isInvalid())
5268     return Result;
5269 
5270   // Check for a narrowing implicit conversion.
5271   APValue PreNarrowingValue;
5272   QualType PreNarrowingType;
5273   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5274                                 PreNarrowingType)) {
5275   case NK_Variable_Narrowing:
5276     // Implicit conversion to a narrower type, and the value is not a constant
5277     // expression. We'll diagnose this in a moment.
5278   case NK_Not_Narrowing:
5279     break;
5280 
5281   case NK_Constant_Narrowing:
5282     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5283       << CCE << /*Constant*/1
5284       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5285     break;
5286 
5287   case NK_Type_Narrowing:
5288     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5289       << CCE << /*Constant*/0 << From->getType() << T;
5290     break;
5291   }
5292 
5293   // Check the expression is a constant expression.
5294   SmallVector<PartialDiagnosticAt, 8> Notes;
5295   Expr::EvalResult Eval;
5296   Eval.Diag = &Notes;
5297 
5298   if ((T->isReferenceType()
5299            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5300            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5301       (RequireInt && !Eval.Val.isInt())) {
5302     // The expression can't be folded, so we can't keep it at this position in
5303     // the AST.
5304     Result = ExprError();
5305   } else {
5306     Value = Eval.Val;
5307 
5308     if (Notes.empty()) {
5309       // It's a constant expression.
5310       return Result;
5311     }
5312   }
5313 
5314   // It's not a constant expression. Produce an appropriate diagnostic.
5315   if (Notes.size() == 1 &&
5316       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5317     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5318   else {
5319     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5320       << CCE << From->getSourceRange();
5321     for (unsigned I = 0; I < Notes.size(); ++I)
5322       S.Diag(Notes[I].first, Notes[I].second);
5323   }
5324   return ExprError();
5325 }
5326 
5327 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5328                                                   APValue &Value, CCEKind CCE) {
5329   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5330 }
5331 
5332 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5333                                                   llvm::APSInt &Value,
5334                                                   CCEKind CCE) {
5335   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5336 
5337   APValue V;
5338   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5339   if (!R.isInvalid())
5340     Value = V.getInt();
5341   return R;
5342 }
5343 
5344 
5345 /// dropPointerConversions - If the given standard conversion sequence
5346 /// involves any pointer conversions, remove them.  This may change
5347 /// the result type of the conversion sequence.
5348 static void dropPointerConversion(StandardConversionSequence &SCS) {
5349   if (SCS.Second == ICK_Pointer_Conversion) {
5350     SCS.Second = ICK_Identity;
5351     SCS.Third = ICK_Identity;
5352     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5353   }
5354 }
5355 
5356 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5357 /// convert the expression From to an Objective-C pointer type.
5358 static ImplicitConversionSequence
5359 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5360   // Do an implicit conversion to 'id'.
5361   QualType Ty = S.Context.getObjCIdType();
5362   ImplicitConversionSequence ICS
5363     = TryImplicitConversion(S, From, Ty,
5364                             // FIXME: Are these flags correct?
5365                             /*SuppressUserConversions=*/false,
5366                             /*AllowExplicit=*/true,
5367                             /*InOverloadResolution=*/false,
5368                             /*CStyle=*/false,
5369                             /*AllowObjCWritebackConversion=*/false,
5370                             /*AllowObjCConversionOnExplicit=*/true);
5371 
5372   // Strip off any final conversions to 'id'.
5373   switch (ICS.getKind()) {
5374   case ImplicitConversionSequence::BadConversion:
5375   case ImplicitConversionSequence::AmbiguousConversion:
5376   case ImplicitConversionSequence::EllipsisConversion:
5377     break;
5378 
5379   case ImplicitConversionSequence::UserDefinedConversion:
5380     dropPointerConversion(ICS.UserDefined.After);
5381     break;
5382 
5383   case ImplicitConversionSequence::StandardConversion:
5384     dropPointerConversion(ICS.Standard);
5385     break;
5386   }
5387 
5388   return ICS;
5389 }
5390 
5391 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5392 /// conversion of the expression From to an Objective-C pointer type.
5393 /// Returns a valid but null ExprResult if no conversion sequence exists.
5394 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5395   if (checkPlaceholderForOverload(*this, From))
5396     return ExprError();
5397 
5398   QualType Ty = Context.getObjCIdType();
5399   ImplicitConversionSequence ICS =
5400     TryContextuallyConvertToObjCPointer(*this, From);
5401   if (!ICS.isBad())
5402     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5403   return ExprResult();
5404 }
5405 
5406 /// Determine whether the provided type is an integral type, or an enumeration
5407 /// type of a permitted flavor.
5408 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5409   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5410                                  : T->isIntegralOrUnscopedEnumerationType();
5411 }
5412 
5413 static ExprResult
5414 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5415                             Sema::ContextualImplicitConverter &Converter,
5416                             QualType T, UnresolvedSetImpl &ViableConversions) {
5417 
5418   if (Converter.Suppress)
5419     return ExprError();
5420 
5421   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5422   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5423     CXXConversionDecl *Conv =
5424         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5425     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5426     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5427   }
5428   return From;
5429 }
5430 
5431 static bool
5432 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5433                            Sema::ContextualImplicitConverter &Converter,
5434                            QualType T, bool HadMultipleCandidates,
5435                            UnresolvedSetImpl &ExplicitConversions) {
5436   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5437     DeclAccessPair Found = ExplicitConversions[0];
5438     CXXConversionDecl *Conversion =
5439         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5440 
5441     // The user probably meant to invoke the given explicit
5442     // conversion; use it.
5443     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5444     std::string TypeStr;
5445     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5446 
5447     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5448         << FixItHint::CreateInsertion(From->getLocStart(),
5449                                       "static_cast<" + TypeStr + ">(")
5450         << FixItHint::CreateInsertion(
5451                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5452     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5453 
5454     // If we aren't in a SFINAE context, build a call to the
5455     // explicit conversion function.
5456     if (SemaRef.isSFINAEContext())
5457       return true;
5458 
5459     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5460     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5461                                                        HadMultipleCandidates);
5462     if (Result.isInvalid())
5463       return true;
5464     // Record usage of conversion in an implicit cast.
5465     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5466                                     CK_UserDefinedConversion, Result.get(),
5467                                     nullptr, Result.get()->getValueKind());
5468   }
5469   return false;
5470 }
5471 
5472 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5473                              Sema::ContextualImplicitConverter &Converter,
5474                              QualType T, bool HadMultipleCandidates,
5475                              DeclAccessPair &Found) {
5476   CXXConversionDecl *Conversion =
5477       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5478   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5479 
5480   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5481   if (!Converter.SuppressConversion) {
5482     if (SemaRef.isSFINAEContext())
5483       return true;
5484 
5485     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5486         << From->getSourceRange();
5487   }
5488 
5489   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5490                                                      HadMultipleCandidates);
5491   if (Result.isInvalid())
5492     return true;
5493   // Record usage of conversion in an implicit cast.
5494   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5495                                   CK_UserDefinedConversion, Result.get(),
5496                                   nullptr, Result.get()->getValueKind());
5497   return false;
5498 }
5499 
5500 static ExprResult finishContextualImplicitConversion(
5501     Sema &SemaRef, SourceLocation Loc, Expr *From,
5502     Sema::ContextualImplicitConverter &Converter) {
5503   if (!Converter.match(From->getType()) && !Converter.Suppress)
5504     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5505         << From->getSourceRange();
5506 
5507   return SemaRef.DefaultLvalueConversion(From);
5508 }
5509 
5510 static void
5511 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5512                                   UnresolvedSetImpl &ViableConversions,
5513                                   OverloadCandidateSet &CandidateSet) {
5514   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5515     DeclAccessPair FoundDecl = ViableConversions[I];
5516     NamedDecl *D = FoundDecl.getDecl();
5517     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5518     if (isa<UsingShadowDecl>(D))
5519       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5520 
5521     CXXConversionDecl *Conv;
5522     FunctionTemplateDecl *ConvTemplate;
5523     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5524       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5525     else
5526       Conv = cast<CXXConversionDecl>(D);
5527 
5528     if (ConvTemplate)
5529       SemaRef.AddTemplateConversionCandidate(
5530         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5531         /*AllowObjCConversionOnExplicit=*/false);
5532     else
5533       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5534                                      ToType, CandidateSet,
5535                                      /*AllowObjCConversionOnExplicit=*/false);
5536   }
5537 }
5538 
5539 /// \brief Attempt to convert the given expression to a type which is accepted
5540 /// by the given converter.
5541 ///
5542 /// This routine will attempt to convert an expression of class type to a
5543 /// type accepted by the specified converter. In C++11 and before, the class
5544 /// must have a single non-explicit conversion function converting to a matching
5545 /// type. In C++1y, there can be multiple such conversion functions, but only
5546 /// one target type.
5547 ///
5548 /// \param Loc The source location of the construct that requires the
5549 /// conversion.
5550 ///
5551 /// \param From The expression we're converting from.
5552 ///
5553 /// \param Converter Used to control and diagnose the conversion process.
5554 ///
5555 /// \returns The expression, converted to an integral or enumeration type if
5556 /// successful.
5557 ExprResult Sema::PerformContextualImplicitConversion(
5558     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5559   // We can't perform any more checking for type-dependent expressions.
5560   if (From->isTypeDependent())
5561     return From;
5562 
5563   // Process placeholders immediately.
5564   if (From->hasPlaceholderType()) {
5565     ExprResult result = CheckPlaceholderExpr(From);
5566     if (result.isInvalid())
5567       return result;
5568     From = result.get();
5569   }
5570 
5571   // If the expression already has a matching type, we're golden.
5572   QualType T = From->getType();
5573   if (Converter.match(T))
5574     return DefaultLvalueConversion(From);
5575 
5576   // FIXME: Check for missing '()' if T is a function type?
5577 
5578   // We can only perform contextual implicit conversions on objects of class
5579   // type.
5580   const RecordType *RecordTy = T->getAs<RecordType>();
5581   if (!RecordTy || !getLangOpts().CPlusPlus) {
5582     if (!Converter.Suppress)
5583       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5584     return From;
5585   }
5586 
5587   // We must have a complete class type.
5588   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5589     ContextualImplicitConverter &Converter;
5590     Expr *From;
5591 
5592     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5593         : Converter(Converter), From(From) {}
5594 
5595     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5596       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5597     }
5598   } IncompleteDiagnoser(Converter, From);
5599 
5600   if (Converter.Suppress ? !isCompleteType(Loc, T)
5601                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5602     return From;
5603 
5604   // Look for a conversion to an integral or enumeration type.
5605   UnresolvedSet<4>
5606       ViableConversions; // These are *potentially* viable in C++1y.
5607   UnresolvedSet<4> ExplicitConversions;
5608   const auto &Conversions =
5609       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5610 
5611   bool HadMultipleCandidates =
5612       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5613 
5614   // To check that there is only one target type, in C++1y:
5615   QualType ToType;
5616   bool HasUniqueTargetType = true;
5617 
5618   // Collect explicit or viable (potentially in C++1y) conversions.
5619   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5620     NamedDecl *D = (*I)->getUnderlyingDecl();
5621     CXXConversionDecl *Conversion;
5622     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5623     if (ConvTemplate) {
5624       if (getLangOpts().CPlusPlus14)
5625         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5626       else
5627         continue; // C++11 does not consider conversion operator templates(?).
5628     } else
5629       Conversion = cast<CXXConversionDecl>(D);
5630 
5631     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5632            "Conversion operator templates are considered potentially "
5633            "viable in C++1y");
5634 
5635     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5636     if (Converter.match(CurToType) || ConvTemplate) {
5637 
5638       if (Conversion->isExplicit()) {
5639         // FIXME: For C++1y, do we need this restriction?
5640         // cf. diagnoseNoViableConversion()
5641         if (!ConvTemplate)
5642           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5643       } else {
5644         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5645           if (ToType.isNull())
5646             ToType = CurToType.getUnqualifiedType();
5647           else if (HasUniqueTargetType &&
5648                    (CurToType.getUnqualifiedType() != ToType))
5649             HasUniqueTargetType = false;
5650         }
5651         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5652       }
5653     }
5654   }
5655 
5656   if (getLangOpts().CPlusPlus14) {
5657     // C++1y [conv]p6:
5658     // ... An expression e of class type E appearing in such a context
5659     // is said to be contextually implicitly converted to a specified
5660     // type T and is well-formed if and only if e can be implicitly
5661     // converted to a type T that is determined as follows: E is searched
5662     // for conversion functions whose return type is cv T or reference to
5663     // cv T such that T is allowed by the context. There shall be
5664     // exactly one such T.
5665 
5666     // If no unique T is found:
5667     if (ToType.isNull()) {
5668       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5669                                      HadMultipleCandidates,
5670                                      ExplicitConversions))
5671         return ExprError();
5672       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5673     }
5674 
5675     // If more than one unique Ts are found:
5676     if (!HasUniqueTargetType)
5677       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5678                                          ViableConversions);
5679 
5680     // If one unique T is found:
5681     // First, build a candidate set from the previously recorded
5682     // potentially viable conversions.
5683     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5684     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5685                                       CandidateSet);
5686 
5687     // Then, perform overload resolution over the candidate set.
5688     OverloadCandidateSet::iterator Best;
5689     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5690     case OR_Success: {
5691       // Apply this conversion.
5692       DeclAccessPair Found =
5693           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5694       if (recordConversion(*this, Loc, From, Converter, T,
5695                            HadMultipleCandidates, Found))
5696         return ExprError();
5697       break;
5698     }
5699     case OR_Ambiguous:
5700       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5701                                          ViableConversions);
5702     case OR_No_Viable_Function:
5703       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5704                                      HadMultipleCandidates,
5705                                      ExplicitConversions))
5706         return ExprError();
5707     // fall through 'OR_Deleted' case.
5708     case OR_Deleted:
5709       // We'll complain below about a non-integral condition type.
5710       break;
5711     }
5712   } else {
5713     switch (ViableConversions.size()) {
5714     case 0: {
5715       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5716                                      HadMultipleCandidates,
5717                                      ExplicitConversions))
5718         return ExprError();
5719 
5720       // We'll complain below about a non-integral condition type.
5721       break;
5722     }
5723     case 1: {
5724       // Apply this conversion.
5725       DeclAccessPair Found = ViableConversions[0];
5726       if (recordConversion(*this, Loc, From, Converter, T,
5727                            HadMultipleCandidates, Found))
5728         return ExprError();
5729       break;
5730     }
5731     default:
5732       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5733                                          ViableConversions);
5734     }
5735   }
5736 
5737   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5738 }
5739 
5740 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5741 /// an acceptable non-member overloaded operator for a call whose
5742 /// arguments have types T1 (and, if non-empty, T2). This routine
5743 /// implements the check in C++ [over.match.oper]p3b2 concerning
5744 /// enumeration types.
5745 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5746                                                    FunctionDecl *Fn,
5747                                                    ArrayRef<Expr *> Args) {
5748   QualType T1 = Args[0]->getType();
5749   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5750 
5751   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5752     return true;
5753 
5754   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5755     return true;
5756 
5757   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5758   if (Proto->getNumParams() < 1)
5759     return false;
5760 
5761   if (T1->isEnumeralType()) {
5762     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5763     if (Context.hasSameUnqualifiedType(T1, ArgType))
5764       return true;
5765   }
5766 
5767   if (Proto->getNumParams() < 2)
5768     return false;
5769 
5770   if (!T2.isNull() && T2->isEnumeralType()) {
5771     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5772     if (Context.hasSameUnqualifiedType(T2, ArgType))
5773       return true;
5774   }
5775 
5776   return false;
5777 }
5778 
5779 /// AddOverloadCandidate - Adds the given function to the set of
5780 /// candidate functions, using the given function call arguments.  If
5781 /// @p SuppressUserConversions, then don't allow user-defined
5782 /// conversions via constructors or conversion operators.
5783 ///
5784 /// \param PartialOverloading true if we are performing "partial" overloading
5785 /// based on an incomplete set of function arguments. This feature is used by
5786 /// code completion.
5787 void
5788 Sema::AddOverloadCandidate(FunctionDecl *Function,
5789                            DeclAccessPair FoundDecl,
5790                            ArrayRef<Expr *> Args,
5791                            OverloadCandidateSet &CandidateSet,
5792                            bool SuppressUserConversions,
5793                            bool PartialOverloading,
5794                            bool AllowExplicit) {
5795   const FunctionProtoType *Proto
5796     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5797   assert(Proto && "Functions without a prototype cannot be overloaded");
5798   assert(!Function->getDescribedFunctionTemplate() &&
5799          "Use AddTemplateOverloadCandidate for function templates");
5800 
5801   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5802     if (!isa<CXXConstructorDecl>(Method)) {
5803       // If we get here, it's because we're calling a member function
5804       // that is named without a member access expression (e.g.,
5805       // "this->f") that was either written explicitly or created
5806       // implicitly. This can happen with a qualified call to a member
5807       // function, e.g., X::f(). We use an empty type for the implied
5808       // object argument (C++ [over.call.func]p3), and the acting context
5809       // is irrelevant.
5810       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5811                          QualType(), Expr::Classification::makeSimpleLValue(),
5812                          Args, CandidateSet, SuppressUserConversions,
5813                          PartialOverloading);
5814       return;
5815     }
5816     // We treat a constructor like a non-member function, since its object
5817     // argument doesn't participate in overload resolution.
5818   }
5819 
5820   if (!CandidateSet.isNewCandidate(Function))
5821     return;
5822 
5823   // C++ [over.match.oper]p3:
5824   //   if no operand has a class type, only those non-member functions in the
5825   //   lookup set that have a first parameter of type T1 or "reference to
5826   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5827   //   is a right operand) a second parameter of type T2 or "reference to
5828   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5829   //   candidate functions.
5830   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5831       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5832     return;
5833 
5834   // C++11 [class.copy]p11: [DR1402]
5835   //   A defaulted move constructor that is defined as deleted is ignored by
5836   //   overload resolution.
5837   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5838   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5839       Constructor->isMoveConstructor())
5840     return;
5841 
5842   // Overload resolution is always an unevaluated context.
5843   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5844 
5845   // Add this candidate
5846   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5847   Candidate.FoundDecl = FoundDecl;
5848   Candidate.Function = Function;
5849   Candidate.Viable = true;
5850   Candidate.IsSurrogate = false;
5851   Candidate.IgnoreObjectArgument = false;
5852   Candidate.ExplicitCallArguments = Args.size();
5853 
5854   if (Constructor) {
5855     // C++ [class.copy]p3:
5856     //   A member function template is never instantiated to perform the copy
5857     //   of a class object to an object of its class type.
5858     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5859     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5860         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5861          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5862                        ClassType))) {
5863       Candidate.Viable = false;
5864       Candidate.FailureKind = ovl_fail_illegal_constructor;
5865       return;
5866     }
5867   }
5868 
5869   unsigned NumParams = Proto->getNumParams();
5870 
5871   // (C++ 13.3.2p2): A candidate function having fewer than m
5872   // parameters is viable only if it has an ellipsis in its parameter
5873   // list (8.3.5).
5874   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5875       !Proto->isVariadic()) {
5876     Candidate.Viable = false;
5877     Candidate.FailureKind = ovl_fail_too_many_arguments;
5878     return;
5879   }
5880 
5881   // (C++ 13.3.2p2): A candidate function having more than m parameters
5882   // is viable only if the (m+1)st parameter has a default argument
5883   // (8.3.6). For the purposes of overload resolution, the
5884   // parameter list is truncated on the right, so that there are
5885   // exactly m parameters.
5886   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5887   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5888     // Not enough arguments.
5889     Candidate.Viable = false;
5890     Candidate.FailureKind = ovl_fail_too_few_arguments;
5891     return;
5892   }
5893 
5894   // (CUDA B.1): Check for invalid calls between targets.
5895   if (getLangOpts().CUDA)
5896     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5897       // Skip the check for callers that are implicit members, because in this
5898       // case we may not yet know what the member's target is; the target is
5899       // inferred for the member automatically, based on the bases and fields of
5900       // the class.
5901       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5902         Candidate.Viable = false;
5903         Candidate.FailureKind = ovl_fail_bad_target;
5904         return;
5905       }
5906 
5907   // Determine the implicit conversion sequences for each of the
5908   // arguments.
5909   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5910     if (ArgIdx < NumParams) {
5911       // (C++ 13.3.2p3): for F to be a viable function, there shall
5912       // exist for each argument an implicit conversion sequence
5913       // (13.3.3.1) that converts that argument to the corresponding
5914       // parameter of F.
5915       QualType ParamType = Proto->getParamType(ArgIdx);
5916       Candidate.Conversions[ArgIdx]
5917         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5918                                 SuppressUserConversions,
5919                                 /*InOverloadResolution=*/true,
5920                                 /*AllowObjCWritebackConversion=*/
5921                                   getLangOpts().ObjCAutoRefCount,
5922                                 AllowExplicit);
5923       if (Candidate.Conversions[ArgIdx].isBad()) {
5924         Candidate.Viable = false;
5925         Candidate.FailureKind = ovl_fail_bad_conversion;
5926         return;
5927       }
5928     } else {
5929       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5930       // argument for which there is no corresponding parameter is
5931       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5932       Candidate.Conversions[ArgIdx].setEllipsis();
5933     }
5934   }
5935 
5936   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5937     Candidate.Viable = false;
5938     Candidate.FailureKind = ovl_fail_enable_if;
5939     Candidate.DeductionFailure.Data = FailedAttr;
5940     return;
5941   }
5942 }
5943 
5944 ObjCMethodDecl *
5945 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5946                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5947   if (Methods.size() <= 1)
5948     return nullptr;
5949 
5950   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5951     bool Match = true;
5952     ObjCMethodDecl *Method = Methods[b];
5953     unsigned NumNamedArgs = Sel.getNumArgs();
5954     // Method might have more arguments than selector indicates. This is due
5955     // to addition of c-style arguments in method.
5956     if (Method->param_size() > NumNamedArgs)
5957       NumNamedArgs = Method->param_size();
5958     if (Args.size() < NumNamedArgs)
5959       continue;
5960 
5961     for (unsigned i = 0; i < NumNamedArgs; i++) {
5962       // We can't do any type-checking on a type-dependent argument.
5963       if (Args[i]->isTypeDependent()) {
5964         Match = false;
5965         break;
5966       }
5967 
5968       ParmVarDecl *param = Method->parameters()[i];
5969       Expr *argExpr = Args[i];
5970       assert(argExpr && "SelectBestMethod(): missing expression");
5971 
5972       // Strip the unbridged-cast placeholder expression off unless it's
5973       // a consumed argument.
5974       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5975           !param->hasAttr<CFConsumedAttr>())
5976         argExpr = stripARCUnbridgedCast(argExpr);
5977 
5978       // If the parameter is __unknown_anytype, move on to the next method.
5979       if (param->getType() == Context.UnknownAnyTy) {
5980         Match = false;
5981         break;
5982       }
5983 
5984       ImplicitConversionSequence ConversionState
5985         = TryCopyInitialization(*this, argExpr, param->getType(),
5986                                 /*SuppressUserConversions*/false,
5987                                 /*InOverloadResolution=*/true,
5988                                 /*AllowObjCWritebackConversion=*/
5989                                 getLangOpts().ObjCAutoRefCount,
5990                                 /*AllowExplicit*/false);
5991       // This function looks for a reasonably-exact match, so we consider
5992       // incompatible pointer conversions to be a failure here.
5993       if (ConversionState.isBad() ||
5994           (ConversionState.isStandard() &&
5995            ConversionState.Standard.Second ==
5996                ICK_Incompatible_Pointer_Conversion)) {
5997         Match = false;
5998         break;
5999       }
6000     }
6001     // Promote additional arguments to variadic methods.
6002     if (Match && Method->isVariadic()) {
6003       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6004         if (Args[i]->isTypeDependent()) {
6005           Match = false;
6006           break;
6007         }
6008         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6009                                                           nullptr);
6010         if (Arg.isInvalid()) {
6011           Match = false;
6012           break;
6013         }
6014       }
6015     } else {
6016       // Check for extra arguments to non-variadic methods.
6017       if (Args.size() != NumNamedArgs)
6018         Match = false;
6019       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6020         // Special case when selectors have no argument. In this case, select
6021         // one with the most general result type of 'id'.
6022         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6023           QualType ReturnT = Methods[b]->getReturnType();
6024           if (ReturnT->isObjCIdType())
6025             return Methods[b];
6026         }
6027       }
6028     }
6029 
6030     if (Match)
6031       return Method;
6032   }
6033   return nullptr;
6034 }
6035 
6036 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6037 // enable_if is order-sensitive. As a result, we need to reverse things
6038 // sometimes. Size of 4 elements is arbitrary.
6039 static SmallVector<EnableIfAttr *, 4>
6040 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6041   SmallVector<EnableIfAttr *, 4> Result;
6042   if (!Function->hasAttrs())
6043     return Result;
6044 
6045   const auto &FuncAttrs = Function->getAttrs();
6046   for (Attr *Attr : FuncAttrs)
6047     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6048       Result.push_back(EnableIf);
6049 
6050   std::reverse(Result.begin(), Result.end());
6051   return Result;
6052 }
6053 
6054 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6055                                   bool MissingImplicitThis) {
6056   auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6057   if (EnableIfAttrs.empty())
6058     return nullptr;
6059 
6060   SFINAETrap Trap(*this);
6061   SmallVector<Expr *, 16> ConvertedArgs;
6062   bool InitializationFailed = false;
6063 
6064   // Ignore any variadic arguments. Converting them is pointless, since the
6065   // user can't refer to them in the enable_if condition.
6066   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6067 
6068   // Convert the arguments.
6069   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6070     ExprResult R;
6071     if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
6072         !cast<CXXMethodDecl>(Function)->isStatic() &&
6073         !isa<CXXConstructorDecl>(Function)) {
6074       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6075       R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6076                                               Method, Method);
6077     } else {
6078       R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6079                                         Context, Function->getParamDecl(I)),
6080                                     SourceLocation(), Args[I]);
6081     }
6082 
6083     if (R.isInvalid()) {
6084       InitializationFailed = true;
6085       break;
6086     }
6087 
6088     ConvertedArgs.push_back(R.get());
6089   }
6090 
6091   if (InitializationFailed || Trap.hasErrorOccurred())
6092     return EnableIfAttrs[0];
6093 
6094   // Push default arguments if needed.
6095   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6096     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6097       ParmVarDecl *P = Function->getParamDecl(i);
6098       ExprResult R = PerformCopyInitialization(
6099           InitializedEntity::InitializeParameter(Context,
6100                                                  Function->getParamDecl(i)),
6101           SourceLocation(),
6102           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6103                                            : P->getDefaultArg());
6104       if (R.isInvalid()) {
6105         InitializationFailed = true;
6106         break;
6107       }
6108       ConvertedArgs.push_back(R.get());
6109     }
6110 
6111     if (InitializationFailed || Trap.hasErrorOccurred())
6112       return EnableIfAttrs[0];
6113   }
6114 
6115   for (auto *EIA : EnableIfAttrs) {
6116     APValue Result;
6117     // FIXME: This doesn't consider value-dependent cases, because doing so is
6118     // very difficult. Ideally, we should handle them more gracefully.
6119     if (!EIA->getCond()->EvaluateWithSubstitution(
6120             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6121       return EIA;
6122 
6123     if (!Result.isInt() || !Result.getInt().getBoolValue())
6124       return EIA;
6125   }
6126   return nullptr;
6127 }
6128 
6129 /// \brief Add all of the function declarations in the given function set to
6130 /// the overload candidate set.
6131 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6132                                  ArrayRef<Expr *> Args,
6133                                  OverloadCandidateSet& CandidateSet,
6134                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6135                                  bool SuppressUserConversions,
6136                                  bool PartialOverloading) {
6137   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6138     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6139     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6140       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6141         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6142                            cast<CXXMethodDecl>(FD)->getParent(),
6143                            Args[0]->getType(), Args[0]->Classify(Context),
6144                            Args.slice(1), CandidateSet,
6145                            SuppressUserConversions, PartialOverloading);
6146       else
6147         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6148                              SuppressUserConversions, PartialOverloading);
6149     } else {
6150       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6151       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6152           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6153         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6154                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6155                                    ExplicitTemplateArgs,
6156                                    Args[0]->getType(),
6157                                    Args[0]->Classify(Context), Args.slice(1),
6158                                    CandidateSet, SuppressUserConversions,
6159                                    PartialOverloading);
6160       else
6161         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6162                                      ExplicitTemplateArgs, Args,
6163                                      CandidateSet, SuppressUserConversions,
6164                                      PartialOverloading);
6165     }
6166   }
6167 }
6168 
6169 /// AddMethodCandidate - Adds a named decl (which is some kind of
6170 /// method) as a method candidate to the given overload set.
6171 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6172                               QualType ObjectType,
6173                               Expr::Classification ObjectClassification,
6174                               ArrayRef<Expr *> Args,
6175                               OverloadCandidateSet& CandidateSet,
6176                               bool SuppressUserConversions) {
6177   NamedDecl *Decl = FoundDecl.getDecl();
6178   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6179 
6180   if (isa<UsingShadowDecl>(Decl))
6181     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6182 
6183   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6184     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6185            "Expected a member function template");
6186     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6187                                /*ExplicitArgs*/ nullptr,
6188                                ObjectType, ObjectClassification,
6189                                Args, CandidateSet,
6190                                SuppressUserConversions);
6191   } else {
6192     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6193                        ObjectType, ObjectClassification,
6194                        Args,
6195                        CandidateSet, SuppressUserConversions);
6196   }
6197 }
6198 
6199 /// AddMethodCandidate - Adds the given C++ member function to the set
6200 /// of candidate functions, using the given function call arguments
6201 /// and the object argument (@c Object). For example, in a call
6202 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6203 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6204 /// allow user-defined conversions via constructors or conversion
6205 /// operators.
6206 void
6207 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6208                          CXXRecordDecl *ActingContext, QualType ObjectType,
6209                          Expr::Classification ObjectClassification,
6210                          ArrayRef<Expr *> Args,
6211                          OverloadCandidateSet &CandidateSet,
6212                          bool SuppressUserConversions,
6213                          bool PartialOverloading) {
6214   const FunctionProtoType *Proto
6215     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6216   assert(Proto && "Methods without a prototype cannot be overloaded");
6217   assert(!isa<CXXConstructorDecl>(Method) &&
6218          "Use AddOverloadCandidate for constructors");
6219 
6220   if (!CandidateSet.isNewCandidate(Method))
6221     return;
6222 
6223   // C++11 [class.copy]p23: [DR1402]
6224   //   A defaulted move assignment operator that is defined as deleted is
6225   //   ignored by overload resolution.
6226   if (Method->isDefaulted() && Method->isDeleted() &&
6227       Method->isMoveAssignmentOperator())
6228     return;
6229 
6230   // Overload resolution is always an unevaluated context.
6231   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6232 
6233   // Add this candidate
6234   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6235   Candidate.FoundDecl = FoundDecl;
6236   Candidate.Function = Method;
6237   Candidate.IsSurrogate = false;
6238   Candidate.IgnoreObjectArgument = false;
6239   Candidate.ExplicitCallArguments = Args.size();
6240 
6241   unsigned NumParams = Proto->getNumParams();
6242 
6243   // (C++ 13.3.2p2): A candidate function having fewer than m
6244   // parameters is viable only if it has an ellipsis in its parameter
6245   // list (8.3.5).
6246   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6247       !Proto->isVariadic()) {
6248     Candidate.Viable = false;
6249     Candidate.FailureKind = ovl_fail_too_many_arguments;
6250     return;
6251   }
6252 
6253   // (C++ 13.3.2p2): A candidate function having more than m parameters
6254   // is viable only if the (m+1)st parameter has a default argument
6255   // (8.3.6). For the purposes of overload resolution, the
6256   // parameter list is truncated on the right, so that there are
6257   // exactly m parameters.
6258   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6259   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6260     // Not enough arguments.
6261     Candidate.Viable = false;
6262     Candidate.FailureKind = ovl_fail_too_few_arguments;
6263     return;
6264   }
6265 
6266   Candidate.Viable = true;
6267 
6268   if (Method->isStatic() || ObjectType.isNull())
6269     // The implicit object argument is ignored.
6270     Candidate.IgnoreObjectArgument = true;
6271   else {
6272     // Determine the implicit conversion sequence for the object
6273     // parameter.
6274     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6275         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6276         Method, ActingContext);
6277     if (Candidate.Conversions[0].isBad()) {
6278       Candidate.Viable = false;
6279       Candidate.FailureKind = ovl_fail_bad_conversion;
6280       return;
6281     }
6282   }
6283 
6284   // (CUDA B.1): Check for invalid calls between targets.
6285   if (getLangOpts().CUDA)
6286     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6287       if (!IsAllowedCUDACall(Caller, Method)) {
6288         Candidate.Viable = false;
6289         Candidate.FailureKind = ovl_fail_bad_target;
6290         return;
6291       }
6292 
6293   // Determine the implicit conversion sequences for each of the
6294   // arguments.
6295   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6296     if (ArgIdx < NumParams) {
6297       // (C++ 13.3.2p3): for F to be a viable function, there shall
6298       // exist for each argument an implicit conversion sequence
6299       // (13.3.3.1) that converts that argument to the corresponding
6300       // parameter of F.
6301       QualType ParamType = Proto->getParamType(ArgIdx);
6302       Candidate.Conversions[ArgIdx + 1]
6303         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6304                                 SuppressUserConversions,
6305                                 /*InOverloadResolution=*/true,
6306                                 /*AllowObjCWritebackConversion=*/
6307                                   getLangOpts().ObjCAutoRefCount);
6308       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6309         Candidate.Viable = false;
6310         Candidate.FailureKind = ovl_fail_bad_conversion;
6311         return;
6312       }
6313     } else {
6314       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6315       // argument for which there is no corresponding parameter is
6316       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6317       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6318     }
6319   }
6320 
6321   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6322     Candidate.Viable = false;
6323     Candidate.FailureKind = ovl_fail_enable_if;
6324     Candidate.DeductionFailure.Data = FailedAttr;
6325     return;
6326   }
6327 }
6328 
6329 /// \brief Add a C++ member function template as a candidate to the candidate
6330 /// set, using template argument deduction to produce an appropriate member
6331 /// function template specialization.
6332 void
6333 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6334                                  DeclAccessPair FoundDecl,
6335                                  CXXRecordDecl *ActingContext,
6336                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6337                                  QualType ObjectType,
6338                                  Expr::Classification ObjectClassification,
6339                                  ArrayRef<Expr *> Args,
6340                                  OverloadCandidateSet& CandidateSet,
6341                                  bool SuppressUserConversions,
6342                                  bool PartialOverloading) {
6343   if (!CandidateSet.isNewCandidate(MethodTmpl))
6344     return;
6345 
6346   // C++ [over.match.funcs]p7:
6347   //   In each case where a candidate is a function template, candidate
6348   //   function template specializations are generated using template argument
6349   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6350   //   candidate functions in the usual way.113) A given name can refer to one
6351   //   or more function templates and also to a set of overloaded non-template
6352   //   functions. In such a case, the candidate functions generated from each
6353   //   function template are combined with the set of non-template candidate
6354   //   functions.
6355   TemplateDeductionInfo Info(CandidateSet.getLocation());
6356   FunctionDecl *Specialization = nullptr;
6357   if (TemplateDeductionResult Result
6358       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6359                                 Specialization, Info, PartialOverloading)) {
6360     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6361     Candidate.FoundDecl = FoundDecl;
6362     Candidate.Function = MethodTmpl->getTemplatedDecl();
6363     Candidate.Viable = false;
6364     Candidate.FailureKind = ovl_fail_bad_deduction;
6365     Candidate.IsSurrogate = false;
6366     Candidate.IgnoreObjectArgument = false;
6367     Candidate.ExplicitCallArguments = Args.size();
6368     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6369                                                           Info);
6370     return;
6371   }
6372 
6373   // Add the function template specialization produced by template argument
6374   // deduction as a candidate.
6375   assert(Specialization && "Missing member function template specialization?");
6376   assert(isa<CXXMethodDecl>(Specialization) &&
6377          "Specialization is not a member function?");
6378   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6379                      ActingContext, ObjectType, ObjectClassification, Args,
6380                      CandidateSet, SuppressUserConversions, PartialOverloading);
6381 }
6382 
6383 /// \brief Add a C++ function template specialization as a candidate
6384 /// in the candidate set, using template argument deduction to produce
6385 /// an appropriate function template specialization.
6386 void
6387 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6388                                    DeclAccessPair FoundDecl,
6389                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6390                                    ArrayRef<Expr *> Args,
6391                                    OverloadCandidateSet& CandidateSet,
6392                                    bool SuppressUserConversions,
6393                                    bool PartialOverloading) {
6394   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6395     return;
6396 
6397   // C++ [over.match.funcs]p7:
6398   //   In each case where a candidate is a function template, candidate
6399   //   function template specializations are generated using template argument
6400   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6401   //   candidate functions in the usual way.113) A given name can refer to one
6402   //   or more function templates and also to a set of overloaded non-template
6403   //   functions. In such a case, the candidate functions generated from each
6404   //   function template are combined with the set of non-template candidate
6405   //   functions.
6406   TemplateDeductionInfo Info(CandidateSet.getLocation());
6407   FunctionDecl *Specialization = nullptr;
6408   if (TemplateDeductionResult Result
6409         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6410                                   Specialization, Info, PartialOverloading)) {
6411     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6412     Candidate.FoundDecl = FoundDecl;
6413     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6414     Candidate.Viable = false;
6415     Candidate.FailureKind = ovl_fail_bad_deduction;
6416     Candidate.IsSurrogate = false;
6417     Candidate.IgnoreObjectArgument = false;
6418     Candidate.ExplicitCallArguments = Args.size();
6419     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6420                                                           Info);
6421     return;
6422   }
6423 
6424   // Add the function template specialization produced by template argument
6425   // deduction as a candidate.
6426   assert(Specialization && "Missing function template specialization?");
6427   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6428                        SuppressUserConversions, PartialOverloading);
6429 }
6430 
6431 /// Determine whether this is an allowable conversion from the result
6432 /// of an explicit conversion operator to the expected type, per C++
6433 /// [over.match.conv]p1 and [over.match.ref]p1.
6434 ///
6435 /// \param ConvType The return type of the conversion function.
6436 ///
6437 /// \param ToType The type we are converting to.
6438 ///
6439 /// \param AllowObjCPointerConversion Allow a conversion from one
6440 /// Objective-C pointer to another.
6441 ///
6442 /// \returns true if the conversion is allowable, false otherwise.
6443 static bool isAllowableExplicitConversion(Sema &S,
6444                                           QualType ConvType, QualType ToType,
6445                                           bool AllowObjCPointerConversion) {
6446   QualType ToNonRefType = ToType.getNonReferenceType();
6447 
6448   // Easy case: the types are the same.
6449   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6450     return true;
6451 
6452   // Allow qualification conversions.
6453   bool ObjCLifetimeConversion;
6454   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6455                                   ObjCLifetimeConversion))
6456     return true;
6457 
6458   // If we're not allowed to consider Objective-C pointer conversions,
6459   // we're done.
6460   if (!AllowObjCPointerConversion)
6461     return false;
6462 
6463   // Is this an Objective-C pointer conversion?
6464   bool IncompatibleObjC = false;
6465   QualType ConvertedType;
6466   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6467                                    IncompatibleObjC);
6468 }
6469 
6470 /// AddConversionCandidate - Add a C++ conversion function as a
6471 /// candidate in the candidate set (C++ [over.match.conv],
6472 /// C++ [over.match.copy]). From is the expression we're converting from,
6473 /// and ToType is the type that we're eventually trying to convert to
6474 /// (which may or may not be the same type as the type that the
6475 /// conversion function produces).
6476 void
6477 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6478                              DeclAccessPair FoundDecl,
6479                              CXXRecordDecl *ActingContext,
6480                              Expr *From, QualType ToType,
6481                              OverloadCandidateSet& CandidateSet,
6482                              bool AllowObjCConversionOnExplicit) {
6483   assert(!Conversion->getDescribedFunctionTemplate() &&
6484          "Conversion function templates use AddTemplateConversionCandidate");
6485   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6486   if (!CandidateSet.isNewCandidate(Conversion))
6487     return;
6488 
6489   // If the conversion function has an undeduced return type, trigger its
6490   // deduction now.
6491   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6492     if (DeduceReturnType(Conversion, From->getExprLoc()))
6493       return;
6494     ConvType = Conversion->getConversionType().getNonReferenceType();
6495   }
6496 
6497   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6498   // operator is only a candidate if its return type is the target type or
6499   // can be converted to the target type with a qualification conversion.
6500   if (Conversion->isExplicit() &&
6501       !isAllowableExplicitConversion(*this, ConvType, ToType,
6502                                      AllowObjCConversionOnExplicit))
6503     return;
6504 
6505   // Overload resolution is always an unevaluated context.
6506   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6507 
6508   // Add this candidate
6509   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6510   Candidate.FoundDecl = FoundDecl;
6511   Candidate.Function = Conversion;
6512   Candidate.IsSurrogate = false;
6513   Candidate.IgnoreObjectArgument = false;
6514   Candidate.FinalConversion.setAsIdentityConversion();
6515   Candidate.FinalConversion.setFromType(ConvType);
6516   Candidate.FinalConversion.setAllToTypes(ToType);
6517   Candidate.Viable = true;
6518   Candidate.ExplicitCallArguments = 1;
6519 
6520   // C++ [over.match.funcs]p4:
6521   //   For conversion functions, the function is considered to be a member of
6522   //   the class of the implicit implied object argument for the purpose of
6523   //   defining the type of the implicit object parameter.
6524   //
6525   // Determine the implicit conversion sequence for the implicit
6526   // object parameter.
6527   QualType ImplicitParamType = From->getType();
6528   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6529     ImplicitParamType = FromPtrType->getPointeeType();
6530   CXXRecordDecl *ConversionContext
6531     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6532 
6533   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6534       *this, CandidateSet.getLocation(), From->getType(),
6535       From->Classify(Context), Conversion, ConversionContext);
6536 
6537   if (Candidate.Conversions[0].isBad()) {
6538     Candidate.Viable = false;
6539     Candidate.FailureKind = ovl_fail_bad_conversion;
6540     return;
6541   }
6542 
6543   // We won't go through a user-defined type conversion function to convert a
6544   // derived to base as such conversions are given Conversion Rank. They only
6545   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6546   QualType FromCanon
6547     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6548   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6549   if (FromCanon == ToCanon ||
6550       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6551     Candidate.Viable = false;
6552     Candidate.FailureKind = ovl_fail_trivial_conversion;
6553     return;
6554   }
6555 
6556   // To determine what the conversion from the result of calling the
6557   // conversion function to the type we're eventually trying to
6558   // convert to (ToType), we need to synthesize a call to the
6559   // conversion function and attempt copy initialization from it. This
6560   // makes sure that we get the right semantics with respect to
6561   // lvalues/rvalues and the type. Fortunately, we can allocate this
6562   // call on the stack and we don't need its arguments to be
6563   // well-formed.
6564   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6565                             VK_LValue, From->getLocStart());
6566   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6567                                 Context.getPointerType(Conversion->getType()),
6568                                 CK_FunctionToPointerDecay,
6569                                 &ConversionRef, VK_RValue);
6570 
6571   QualType ConversionType = Conversion->getConversionType();
6572   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6573     Candidate.Viable = false;
6574     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6575     return;
6576   }
6577 
6578   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6579 
6580   // Note that it is safe to allocate CallExpr on the stack here because
6581   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6582   // allocator).
6583   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6584   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6585                 From->getLocStart());
6586   ImplicitConversionSequence ICS =
6587     TryCopyInitialization(*this, &Call, ToType,
6588                           /*SuppressUserConversions=*/true,
6589                           /*InOverloadResolution=*/false,
6590                           /*AllowObjCWritebackConversion=*/false);
6591 
6592   switch (ICS.getKind()) {
6593   case ImplicitConversionSequence::StandardConversion:
6594     Candidate.FinalConversion = ICS.Standard;
6595 
6596     // C++ [over.ics.user]p3:
6597     //   If the user-defined conversion is specified by a specialization of a
6598     //   conversion function template, the second standard conversion sequence
6599     //   shall have exact match rank.
6600     if (Conversion->getPrimaryTemplate() &&
6601         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6602       Candidate.Viable = false;
6603       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6604       return;
6605     }
6606 
6607     // C++0x [dcl.init.ref]p5:
6608     //    In the second case, if the reference is an rvalue reference and
6609     //    the second standard conversion sequence of the user-defined
6610     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6611     //    program is ill-formed.
6612     if (ToType->isRValueReferenceType() &&
6613         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6614       Candidate.Viable = false;
6615       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6616       return;
6617     }
6618     break;
6619 
6620   case ImplicitConversionSequence::BadConversion:
6621     Candidate.Viable = false;
6622     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6623     return;
6624 
6625   default:
6626     llvm_unreachable(
6627            "Can only end up with a standard conversion sequence or failure");
6628   }
6629 
6630   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6631     Candidate.Viable = false;
6632     Candidate.FailureKind = ovl_fail_enable_if;
6633     Candidate.DeductionFailure.Data = FailedAttr;
6634     return;
6635   }
6636 }
6637 
6638 /// \brief Adds a conversion function template specialization
6639 /// candidate to the overload set, using template argument deduction
6640 /// to deduce the template arguments of the conversion function
6641 /// template from the type that we are converting to (C++
6642 /// [temp.deduct.conv]).
6643 void
6644 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6645                                      DeclAccessPair FoundDecl,
6646                                      CXXRecordDecl *ActingDC,
6647                                      Expr *From, QualType ToType,
6648                                      OverloadCandidateSet &CandidateSet,
6649                                      bool AllowObjCConversionOnExplicit) {
6650   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6651          "Only conversion function templates permitted here");
6652 
6653   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6654     return;
6655 
6656   TemplateDeductionInfo Info(CandidateSet.getLocation());
6657   CXXConversionDecl *Specialization = nullptr;
6658   if (TemplateDeductionResult Result
6659         = DeduceTemplateArguments(FunctionTemplate, ToType,
6660                                   Specialization, Info)) {
6661     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6662     Candidate.FoundDecl = FoundDecl;
6663     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6664     Candidate.Viable = false;
6665     Candidate.FailureKind = ovl_fail_bad_deduction;
6666     Candidate.IsSurrogate = false;
6667     Candidate.IgnoreObjectArgument = false;
6668     Candidate.ExplicitCallArguments = 1;
6669     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6670                                                           Info);
6671     return;
6672   }
6673 
6674   // Add the conversion function template specialization produced by
6675   // template argument deduction as a candidate.
6676   assert(Specialization && "Missing function template specialization?");
6677   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6678                          CandidateSet, AllowObjCConversionOnExplicit);
6679 }
6680 
6681 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6682 /// converts the given @c Object to a function pointer via the
6683 /// conversion function @c Conversion, and then attempts to call it
6684 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6685 /// the type of function that we'll eventually be calling.
6686 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6687                                  DeclAccessPair FoundDecl,
6688                                  CXXRecordDecl *ActingContext,
6689                                  const FunctionProtoType *Proto,
6690                                  Expr *Object,
6691                                  ArrayRef<Expr *> Args,
6692                                  OverloadCandidateSet& CandidateSet) {
6693   if (!CandidateSet.isNewCandidate(Conversion))
6694     return;
6695 
6696   // Overload resolution is always an unevaluated context.
6697   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6698 
6699   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6700   Candidate.FoundDecl = FoundDecl;
6701   Candidate.Function = nullptr;
6702   Candidate.Surrogate = Conversion;
6703   Candidate.Viable = true;
6704   Candidate.IsSurrogate = true;
6705   Candidate.IgnoreObjectArgument = false;
6706   Candidate.ExplicitCallArguments = Args.size();
6707 
6708   // Determine the implicit conversion sequence for the implicit
6709   // object parameter.
6710   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6711       *this, CandidateSet.getLocation(), Object->getType(),
6712       Object->Classify(Context), Conversion, ActingContext);
6713   if (ObjectInit.isBad()) {
6714     Candidate.Viable = false;
6715     Candidate.FailureKind = ovl_fail_bad_conversion;
6716     Candidate.Conversions[0] = ObjectInit;
6717     return;
6718   }
6719 
6720   // The first conversion is actually a user-defined conversion whose
6721   // first conversion is ObjectInit's standard conversion (which is
6722   // effectively a reference binding). Record it as such.
6723   Candidate.Conversions[0].setUserDefined();
6724   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6725   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6726   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6727   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6728   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6729   Candidate.Conversions[0].UserDefined.After
6730     = Candidate.Conversions[0].UserDefined.Before;
6731   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6732 
6733   // Find the
6734   unsigned NumParams = Proto->getNumParams();
6735 
6736   // (C++ 13.3.2p2): A candidate function having fewer than m
6737   // parameters is viable only if it has an ellipsis in its parameter
6738   // list (8.3.5).
6739   if (Args.size() > NumParams && !Proto->isVariadic()) {
6740     Candidate.Viable = false;
6741     Candidate.FailureKind = ovl_fail_too_many_arguments;
6742     return;
6743   }
6744 
6745   // Function types don't have any default arguments, so just check if
6746   // we have enough arguments.
6747   if (Args.size() < NumParams) {
6748     // Not enough arguments.
6749     Candidate.Viable = false;
6750     Candidate.FailureKind = ovl_fail_too_few_arguments;
6751     return;
6752   }
6753 
6754   // Determine the implicit conversion sequences for each of the
6755   // arguments.
6756   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6757     if (ArgIdx < NumParams) {
6758       // (C++ 13.3.2p3): for F to be a viable function, there shall
6759       // exist for each argument an implicit conversion sequence
6760       // (13.3.3.1) that converts that argument to the corresponding
6761       // parameter of F.
6762       QualType ParamType = Proto->getParamType(ArgIdx);
6763       Candidate.Conversions[ArgIdx + 1]
6764         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6765                                 /*SuppressUserConversions=*/false,
6766                                 /*InOverloadResolution=*/false,
6767                                 /*AllowObjCWritebackConversion=*/
6768                                   getLangOpts().ObjCAutoRefCount);
6769       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6770         Candidate.Viable = false;
6771         Candidate.FailureKind = ovl_fail_bad_conversion;
6772         return;
6773       }
6774     } else {
6775       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6776       // argument for which there is no corresponding parameter is
6777       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6778       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6779     }
6780   }
6781 
6782   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6783     Candidate.Viable = false;
6784     Candidate.FailureKind = ovl_fail_enable_if;
6785     Candidate.DeductionFailure.Data = FailedAttr;
6786     return;
6787   }
6788 }
6789 
6790 /// \brief Add overload candidates for overloaded operators that are
6791 /// member functions.
6792 ///
6793 /// Add the overloaded operator candidates that are member functions
6794 /// for the operator Op that was used in an operator expression such
6795 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6796 /// CandidateSet will store the added overload candidates. (C++
6797 /// [over.match.oper]).
6798 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6799                                        SourceLocation OpLoc,
6800                                        ArrayRef<Expr *> Args,
6801                                        OverloadCandidateSet& CandidateSet,
6802                                        SourceRange OpRange) {
6803   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6804 
6805   // C++ [over.match.oper]p3:
6806   //   For a unary operator @ with an operand of a type whose
6807   //   cv-unqualified version is T1, and for a binary operator @ with
6808   //   a left operand of a type whose cv-unqualified version is T1 and
6809   //   a right operand of a type whose cv-unqualified version is T2,
6810   //   three sets of candidate functions, designated member
6811   //   candidates, non-member candidates and built-in candidates, are
6812   //   constructed as follows:
6813   QualType T1 = Args[0]->getType();
6814 
6815   //     -- If T1 is a complete class type or a class currently being
6816   //        defined, the set of member candidates is the result of the
6817   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6818   //        the set of member candidates is empty.
6819   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6820     // Complete the type if it can be completed.
6821     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6822       return;
6823     // If the type is neither complete nor being defined, bail out now.
6824     if (!T1Rec->getDecl()->getDefinition())
6825       return;
6826 
6827     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6828     LookupQualifiedName(Operators, T1Rec->getDecl());
6829     Operators.suppressDiagnostics();
6830 
6831     for (LookupResult::iterator Oper = Operators.begin(),
6832                              OperEnd = Operators.end();
6833          Oper != OperEnd;
6834          ++Oper)
6835       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6836                          Args[0]->Classify(Context),
6837                          Args.slice(1),
6838                          CandidateSet,
6839                          /* SuppressUserConversions = */ false);
6840   }
6841 }
6842 
6843 /// AddBuiltinCandidate - Add a candidate for a built-in
6844 /// operator. ResultTy and ParamTys are the result and parameter types
6845 /// of the built-in candidate, respectively. Args and NumArgs are the
6846 /// arguments being passed to the candidate. IsAssignmentOperator
6847 /// should be true when this built-in candidate is an assignment
6848 /// operator. NumContextualBoolArguments is the number of arguments
6849 /// (at the beginning of the argument list) that will be contextually
6850 /// converted to bool.
6851 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6852                                ArrayRef<Expr *> Args,
6853                                OverloadCandidateSet& CandidateSet,
6854                                bool IsAssignmentOperator,
6855                                unsigned NumContextualBoolArguments) {
6856   // Overload resolution is always an unevaluated context.
6857   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6858 
6859   // Add this candidate
6860   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6861   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6862   Candidate.Function = nullptr;
6863   Candidate.IsSurrogate = false;
6864   Candidate.IgnoreObjectArgument = false;
6865   Candidate.BuiltinTypes.ResultTy = ResultTy;
6866   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6867     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6868 
6869   // Determine the implicit conversion sequences for each of the
6870   // arguments.
6871   Candidate.Viable = true;
6872   Candidate.ExplicitCallArguments = Args.size();
6873   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6874     // C++ [over.match.oper]p4:
6875     //   For the built-in assignment operators, conversions of the
6876     //   left operand are restricted as follows:
6877     //     -- no temporaries are introduced to hold the left operand, and
6878     //     -- no user-defined conversions are applied to the left
6879     //        operand to achieve a type match with the left-most
6880     //        parameter of a built-in candidate.
6881     //
6882     // We block these conversions by turning off user-defined
6883     // conversions, since that is the only way that initialization of
6884     // a reference to a non-class type can occur from something that
6885     // is not of the same type.
6886     if (ArgIdx < NumContextualBoolArguments) {
6887       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6888              "Contextual conversion to bool requires bool type");
6889       Candidate.Conversions[ArgIdx]
6890         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6891     } else {
6892       Candidate.Conversions[ArgIdx]
6893         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6894                                 ArgIdx == 0 && IsAssignmentOperator,
6895                                 /*InOverloadResolution=*/false,
6896                                 /*AllowObjCWritebackConversion=*/
6897                                   getLangOpts().ObjCAutoRefCount);
6898     }
6899     if (Candidate.Conversions[ArgIdx].isBad()) {
6900       Candidate.Viable = false;
6901       Candidate.FailureKind = ovl_fail_bad_conversion;
6902       break;
6903     }
6904   }
6905 }
6906 
6907 namespace {
6908 
6909 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6910 /// candidate operator functions for built-in operators (C++
6911 /// [over.built]). The types are separated into pointer types and
6912 /// enumeration types.
6913 class BuiltinCandidateTypeSet  {
6914   /// TypeSet - A set of types.
6915   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6916                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
6917 
6918   /// PointerTypes - The set of pointer types that will be used in the
6919   /// built-in candidates.
6920   TypeSet PointerTypes;
6921 
6922   /// MemberPointerTypes - The set of member pointer types that will be
6923   /// used in the built-in candidates.
6924   TypeSet MemberPointerTypes;
6925 
6926   /// EnumerationTypes - The set of enumeration types that will be
6927   /// used in the built-in candidates.
6928   TypeSet EnumerationTypes;
6929 
6930   /// \brief The set of vector types that will be used in the built-in
6931   /// candidates.
6932   TypeSet VectorTypes;
6933 
6934   /// \brief A flag indicating non-record types are viable candidates
6935   bool HasNonRecordTypes;
6936 
6937   /// \brief A flag indicating whether either arithmetic or enumeration types
6938   /// were present in the candidate set.
6939   bool HasArithmeticOrEnumeralTypes;
6940 
6941   /// \brief A flag indicating whether the nullptr type was present in the
6942   /// candidate set.
6943   bool HasNullPtrType;
6944 
6945   /// Sema - The semantic analysis instance where we are building the
6946   /// candidate type set.
6947   Sema &SemaRef;
6948 
6949   /// Context - The AST context in which we will build the type sets.
6950   ASTContext &Context;
6951 
6952   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6953                                                const Qualifiers &VisibleQuals);
6954   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6955 
6956 public:
6957   /// iterator - Iterates through the types that are part of the set.
6958   typedef TypeSet::iterator iterator;
6959 
6960   BuiltinCandidateTypeSet(Sema &SemaRef)
6961     : HasNonRecordTypes(false),
6962       HasArithmeticOrEnumeralTypes(false),
6963       HasNullPtrType(false),
6964       SemaRef(SemaRef),
6965       Context(SemaRef.Context) { }
6966 
6967   void AddTypesConvertedFrom(QualType Ty,
6968                              SourceLocation Loc,
6969                              bool AllowUserConversions,
6970                              bool AllowExplicitConversions,
6971                              const Qualifiers &VisibleTypeConversionsQuals);
6972 
6973   /// pointer_begin - First pointer type found;
6974   iterator pointer_begin() { return PointerTypes.begin(); }
6975 
6976   /// pointer_end - Past the last pointer type found;
6977   iterator pointer_end() { return PointerTypes.end(); }
6978 
6979   /// member_pointer_begin - First member pointer type found;
6980   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6981 
6982   /// member_pointer_end - Past the last member pointer type found;
6983   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6984 
6985   /// enumeration_begin - First enumeration type found;
6986   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6987 
6988   /// enumeration_end - Past the last enumeration type found;
6989   iterator enumeration_end() { return EnumerationTypes.end(); }
6990 
6991   iterator vector_begin() { return VectorTypes.begin(); }
6992   iterator vector_end() { return VectorTypes.end(); }
6993 
6994   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6995   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6996   bool hasNullPtrType() const { return HasNullPtrType; }
6997 };
6998 
6999 } // end anonymous namespace
7000 
7001 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7002 /// the set of pointer types along with any more-qualified variants of
7003 /// that type. For example, if @p Ty is "int const *", this routine
7004 /// will add "int const *", "int const volatile *", "int const
7005 /// restrict *", and "int const volatile restrict *" to the set of
7006 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7007 /// false otherwise.
7008 ///
7009 /// FIXME: what to do about extended qualifiers?
7010 bool
7011 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7012                                              const Qualifiers &VisibleQuals) {
7013 
7014   // Insert this type.
7015   if (!PointerTypes.insert(Ty))
7016     return false;
7017 
7018   QualType PointeeTy;
7019   const PointerType *PointerTy = Ty->getAs<PointerType>();
7020   bool buildObjCPtr = false;
7021   if (!PointerTy) {
7022     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7023     PointeeTy = PTy->getPointeeType();
7024     buildObjCPtr = true;
7025   } else {
7026     PointeeTy = PointerTy->getPointeeType();
7027   }
7028 
7029   // Don't add qualified variants of arrays. For one, they're not allowed
7030   // (the qualifier would sink to the element type), and for another, the
7031   // only overload situation where it matters is subscript or pointer +- int,
7032   // and those shouldn't have qualifier variants anyway.
7033   if (PointeeTy->isArrayType())
7034     return true;
7035 
7036   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7037   bool hasVolatile = VisibleQuals.hasVolatile();
7038   bool hasRestrict = VisibleQuals.hasRestrict();
7039 
7040   // Iterate through all strict supersets of BaseCVR.
7041   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7042     if ((CVR | BaseCVR) != CVR) continue;
7043     // Skip over volatile if no volatile found anywhere in the types.
7044     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7045 
7046     // Skip over restrict if no restrict found anywhere in the types, or if
7047     // the type cannot be restrict-qualified.
7048     if ((CVR & Qualifiers::Restrict) &&
7049         (!hasRestrict ||
7050          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7051       continue;
7052 
7053     // Build qualified pointee type.
7054     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7055 
7056     // Build qualified pointer type.
7057     QualType QPointerTy;
7058     if (!buildObjCPtr)
7059       QPointerTy = Context.getPointerType(QPointeeTy);
7060     else
7061       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7062 
7063     // Insert qualified pointer type.
7064     PointerTypes.insert(QPointerTy);
7065   }
7066 
7067   return true;
7068 }
7069 
7070 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7071 /// to the set of pointer types along with any more-qualified variants of
7072 /// that type. For example, if @p Ty is "int const *", this routine
7073 /// will add "int const *", "int const volatile *", "int const
7074 /// restrict *", and "int const volatile restrict *" to the set of
7075 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7076 /// false otherwise.
7077 ///
7078 /// FIXME: what to do about extended qualifiers?
7079 bool
7080 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7081     QualType Ty) {
7082   // Insert this type.
7083   if (!MemberPointerTypes.insert(Ty))
7084     return false;
7085 
7086   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7087   assert(PointerTy && "type was not a member pointer type!");
7088 
7089   QualType PointeeTy = PointerTy->getPointeeType();
7090   // Don't add qualified variants of arrays. For one, they're not allowed
7091   // (the qualifier would sink to the element type), and for another, the
7092   // only overload situation where it matters is subscript or pointer +- int,
7093   // and those shouldn't have qualifier variants anyway.
7094   if (PointeeTy->isArrayType())
7095     return true;
7096   const Type *ClassTy = PointerTy->getClass();
7097 
7098   // Iterate through all strict supersets of the pointee type's CVR
7099   // qualifiers.
7100   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7101   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7102     if ((CVR | BaseCVR) != CVR) continue;
7103 
7104     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7105     MemberPointerTypes.insert(
7106       Context.getMemberPointerType(QPointeeTy, ClassTy));
7107   }
7108 
7109   return true;
7110 }
7111 
7112 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7113 /// Ty can be implicit converted to the given set of @p Types. We're
7114 /// primarily interested in pointer types and enumeration types. We also
7115 /// take member pointer types, for the conditional operator.
7116 /// AllowUserConversions is true if we should look at the conversion
7117 /// functions of a class type, and AllowExplicitConversions if we
7118 /// should also include the explicit conversion functions of a class
7119 /// type.
7120 void
7121 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7122                                                SourceLocation Loc,
7123                                                bool AllowUserConversions,
7124                                                bool AllowExplicitConversions,
7125                                                const Qualifiers &VisibleQuals) {
7126   // Only deal with canonical types.
7127   Ty = Context.getCanonicalType(Ty);
7128 
7129   // Look through reference types; they aren't part of the type of an
7130   // expression for the purposes of conversions.
7131   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7132     Ty = RefTy->getPointeeType();
7133 
7134   // If we're dealing with an array type, decay to the pointer.
7135   if (Ty->isArrayType())
7136     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7137 
7138   // Otherwise, we don't care about qualifiers on the type.
7139   Ty = Ty.getLocalUnqualifiedType();
7140 
7141   // Flag if we ever add a non-record type.
7142   const RecordType *TyRec = Ty->getAs<RecordType>();
7143   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7144 
7145   // Flag if we encounter an arithmetic type.
7146   HasArithmeticOrEnumeralTypes =
7147     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7148 
7149   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7150     PointerTypes.insert(Ty);
7151   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7152     // Insert our type, and its more-qualified variants, into the set
7153     // of types.
7154     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7155       return;
7156   } else if (Ty->isMemberPointerType()) {
7157     // Member pointers are far easier, since the pointee can't be converted.
7158     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7159       return;
7160   } else if (Ty->isEnumeralType()) {
7161     HasArithmeticOrEnumeralTypes = true;
7162     EnumerationTypes.insert(Ty);
7163   } else if (Ty->isVectorType()) {
7164     // We treat vector types as arithmetic types in many contexts as an
7165     // extension.
7166     HasArithmeticOrEnumeralTypes = true;
7167     VectorTypes.insert(Ty);
7168   } else if (Ty->isNullPtrType()) {
7169     HasNullPtrType = true;
7170   } else if (AllowUserConversions && TyRec) {
7171     // No conversion functions in incomplete types.
7172     if (!SemaRef.isCompleteType(Loc, Ty))
7173       return;
7174 
7175     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7176     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7177       if (isa<UsingShadowDecl>(D))
7178         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7179 
7180       // Skip conversion function templates; they don't tell us anything
7181       // about which builtin types we can convert to.
7182       if (isa<FunctionTemplateDecl>(D))
7183         continue;
7184 
7185       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7186       if (AllowExplicitConversions || !Conv->isExplicit()) {
7187         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7188                               VisibleQuals);
7189       }
7190     }
7191   }
7192 }
7193 
7194 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7195 /// the volatile- and non-volatile-qualified assignment operators for the
7196 /// given type to the candidate set.
7197 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7198                                                    QualType T,
7199                                                    ArrayRef<Expr *> Args,
7200                                     OverloadCandidateSet &CandidateSet) {
7201   QualType ParamTypes[2];
7202 
7203   // T& operator=(T&, T)
7204   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7205   ParamTypes[1] = T;
7206   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7207                         /*IsAssignmentOperator=*/true);
7208 
7209   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7210     // volatile T& operator=(volatile T&, T)
7211     ParamTypes[0]
7212       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7213     ParamTypes[1] = T;
7214     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7215                           /*IsAssignmentOperator=*/true);
7216   }
7217 }
7218 
7219 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7220 /// if any, found in visible type conversion functions found in ArgExpr's type.
7221 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7222     Qualifiers VRQuals;
7223     const RecordType *TyRec;
7224     if (const MemberPointerType *RHSMPType =
7225         ArgExpr->getType()->getAs<MemberPointerType>())
7226       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7227     else
7228       TyRec = ArgExpr->getType()->getAs<RecordType>();
7229     if (!TyRec) {
7230       // Just to be safe, assume the worst case.
7231       VRQuals.addVolatile();
7232       VRQuals.addRestrict();
7233       return VRQuals;
7234     }
7235 
7236     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7237     if (!ClassDecl->hasDefinition())
7238       return VRQuals;
7239 
7240     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7241       if (isa<UsingShadowDecl>(D))
7242         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7243       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7244         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7245         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7246           CanTy = ResTypeRef->getPointeeType();
7247         // Need to go down the pointer/mempointer chain and add qualifiers
7248         // as see them.
7249         bool done = false;
7250         while (!done) {
7251           if (CanTy.isRestrictQualified())
7252             VRQuals.addRestrict();
7253           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7254             CanTy = ResTypePtr->getPointeeType();
7255           else if (const MemberPointerType *ResTypeMPtr =
7256                 CanTy->getAs<MemberPointerType>())
7257             CanTy = ResTypeMPtr->getPointeeType();
7258           else
7259             done = true;
7260           if (CanTy.isVolatileQualified())
7261             VRQuals.addVolatile();
7262           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7263             return VRQuals;
7264         }
7265       }
7266     }
7267     return VRQuals;
7268 }
7269 
7270 namespace {
7271 
7272 /// \brief Helper class to manage the addition of builtin operator overload
7273 /// candidates. It provides shared state and utility methods used throughout
7274 /// the process, as well as a helper method to add each group of builtin
7275 /// operator overloads from the standard to a candidate set.
7276 class BuiltinOperatorOverloadBuilder {
7277   // Common instance state available to all overload candidate addition methods.
7278   Sema &S;
7279   ArrayRef<Expr *> Args;
7280   Qualifiers VisibleTypeConversionsQuals;
7281   bool HasArithmeticOrEnumeralCandidateType;
7282   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7283   OverloadCandidateSet &CandidateSet;
7284 
7285   // Define some constants used to index and iterate over the arithemetic types
7286   // provided via the getArithmeticType() method below.
7287   // The "promoted arithmetic types" are the arithmetic
7288   // types are that preserved by promotion (C++ [over.built]p2).
7289   static const unsigned FirstIntegralType = 4;
7290   static const unsigned LastIntegralType = 21;
7291   static const unsigned FirstPromotedIntegralType = 4,
7292                         LastPromotedIntegralType = 12;
7293   static const unsigned FirstPromotedArithmeticType = 0,
7294                         LastPromotedArithmeticType = 12;
7295   static const unsigned NumArithmeticTypes = 21;
7296 
7297   /// \brief Get the canonical type for a given arithmetic type index.
7298   CanQualType getArithmeticType(unsigned index) {
7299     assert(index < NumArithmeticTypes);
7300     static CanQualType ASTContext::* const
7301       ArithmeticTypes[NumArithmeticTypes] = {
7302       // Start of promoted types.
7303       &ASTContext::FloatTy,
7304       &ASTContext::DoubleTy,
7305       &ASTContext::LongDoubleTy,
7306       &ASTContext::Float128Ty,
7307 
7308       // Start of integral types.
7309       &ASTContext::IntTy,
7310       &ASTContext::LongTy,
7311       &ASTContext::LongLongTy,
7312       &ASTContext::Int128Ty,
7313       &ASTContext::UnsignedIntTy,
7314       &ASTContext::UnsignedLongTy,
7315       &ASTContext::UnsignedLongLongTy,
7316       &ASTContext::UnsignedInt128Ty,
7317       // End of promoted types.
7318 
7319       &ASTContext::BoolTy,
7320       &ASTContext::CharTy,
7321       &ASTContext::WCharTy,
7322       &ASTContext::Char16Ty,
7323       &ASTContext::Char32Ty,
7324       &ASTContext::SignedCharTy,
7325       &ASTContext::ShortTy,
7326       &ASTContext::UnsignedCharTy,
7327       &ASTContext::UnsignedShortTy,
7328       // End of integral types.
7329       // FIXME: What about complex? What about half?
7330     };
7331     return S.Context.*ArithmeticTypes[index];
7332   }
7333 
7334   /// \brief Gets the canonical type resulting from the usual arithemetic
7335   /// converions for the given arithmetic types.
7336   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7337     // Accelerator table for performing the usual arithmetic conversions.
7338     // The rules are basically:
7339     //   - if either is floating-point, use the wider floating-point
7340     //   - if same signedness, use the higher rank
7341     //   - if same size, use unsigned of the higher rank
7342     //   - use the larger type
7343     // These rules, together with the axiom that higher ranks are
7344     // never smaller, are sufficient to precompute all of these results
7345     // *except* when dealing with signed types of higher rank.
7346     // (we could precompute SLL x UI for all known platforms, but it's
7347     // better not to make any assumptions).
7348     // We assume that int128 has a higher rank than long long on all platforms.
7349     enum PromotedType : int8_t {
7350             Dep=-1,
7351             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7352     };
7353     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7354                                         [LastPromotedArithmeticType] = {
7355 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7356 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7357 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7358 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7359 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7360 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7361 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7362 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7363 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7364 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7365 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7366     };
7367 
7368     assert(L < LastPromotedArithmeticType);
7369     assert(R < LastPromotedArithmeticType);
7370     int Idx = ConversionsTable[L][R];
7371 
7372     // Fast path: the table gives us a concrete answer.
7373     if (Idx != Dep) return getArithmeticType(Idx);
7374 
7375     // Slow path: we need to compare widths.
7376     // An invariant is that the signed type has higher rank.
7377     CanQualType LT = getArithmeticType(L),
7378                 RT = getArithmeticType(R);
7379     unsigned LW = S.Context.getIntWidth(LT),
7380              RW = S.Context.getIntWidth(RT);
7381 
7382     // If they're different widths, use the signed type.
7383     if (LW > RW) return LT;
7384     else if (LW < RW) return RT;
7385 
7386     // Otherwise, use the unsigned type of the signed type's rank.
7387     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7388     assert(L == SLL || R == SLL);
7389     return S.Context.UnsignedLongLongTy;
7390   }
7391 
7392   /// \brief Helper method to factor out the common pattern of adding overloads
7393   /// for '++' and '--' builtin operators.
7394   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7395                                            bool HasVolatile,
7396                                            bool HasRestrict) {
7397     QualType ParamTypes[2] = {
7398       S.Context.getLValueReferenceType(CandidateTy),
7399       S.Context.IntTy
7400     };
7401 
7402     // Non-volatile version.
7403     if (Args.size() == 1)
7404       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7405     else
7406       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7407 
7408     // Use a heuristic to reduce number of builtin candidates in the set:
7409     // add volatile version only if there are conversions to a volatile type.
7410     if (HasVolatile) {
7411       ParamTypes[0] =
7412         S.Context.getLValueReferenceType(
7413           S.Context.getVolatileType(CandidateTy));
7414       if (Args.size() == 1)
7415         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7416       else
7417         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7418     }
7419 
7420     // Add restrict version only if there are conversions to a restrict type
7421     // and our candidate type is a non-restrict-qualified pointer.
7422     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7423         !CandidateTy.isRestrictQualified()) {
7424       ParamTypes[0]
7425         = S.Context.getLValueReferenceType(
7426             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7427       if (Args.size() == 1)
7428         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7429       else
7430         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7431 
7432       if (HasVolatile) {
7433         ParamTypes[0]
7434           = S.Context.getLValueReferenceType(
7435               S.Context.getCVRQualifiedType(CandidateTy,
7436                                             (Qualifiers::Volatile |
7437                                              Qualifiers::Restrict)));
7438         if (Args.size() == 1)
7439           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7440         else
7441           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7442       }
7443     }
7444 
7445   }
7446 
7447 public:
7448   BuiltinOperatorOverloadBuilder(
7449     Sema &S, ArrayRef<Expr *> Args,
7450     Qualifiers VisibleTypeConversionsQuals,
7451     bool HasArithmeticOrEnumeralCandidateType,
7452     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7453     OverloadCandidateSet &CandidateSet)
7454     : S(S), Args(Args),
7455       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7456       HasArithmeticOrEnumeralCandidateType(
7457         HasArithmeticOrEnumeralCandidateType),
7458       CandidateTypes(CandidateTypes),
7459       CandidateSet(CandidateSet) {
7460     // Validate some of our static helper constants in debug builds.
7461     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7462            "Invalid first promoted integral type");
7463     assert(getArithmeticType(LastPromotedIntegralType - 1)
7464              == S.Context.UnsignedInt128Ty &&
7465            "Invalid last promoted integral type");
7466     assert(getArithmeticType(FirstPromotedArithmeticType)
7467              == S.Context.FloatTy &&
7468            "Invalid first promoted arithmetic type");
7469     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7470              == S.Context.UnsignedInt128Ty &&
7471            "Invalid last promoted arithmetic type");
7472   }
7473 
7474   // C++ [over.built]p3:
7475   //
7476   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7477   //   is either volatile or empty, there exist candidate operator
7478   //   functions of the form
7479   //
7480   //       VQ T&      operator++(VQ T&);
7481   //       T          operator++(VQ T&, int);
7482   //
7483   // C++ [over.built]p4:
7484   //
7485   //   For every pair (T, VQ), where T is an arithmetic type other
7486   //   than bool, and VQ is either volatile or empty, there exist
7487   //   candidate operator functions of the form
7488   //
7489   //       VQ T&      operator--(VQ T&);
7490   //       T          operator--(VQ T&, int);
7491   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7492     if (!HasArithmeticOrEnumeralCandidateType)
7493       return;
7494 
7495     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7496          Arith < NumArithmeticTypes; ++Arith) {
7497       addPlusPlusMinusMinusStyleOverloads(
7498         getArithmeticType(Arith),
7499         VisibleTypeConversionsQuals.hasVolatile(),
7500         VisibleTypeConversionsQuals.hasRestrict());
7501     }
7502   }
7503 
7504   // C++ [over.built]p5:
7505   //
7506   //   For every pair (T, VQ), where T is a cv-qualified or
7507   //   cv-unqualified object type, and VQ is either volatile or
7508   //   empty, there exist candidate operator functions of the form
7509   //
7510   //       T*VQ&      operator++(T*VQ&);
7511   //       T*VQ&      operator--(T*VQ&);
7512   //       T*         operator++(T*VQ&, int);
7513   //       T*         operator--(T*VQ&, int);
7514   void addPlusPlusMinusMinusPointerOverloads() {
7515     for (BuiltinCandidateTypeSet::iterator
7516               Ptr = CandidateTypes[0].pointer_begin(),
7517            PtrEnd = CandidateTypes[0].pointer_end();
7518          Ptr != PtrEnd; ++Ptr) {
7519       // Skip pointer types that aren't pointers to object types.
7520       if (!(*Ptr)->getPointeeType()->isObjectType())
7521         continue;
7522 
7523       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7524         (!(*Ptr).isVolatileQualified() &&
7525          VisibleTypeConversionsQuals.hasVolatile()),
7526         (!(*Ptr).isRestrictQualified() &&
7527          VisibleTypeConversionsQuals.hasRestrict()));
7528     }
7529   }
7530 
7531   // C++ [over.built]p6:
7532   //   For every cv-qualified or cv-unqualified object type T, there
7533   //   exist candidate operator functions of the form
7534   //
7535   //       T&         operator*(T*);
7536   //
7537   // C++ [over.built]p7:
7538   //   For every function type T that does not have cv-qualifiers or a
7539   //   ref-qualifier, there exist candidate operator functions of the form
7540   //       T&         operator*(T*);
7541   void addUnaryStarPointerOverloads() {
7542     for (BuiltinCandidateTypeSet::iterator
7543               Ptr = CandidateTypes[0].pointer_begin(),
7544            PtrEnd = CandidateTypes[0].pointer_end();
7545          Ptr != PtrEnd; ++Ptr) {
7546       QualType ParamTy = *Ptr;
7547       QualType PointeeTy = ParamTy->getPointeeType();
7548       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7549         continue;
7550 
7551       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7552         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7553           continue;
7554 
7555       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7556                             &ParamTy, Args, CandidateSet);
7557     }
7558   }
7559 
7560   // C++ [over.built]p9:
7561   //  For every promoted arithmetic type T, there exist candidate
7562   //  operator functions of the form
7563   //
7564   //       T         operator+(T);
7565   //       T         operator-(T);
7566   void addUnaryPlusOrMinusArithmeticOverloads() {
7567     if (!HasArithmeticOrEnumeralCandidateType)
7568       return;
7569 
7570     for (unsigned Arith = FirstPromotedArithmeticType;
7571          Arith < LastPromotedArithmeticType; ++Arith) {
7572       QualType ArithTy = getArithmeticType(Arith);
7573       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7574     }
7575 
7576     // Extension: We also add these operators for vector types.
7577     for (BuiltinCandidateTypeSet::iterator
7578               Vec = CandidateTypes[0].vector_begin(),
7579            VecEnd = CandidateTypes[0].vector_end();
7580          Vec != VecEnd; ++Vec) {
7581       QualType VecTy = *Vec;
7582       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7583     }
7584   }
7585 
7586   // C++ [over.built]p8:
7587   //   For every type T, there exist candidate operator functions of
7588   //   the form
7589   //
7590   //       T*         operator+(T*);
7591   void addUnaryPlusPointerOverloads() {
7592     for (BuiltinCandidateTypeSet::iterator
7593               Ptr = CandidateTypes[0].pointer_begin(),
7594            PtrEnd = CandidateTypes[0].pointer_end();
7595          Ptr != PtrEnd; ++Ptr) {
7596       QualType ParamTy = *Ptr;
7597       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7598     }
7599   }
7600 
7601   // C++ [over.built]p10:
7602   //   For every promoted integral type T, there exist candidate
7603   //   operator functions of the form
7604   //
7605   //        T         operator~(T);
7606   void addUnaryTildePromotedIntegralOverloads() {
7607     if (!HasArithmeticOrEnumeralCandidateType)
7608       return;
7609 
7610     for (unsigned Int = FirstPromotedIntegralType;
7611          Int < LastPromotedIntegralType; ++Int) {
7612       QualType IntTy = getArithmeticType(Int);
7613       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7614     }
7615 
7616     // Extension: We also add this operator for vector types.
7617     for (BuiltinCandidateTypeSet::iterator
7618               Vec = CandidateTypes[0].vector_begin(),
7619            VecEnd = CandidateTypes[0].vector_end();
7620          Vec != VecEnd; ++Vec) {
7621       QualType VecTy = *Vec;
7622       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7623     }
7624   }
7625 
7626   // C++ [over.match.oper]p16:
7627   //   For every pointer to member type T, there exist candidate operator
7628   //   functions of the form
7629   //
7630   //        bool operator==(T,T);
7631   //        bool operator!=(T,T);
7632   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7633     /// Set of (canonical) types that we've already handled.
7634     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7635 
7636     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7637       for (BuiltinCandidateTypeSet::iterator
7638                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7639              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7640            MemPtr != MemPtrEnd;
7641            ++MemPtr) {
7642         // Don't add the same builtin candidate twice.
7643         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7644           continue;
7645 
7646         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7647         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7648       }
7649     }
7650   }
7651 
7652   // C++ [over.built]p15:
7653   //
7654   //   For every T, where T is an enumeration type, a pointer type, or
7655   //   std::nullptr_t, there exist candidate operator functions of the form
7656   //
7657   //        bool       operator<(T, T);
7658   //        bool       operator>(T, T);
7659   //        bool       operator<=(T, T);
7660   //        bool       operator>=(T, T);
7661   //        bool       operator==(T, T);
7662   //        bool       operator!=(T, T);
7663   void addRelationalPointerOrEnumeralOverloads() {
7664     // C++ [over.match.oper]p3:
7665     //   [...]the built-in candidates include all of the candidate operator
7666     //   functions defined in 13.6 that, compared to the given operator, [...]
7667     //   do not have the same parameter-type-list as any non-template non-member
7668     //   candidate.
7669     //
7670     // Note that in practice, this only affects enumeration types because there
7671     // aren't any built-in candidates of record type, and a user-defined operator
7672     // must have an operand of record or enumeration type. Also, the only other
7673     // overloaded operator with enumeration arguments, operator=,
7674     // cannot be overloaded for enumeration types, so this is the only place
7675     // where we must suppress candidates like this.
7676     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7677       UserDefinedBinaryOperators;
7678 
7679     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7680       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7681           CandidateTypes[ArgIdx].enumeration_end()) {
7682         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7683                                          CEnd = CandidateSet.end();
7684              C != CEnd; ++C) {
7685           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7686             continue;
7687 
7688           if (C->Function->isFunctionTemplateSpecialization())
7689             continue;
7690 
7691           QualType FirstParamType =
7692             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7693           QualType SecondParamType =
7694             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7695 
7696           // Skip if either parameter isn't of enumeral type.
7697           if (!FirstParamType->isEnumeralType() ||
7698               !SecondParamType->isEnumeralType())
7699             continue;
7700 
7701           // Add this operator to the set of known user-defined operators.
7702           UserDefinedBinaryOperators.insert(
7703             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7704                            S.Context.getCanonicalType(SecondParamType)));
7705         }
7706       }
7707     }
7708 
7709     /// Set of (canonical) types that we've already handled.
7710     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7711 
7712     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7713       for (BuiltinCandidateTypeSet::iterator
7714                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7715              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7716            Ptr != PtrEnd; ++Ptr) {
7717         // Don't add the same builtin candidate twice.
7718         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7719           continue;
7720 
7721         QualType ParamTypes[2] = { *Ptr, *Ptr };
7722         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7723       }
7724       for (BuiltinCandidateTypeSet::iterator
7725                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7726              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7727            Enum != EnumEnd; ++Enum) {
7728         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7729 
7730         // Don't add the same builtin candidate twice, or if a user defined
7731         // candidate exists.
7732         if (!AddedTypes.insert(CanonType).second ||
7733             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7734                                                             CanonType)))
7735           continue;
7736 
7737         QualType ParamTypes[2] = { *Enum, *Enum };
7738         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7739       }
7740 
7741       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7742         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7743         if (AddedTypes.insert(NullPtrTy).second &&
7744             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7745                                                              NullPtrTy))) {
7746           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7747           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7748                                 CandidateSet);
7749         }
7750       }
7751     }
7752   }
7753 
7754   // C++ [over.built]p13:
7755   //
7756   //   For every cv-qualified or cv-unqualified object type T
7757   //   there exist candidate operator functions of the form
7758   //
7759   //      T*         operator+(T*, ptrdiff_t);
7760   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7761   //      T*         operator-(T*, ptrdiff_t);
7762   //      T*         operator+(ptrdiff_t, T*);
7763   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7764   //
7765   // C++ [over.built]p14:
7766   //
7767   //   For every T, where T is a pointer to object type, there
7768   //   exist candidate operator functions of the form
7769   //
7770   //      ptrdiff_t  operator-(T, T);
7771   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7772     /// Set of (canonical) types that we've already handled.
7773     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7774 
7775     for (int Arg = 0; Arg < 2; ++Arg) {
7776       QualType AsymmetricParamTypes[2] = {
7777         S.Context.getPointerDiffType(),
7778         S.Context.getPointerDiffType(),
7779       };
7780       for (BuiltinCandidateTypeSet::iterator
7781                 Ptr = CandidateTypes[Arg].pointer_begin(),
7782              PtrEnd = CandidateTypes[Arg].pointer_end();
7783            Ptr != PtrEnd; ++Ptr) {
7784         QualType PointeeTy = (*Ptr)->getPointeeType();
7785         if (!PointeeTy->isObjectType())
7786           continue;
7787 
7788         AsymmetricParamTypes[Arg] = *Ptr;
7789         if (Arg == 0 || Op == OO_Plus) {
7790           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7791           // T* operator+(ptrdiff_t, T*);
7792           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7793         }
7794         if (Op == OO_Minus) {
7795           // ptrdiff_t operator-(T, T);
7796           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7797             continue;
7798 
7799           QualType ParamTypes[2] = { *Ptr, *Ptr };
7800           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7801                                 Args, CandidateSet);
7802         }
7803       }
7804     }
7805   }
7806 
7807   // C++ [over.built]p12:
7808   //
7809   //   For every pair of promoted arithmetic types L and R, there
7810   //   exist candidate operator functions of the form
7811   //
7812   //        LR         operator*(L, R);
7813   //        LR         operator/(L, R);
7814   //        LR         operator+(L, R);
7815   //        LR         operator-(L, R);
7816   //        bool       operator<(L, R);
7817   //        bool       operator>(L, R);
7818   //        bool       operator<=(L, R);
7819   //        bool       operator>=(L, R);
7820   //        bool       operator==(L, R);
7821   //        bool       operator!=(L, R);
7822   //
7823   //   where LR is the result of the usual arithmetic conversions
7824   //   between types L and R.
7825   //
7826   // C++ [over.built]p24:
7827   //
7828   //   For every pair of promoted arithmetic types L and R, there exist
7829   //   candidate operator functions of the form
7830   //
7831   //        LR       operator?(bool, L, R);
7832   //
7833   //   where LR is the result of the usual arithmetic conversions
7834   //   between types L and R.
7835   // Our candidates ignore the first parameter.
7836   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7837     if (!HasArithmeticOrEnumeralCandidateType)
7838       return;
7839 
7840     for (unsigned Left = FirstPromotedArithmeticType;
7841          Left < LastPromotedArithmeticType; ++Left) {
7842       for (unsigned Right = FirstPromotedArithmeticType;
7843            Right < LastPromotedArithmeticType; ++Right) {
7844         QualType LandR[2] = { getArithmeticType(Left),
7845                               getArithmeticType(Right) };
7846         QualType Result =
7847           isComparison ? S.Context.BoolTy
7848                        : getUsualArithmeticConversions(Left, Right);
7849         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7850       }
7851     }
7852 
7853     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7854     // conditional operator for vector types.
7855     for (BuiltinCandidateTypeSet::iterator
7856               Vec1 = CandidateTypes[0].vector_begin(),
7857            Vec1End = CandidateTypes[0].vector_end();
7858          Vec1 != Vec1End; ++Vec1) {
7859       for (BuiltinCandidateTypeSet::iterator
7860                 Vec2 = CandidateTypes[1].vector_begin(),
7861              Vec2End = CandidateTypes[1].vector_end();
7862            Vec2 != Vec2End; ++Vec2) {
7863         QualType LandR[2] = { *Vec1, *Vec2 };
7864         QualType Result = S.Context.BoolTy;
7865         if (!isComparison) {
7866           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7867             Result = *Vec1;
7868           else
7869             Result = *Vec2;
7870         }
7871 
7872         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7873       }
7874     }
7875   }
7876 
7877   // C++ [over.built]p17:
7878   //
7879   //   For every pair of promoted integral types L and R, there
7880   //   exist candidate operator functions of the form
7881   //
7882   //      LR         operator%(L, R);
7883   //      LR         operator&(L, R);
7884   //      LR         operator^(L, R);
7885   //      LR         operator|(L, R);
7886   //      L          operator<<(L, R);
7887   //      L          operator>>(L, R);
7888   //
7889   //   where LR is the result of the usual arithmetic conversions
7890   //   between types L and R.
7891   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7892     if (!HasArithmeticOrEnumeralCandidateType)
7893       return;
7894 
7895     for (unsigned Left = FirstPromotedIntegralType;
7896          Left < LastPromotedIntegralType; ++Left) {
7897       for (unsigned Right = FirstPromotedIntegralType;
7898            Right < LastPromotedIntegralType; ++Right) {
7899         QualType LandR[2] = { getArithmeticType(Left),
7900                               getArithmeticType(Right) };
7901         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7902             ? LandR[0]
7903             : getUsualArithmeticConversions(Left, Right);
7904         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7905       }
7906     }
7907   }
7908 
7909   // C++ [over.built]p20:
7910   //
7911   //   For every pair (T, VQ), where T is an enumeration or
7912   //   pointer to member type and VQ is either volatile or
7913   //   empty, there exist candidate operator functions of the form
7914   //
7915   //        VQ T&      operator=(VQ T&, T);
7916   void addAssignmentMemberPointerOrEnumeralOverloads() {
7917     /// Set of (canonical) types that we've already handled.
7918     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7919 
7920     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7921       for (BuiltinCandidateTypeSet::iterator
7922                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7923              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7924            Enum != EnumEnd; ++Enum) {
7925         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7926           continue;
7927 
7928         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7929       }
7930 
7931       for (BuiltinCandidateTypeSet::iterator
7932                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7933              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7934            MemPtr != MemPtrEnd; ++MemPtr) {
7935         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7936           continue;
7937 
7938         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7939       }
7940     }
7941   }
7942 
7943   // C++ [over.built]p19:
7944   //
7945   //   For every pair (T, VQ), where T is any type and VQ is either
7946   //   volatile or empty, there exist candidate operator functions
7947   //   of the form
7948   //
7949   //        T*VQ&      operator=(T*VQ&, T*);
7950   //
7951   // C++ [over.built]p21:
7952   //
7953   //   For every pair (T, VQ), where T is a cv-qualified or
7954   //   cv-unqualified object type and VQ is either volatile or
7955   //   empty, there exist candidate operator functions of the form
7956   //
7957   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7958   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7959   void addAssignmentPointerOverloads(bool isEqualOp) {
7960     /// Set of (canonical) types that we've already handled.
7961     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7962 
7963     for (BuiltinCandidateTypeSet::iterator
7964               Ptr = CandidateTypes[0].pointer_begin(),
7965            PtrEnd = CandidateTypes[0].pointer_end();
7966          Ptr != PtrEnd; ++Ptr) {
7967       // If this is operator=, keep track of the builtin candidates we added.
7968       if (isEqualOp)
7969         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7970       else if (!(*Ptr)->getPointeeType()->isObjectType())
7971         continue;
7972 
7973       // non-volatile version
7974       QualType ParamTypes[2] = {
7975         S.Context.getLValueReferenceType(*Ptr),
7976         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7977       };
7978       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7979                             /*IsAssigmentOperator=*/ isEqualOp);
7980 
7981       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7982                           VisibleTypeConversionsQuals.hasVolatile();
7983       if (NeedVolatile) {
7984         // volatile version
7985         ParamTypes[0] =
7986           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7987         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7988                               /*IsAssigmentOperator=*/isEqualOp);
7989       }
7990 
7991       if (!(*Ptr).isRestrictQualified() &&
7992           VisibleTypeConversionsQuals.hasRestrict()) {
7993         // restrict version
7994         ParamTypes[0]
7995           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7996         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7997                               /*IsAssigmentOperator=*/isEqualOp);
7998 
7999         if (NeedVolatile) {
8000           // volatile restrict version
8001           ParamTypes[0]
8002             = S.Context.getLValueReferenceType(
8003                 S.Context.getCVRQualifiedType(*Ptr,
8004                                               (Qualifiers::Volatile |
8005                                                Qualifiers::Restrict)));
8006           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8007                                 /*IsAssigmentOperator=*/isEqualOp);
8008         }
8009       }
8010     }
8011 
8012     if (isEqualOp) {
8013       for (BuiltinCandidateTypeSet::iterator
8014                 Ptr = CandidateTypes[1].pointer_begin(),
8015              PtrEnd = CandidateTypes[1].pointer_end();
8016            Ptr != PtrEnd; ++Ptr) {
8017         // Make sure we don't add the same candidate twice.
8018         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8019           continue;
8020 
8021         QualType ParamTypes[2] = {
8022           S.Context.getLValueReferenceType(*Ptr),
8023           *Ptr,
8024         };
8025 
8026         // non-volatile version
8027         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8028                               /*IsAssigmentOperator=*/true);
8029 
8030         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8031                            VisibleTypeConversionsQuals.hasVolatile();
8032         if (NeedVolatile) {
8033           // volatile version
8034           ParamTypes[0] =
8035             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8036           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8037                                 /*IsAssigmentOperator=*/true);
8038         }
8039 
8040         if (!(*Ptr).isRestrictQualified() &&
8041             VisibleTypeConversionsQuals.hasRestrict()) {
8042           // restrict version
8043           ParamTypes[0]
8044             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8045           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8046                                 /*IsAssigmentOperator=*/true);
8047 
8048           if (NeedVolatile) {
8049             // volatile restrict version
8050             ParamTypes[0]
8051               = S.Context.getLValueReferenceType(
8052                   S.Context.getCVRQualifiedType(*Ptr,
8053                                                 (Qualifiers::Volatile |
8054                                                  Qualifiers::Restrict)));
8055             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8056                                   /*IsAssigmentOperator=*/true);
8057           }
8058         }
8059       }
8060     }
8061   }
8062 
8063   // C++ [over.built]p18:
8064   //
8065   //   For every triple (L, VQ, R), where L is an arithmetic type,
8066   //   VQ is either volatile or empty, and R is a promoted
8067   //   arithmetic type, there exist candidate operator functions of
8068   //   the form
8069   //
8070   //        VQ L&      operator=(VQ L&, R);
8071   //        VQ L&      operator*=(VQ L&, R);
8072   //        VQ L&      operator/=(VQ L&, R);
8073   //        VQ L&      operator+=(VQ L&, R);
8074   //        VQ L&      operator-=(VQ L&, R);
8075   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8076     if (!HasArithmeticOrEnumeralCandidateType)
8077       return;
8078 
8079     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8080       for (unsigned Right = FirstPromotedArithmeticType;
8081            Right < LastPromotedArithmeticType; ++Right) {
8082         QualType ParamTypes[2];
8083         ParamTypes[1] = getArithmeticType(Right);
8084 
8085         // Add this built-in operator as a candidate (VQ is empty).
8086         ParamTypes[0] =
8087           S.Context.getLValueReferenceType(getArithmeticType(Left));
8088         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8089                               /*IsAssigmentOperator=*/isEqualOp);
8090 
8091         // Add this built-in operator as a candidate (VQ is 'volatile').
8092         if (VisibleTypeConversionsQuals.hasVolatile()) {
8093           ParamTypes[0] =
8094             S.Context.getVolatileType(getArithmeticType(Left));
8095           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8096           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8097                                 /*IsAssigmentOperator=*/isEqualOp);
8098         }
8099       }
8100     }
8101 
8102     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8103     for (BuiltinCandidateTypeSet::iterator
8104               Vec1 = CandidateTypes[0].vector_begin(),
8105            Vec1End = CandidateTypes[0].vector_end();
8106          Vec1 != Vec1End; ++Vec1) {
8107       for (BuiltinCandidateTypeSet::iterator
8108                 Vec2 = CandidateTypes[1].vector_begin(),
8109              Vec2End = CandidateTypes[1].vector_end();
8110            Vec2 != Vec2End; ++Vec2) {
8111         QualType ParamTypes[2];
8112         ParamTypes[1] = *Vec2;
8113         // Add this built-in operator as a candidate (VQ is empty).
8114         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8115         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8116                               /*IsAssigmentOperator=*/isEqualOp);
8117 
8118         // Add this built-in operator as a candidate (VQ is 'volatile').
8119         if (VisibleTypeConversionsQuals.hasVolatile()) {
8120           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8121           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8122           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8123                                 /*IsAssigmentOperator=*/isEqualOp);
8124         }
8125       }
8126     }
8127   }
8128 
8129   // C++ [over.built]p22:
8130   //
8131   //   For every triple (L, VQ, R), where L is an integral type, VQ
8132   //   is either volatile or empty, and R is a promoted integral
8133   //   type, there exist candidate operator functions of the form
8134   //
8135   //        VQ L&       operator%=(VQ L&, R);
8136   //        VQ L&       operator<<=(VQ L&, R);
8137   //        VQ L&       operator>>=(VQ L&, R);
8138   //        VQ L&       operator&=(VQ L&, R);
8139   //        VQ L&       operator^=(VQ L&, R);
8140   //        VQ L&       operator|=(VQ L&, R);
8141   void addAssignmentIntegralOverloads() {
8142     if (!HasArithmeticOrEnumeralCandidateType)
8143       return;
8144 
8145     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8146       for (unsigned Right = FirstPromotedIntegralType;
8147            Right < LastPromotedIntegralType; ++Right) {
8148         QualType ParamTypes[2];
8149         ParamTypes[1] = getArithmeticType(Right);
8150 
8151         // Add this built-in operator as a candidate (VQ is empty).
8152         ParamTypes[0] =
8153           S.Context.getLValueReferenceType(getArithmeticType(Left));
8154         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8155         if (VisibleTypeConversionsQuals.hasVolatile()) {
8156           // Add this built-in operator as a candidate (VQ is 'volatile').
8157           ParamTypes[0] = getArithmeticType(Left);
8158           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8159           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8160           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8161         }
8162       }
8163     }
8164   }
8165 
8166   // C++ [over.operator]p23:
8167   //
8168   //   There also exist candidate operator functions of the form
8169   //
8170   //        bool        operator!(bool);
8171   //        bool        operator&&(bool, bool);
8172   //        bool        operator||(bool, bool);
8173   void addExclaimOverload() {
8174     QualType ParamTy = S.Context.BoolTy;
8175     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8176                           /*IsAssignmentOperator=*/false,
8177                           /*NumContextualBoolArguments=*/1);
8178   }
8179   void addAmpAmpOrPipePipeOverload() {
8180     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8181     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8182                           /*IsAssignmentOperator=*/false,
8183                           /*NumContextualBoolArguments=*/2);
8184   }
8185 
8186   // C++ [over.built]p13:
8187   //
8188   //   For every cv-qualified or cv-unqualified object type T there
8189   //   exist candidate operator functions of the form
8190   //
8191   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8192   //        T&         operator[](T*, ptrdiff_t);
8193   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8194   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8195   //        T&         operator[](ptrdiff_t, T*);
8196   void addSubscriptOverloads() {
8197     for (BuiltinCandidateTypeSet::iterator
8198               Ptr = CandidateTypes[0].pointer_begin(),
8199            PtrEnd = CandidateTypes[0].pointer_end();
8200          Ptr != PtrEnd; ++Ptr) {
8201       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8202       QualType PointeeType = (*Ptr)->getPointeeType();
8203       if (!PointeeType->isObjectType())
8204         continue;
8205 
8206       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8207 
8208       // T& operator[](T*, ptrdiff_t)
8209       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8210     }
8211 
8212     for (BuiltinCandidateTypeSet::iterator
8213               Ptr = CandidateTypes[1].pointer_begin(),
8214            PtrEnd = CandidateTypes[1].pointer_end();
8215          Ptr != PtrEnd; ++Ptr) {
8216       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8217       QualType PointeeType = (*Ptr)->getPointeeType();
8218       if (!PointeeType->isObjectType())
8219         continue;
8220 
8221       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8222 
8223       // T& operator[](ptrdiff_t, T*)
8224       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8225     }
8226   }
8227 
8228   // C++ [over.built]p11:
8229   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8230   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8231   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8232   //    there exist candidate operator functions of the form
8233   //
8234   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8235   //
8236   //    where CV12 is the union of CV1 and CV2.
8237   void addArrowStarOverloads() {
8238     for (BuiltinCandidateTypeSet::iterator
8239              Ptr = CandidateTypes[0].pointer_begin(),
8240            PtrEnd = CandidateTypes[0].pointer_end();
8241          Ptr != PtrEnd; ++Ptr) {
8242       QualType C1Ty = (*Ptr);
8243       QualType C1;
8244       QualifierCollector Q1;
8245       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8246       if (!isa<RecordType>(C1))
8247         continue;
8248       // heuristic to reduce number of builtin candidates in the set.
8249       // Add volatile/restrict version only if there are conversions to a
8250       // volatile/restrict type.
8251       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8252         continue;
8253       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8254         continue;
8255       for (BuiltinCandidateTypeSet::iterator
8256                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8257              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8258            MemPtr != MemPtrEnd; ++MemPtr) {
8259         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8260         QualType C2 = QualType(mptr->getClass(), 0);
8261         C2 = C2.getUnqualifiedType();
8262         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8263           break;
8264         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8265         // build CV12 T&
8266         QualType T = mptr->getPointeeType();
8267         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8268             T.isVolatileQualified())
8269           continue;
8270         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8271             T.isRestrictQualified())
8272           continue;
8273         T = Q1.apply(S.Context, T);
8274         QualType ResultTy = S.Context.getLValueReferenceType(T);
8275         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8276       }
8277     }
8278   }
8279 
8280   // Note that we don't consider the first argument, since it has been
8281   // contextually converted to bool long ago. The candidates below are
8282   // therefore added as binary.
8283   //
8284   // C++ [over.built]p25:
8285   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8286   //   enumeration type, there exist candidate operator functions of the form
8287   //
8288   //        T        operator?(bool, T, T);
8289   //
8290   void addConditionalOperatorOverloads() {
8291     /// Set of (canonical) types that we've already handled.
8292     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8293 
8294     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8295       for (BuiltinCandidateTypeSet::iterator
8296                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8297              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8298            Ptr != PtrEnd; ++Ptr) {
8299         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8300           continue;
8301 
8302         QualType ParamTypes[2] = { *Ptr, *Ptr };
8303         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8304       }
8305 
8306       for (BuiltinCandidateTypeSet::iterator
8307                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8308              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8309            MemPtr != MemPtrEnd; ++MemPtr) {
8310         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8311           continue;
8312 
8313         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8314         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8315       }
8316 
8317       if (S.getLangOpts().CPlusPlus11) {
8318         for (BuiltinCandidateTypeSet::iterator
8319                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8320                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8321              Enum != EnumEnd; ++Enum) {
8322           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8323             continue;
8324 
8325           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8326             continue;
8327 
8328           QualType ParamTypes[2] = { *Enum, *Enum };
8329           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8330         }
8331       }
8332     }
8333   }
8334 };
8335 
8336 } // end anonymous namespace
8337 
8338 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8339 /// operator overloads to the candidate set (C++ [over.built]), based
8340 /// on the operator @p Op and the arguments given. For example, if the
8341 /// operator is a binary '+', this routine might add "int
8342 /// operator+(int, int)" to cover integer addition.
8343 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8344                                         SourceLocation OpLoc,
8345                                         ArrayRef<Expr *> Args,
8346                                         OverloadCandidateSet &CandidateSet) {
8347   // Find all of the types that the arguments can convert to, but only
8348   // if the operator we're looking at has built-in operator candidates
8349   // that make use of these types. Also record whether we encounter non-record
8350   // candidate types or either arithmetic or enumeral candidate types.
8351   Qualifiers VisibleTypeConversionsQuals;
8352   VisibleTypeConversionsQuals.addConst();
8353   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8354     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8355 
8356   bool HasNonRecordCandidateType = false;
8357   bool HasArithmeticOrEnumeralCandidateType = false;
8358   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8359   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8360     CandidateTypes.emplace_back(*this);
8361     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8362                                                  OpLoc,
8363                                                  true,
8364                                                  (Op == OO_Exclaim ||
8365                                                   Op == OO_AmpAmp ||
8366                                                   Op == OO_PipePipe),
8367                                                  VisibleTypeConversionsQuals);
8368     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8369         CandidateTypes[ArgIdx].hasNonRecordTypes();
8370     HasArithmeticOrEnumeralCandidateType =
8371         HasArithmeticOrEnumeralCandidateType ||
8372         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8373   }
8374 
8375   // Exit early when no non-record types have been added to the candidate set
8376   // for any of the arguments to the operator.
8377   //
8378   // We can't exit early for !, ||, or &&, since there we have always have
8379   // 'bool' overloads.
8380   if (!HasNonRecordCandidateType &&
8381       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8382     return;
8383 
8384   // Setup an object to manage the common state for building overloads.
8385   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8386                                            VisibleTypeConversionsQuals,
8387                                            HasArithmeticOrEnumeralCandidateType,
8388                                            CandidateTypes, CandidateSet);
8389 
8390   // Dispatch over the operation to add in only those overloads which apply.
8391   switch (Op) {
8392   case OO_None:
8393   case NUM_OVERLOADED_OPERATORS:
8394     llvm_unreachable("Expected an overloaded operator");
8395 
8396   case OO_New:
8397   case OO_Delete:
8398   case OO_Array_New:
8399   case OO_Array_Delete:
8400   case OO_Call:
8401     llvm_unreachable(
8402                     "Special operators don't use AddBuiltinOperatorCandidates");
8403 
8404   case OO_Comma:
8405   case OO_Arrow:
8406   case OO_Coawait:
8407     // C++ [over.match.oper]p3:
8408     //   -- For the operator ',', the unary operator '&', the
8409     //      operator '->', or the operator 'co_await', the
8410     //      built-in candidates set is empty.
8411     break;
8412 
8413   case OO_Plus: // '+' is either unary or binary
8414     if (Args.size() == 1)
8415       OpBuilder.addUnaryPlusPointerOverloads();
8416     // Fall through.
8417 
8418   case OO_Minus: // '-' is either unary or binary
8419     if (Args.size() == 1) {
8420       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8421     } else {
8422       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8423       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8424     }
8425     break;
8426 
8427   case OO_Star: // '*' is either unary or binary
8428     if (Args.size() == 1)
8429       OpBuilder.addUnaryStarPointerOverloads();
8430     else
8431       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8432     break;
8433 
8434   case OO_Slash:
8435     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8436     break;
8437 
8438   case OO_PlusPlus:
8439   case OO_MinusMinus:
8440     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8441     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8442     break;
8443 
8444   case OO_EqualEqual:
8445   case OO_ExclaimEqual:
8446     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8447     // Fall through.
8448 
8449   case OO_Less:
8450   case OO_Greater:
8451   case OO_LessEqual:
8452   case OO_GreaterEqual:
8453     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8454     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8455     break;
8456 
8457   case OO_Percent:
8458   case OO_Caret:
8459   case OO_Pipe:
8460   case OO_LessLess:
8461   case OO_GreaterGreater:
8462     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8463     break;
8464 
8465   case OO_Amp: // '&' is either unary or binary
8466     if (Args.size() == 1)
8467       // C++ [over.match.oper]p3:
8468       //   -- For the operator ',', the unary operator '&', or the
8469       //      operator '->', the built-in candidates set is empty.
8470       break;
8471 
8472     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8473     break;
8474 
8475   case OO_Tilde:
8476     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8477     break;
8478 
8479   case OO_Equal:
8480     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8481     // Fall through.
8482 
8483   case OO_PlusEqual:
8484   case OO_MinusEqual:
8485     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8486     // Fall through.
8487 
8488   case OO_StarEqual:
8489   case OO_SlashEqual:
8490     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8491     break;
8492 
8493   case OO_PercentEqual:
8494   case OO_LessLessEqual:
8495   case OO_GreaterGreaterEqual:
8496   case OO_AmpEqual:
8497   case OO_CaretEqual:
8498   case OO_PipeEqual:
8499     OpBuilder.addAssignmentIntegralOverloads();
8500     break;
8501 
8502   case OO_Exclaim:
8503     OpBuilder.addExclaimOverload();
8504     break;
8505 
8506   case OO_AmpAmp:
8507   case OO_PipePipe:
8508     OpBuilder.addAmpAmpOrPipePipeOverload();
8509     break;
8510 
8511   case OO_Subscript:
8512     OpBuilder.addSubscriptOverloads();
8513     break;
8514 
8515   case OO_ArrowStar:
8516     OpBuilder.addArrowStarOverloads();
8517     break;
8518 
8519   case OO_Conditional:
8520     OpBuilder.addConditionalOperatorOverloads();
8521     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8522     break;
8523   }
8524 }
8525 
8526 /// \brief Add function candidates found via argument-dependent lookup
8527 /// to the set of overloading candidates.
8528 ///
8529 /// This routine performs argument-dependent name lookup based on the
8530 /// given function name (which may also be an operator name) and adds
8531 /// all of the overload candidates found by ADL to the overload
8532 /// candidate set (C++ [basic.lookup.argdep]).
8533 void
8534 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8535                                            SourceLocation Loc,
8536                                            ArrayRef<Expr *> Args,
8537                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8538                                            OverloadCandidateSet& CandidateSet,
8539                                            bool PartialOverloading) {
8540   ADLResult Fns;
8541 
8542   // FIXME: This approach for uniquing ADL results (and removing
8543   // redundant candidates from the set) relies on pointer-equality,
8544   // which means we need to key off the canonical decl.  However,
8545   // always going back to the canonical decl might not get us the
8546   // right set of default arguments.  What default arguments are
8547   // we supposed to consider on ADL candidates, anyway?
8548 
8549   // FIXME: Pass in the explicit template arguments?
8550   ArgumentDependentLookup(Name, Loc, Args, Fns);
8551 
8552   // Erase all of the candidates we already knew about.
8553   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8554                                    CandEnd = CandidateSet.end();
8555        Cand != CandEnd; ++Cand)
8556     if (Cand->Function) {
8557       Fns.erase(Cand->Function);
8558       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8559         Fns.erase(FunTmpl);
8560     }
8561 
8562   // For each of the ADL candidates we found, add it to the overload
8563   // set.
8564   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8565     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8566     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8567       if (ExplicitTemplateArgs)
8568         continue;
8569 
8570       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8571                            PartialOverloading);
8572     } else
8573       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8574                                    FoundDecl, ExplicitTemplateArgs,
8575                                    Args, CandidateSet, PartialOverloading);
8576   }
8577 }
8578 
8579 namespace {
8580 enum class Comparison { Equal, Better, Worse };
8581 }
8582 
8583 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8584 /// overload resolution.
8585 ///
8586 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8587 /// Cand1's first N enable_if attributes have precisely the same conditions as
8588 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8589 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8590 ///
8591 /// Note that you can have a pair of candidates such that Cand1's enable_if
8592 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8593 /// worse than Cand1's.
8594 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8595                                        const FunctionDecl *Cand2) {
8596   // Common case: One (or both) decls don't have enable_if attrs.
8597   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8598   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8599   if (!Cand1Attr || !Cand2Attr) {
8600     if (Cand1Attr == Cand2Attr)
8601       return Comparison::Equal;
8602     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8603   }
8604 
8605   // FIXME: The next several lines are just
8606   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8607   // instead of reverse order which is how they're stored in the AST.
8608   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8609   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8610 
8611   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8612   // has fewer enable_if attributes than Cand2.
8613   if (Cand1Attrs.size() < Cand2Attrs.size())
8614     return Comparison::Worse;
8615 
8616   auto Cand1I = Cand1Attrs.begin();
8617   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8618   for (auto &Cand2A : Cand2Attrs) {
8619     Cand1ID.clear();
8620     Cand2ID.clear();
8621 
8622     auto &Cand1A = *Cand1I++;
8623     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8624     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8625     if (Cand1ID != Cand2ID)
8626       return Comparison::Worse;
8627   }
8628 
8629   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8630 }
8631 
8632 /// isBetterOverloadCandidate - Determines whether the first overload
8633 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8634 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8635                                       const OverloadCandidate &Cand2,
8636                                       SourceLocation Loc,
8637                                       bool UserDefinedConversion) {
8638   // Define viable functions to be better candidates than non-viable
8639   // functions.
8640   if (!Cand2.Viable)
8641     return Cand1.Viable;
8642   else if (!Cand1.Viable)
8643     return false;
8644 
8645   // C++ [over.match.best]p1:
8646   //
8647   //   -- if F is a static member function, ICS1(F) is defined such
8648   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8649   //      any function G, and, symmetrically, ICS1(G) is neither
8650   //      better nor worse than ICS1(F).
8651   unsigned StartArg = 0;
8652   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8653     StartArg = 1;
8654 
8655   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8656     // We don't allow incompatible pointer conversions in C++.
8657     if (!S.getLangOpts().CPlusPlus)
8658       return ICS.isStandard() &&
8659              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8660 
8661     // The only ill-formed conversion we allow in C++ is the string literal to
8662     // char* conversion, which is only considered ill-formed after C++11.
8663     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8664            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8665   };
8666 
8667   // Define functions that don't require ill-formed conversions for a given
8668   // argument to be better candidates than functions that do.
8669   unsigned NumArgs = Cand1.NumConversions;
8670   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8671   bool HasBetterConversion = false;
8672   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8673     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8674     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8675     if (Cand1Bad != Cand2Bad) {
8676       if (Cand1Bad)
8677         return false;
8678       HasBetterConversion = true;
8679     }
8680   }
8681 
8682   if (HasBetterConversion)
8683     return true;
8684 
8685   // C++ [over.match.best]p1:
8686   //   A viable function F1 is defined to be a better function than another
8687   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8688   //   conversion sequence than ICSi(F2), and then...
8689   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8690     switch (CompareImplicitConversionSequences(S, Loc,
8691                                                Cand1.Conversions[ArgIdx],
8692                                                Cand2.Conversions[ArgIdx])) {
8693     case ImplicitConversionSequence::Better:
8694       // Cand1 has a better conversion sequence.
8695       HasBetterConversion = true;
8696       break;
8697 
8698     case ImplicitConversionSequence::Worse:
8699       // Cand1 can't be better than Cand2.
8700       return false;
8701 
8702     case ImplicitConversionSequence::Indistinguishable:
8703       // Do nothing.
8704       break;
8705     }
8706   }
8707 
8708   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8709   //       ICSj(F2), or, if not that,
8710   if (HasBetterConversion)
8711     return true;
8712 
8713   //   -- the context is an initialization by user-defined conversion
8714   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8715   //      from the return type of F1 to the destination type (i.e.,
8716   //      the type of the entity being initialized) is a better
8717   //      conversion sequence than the standard conversion sequence
8718   //      from the return type of F2 to the destination type.
8719   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8720       isa<CXXConversionDecl>(Cand1.Function) &&
8721       isa<CXXConversionDecl>(Cand2.Function)) {
8722     // First check whether we prefer one of the conversion functions over the
8723     // other. This only distinguishes the results in non-standard, extension
8724     // cases such as the conversion from a lambda closure type to a function
8725     // pointer or block.
8726     ImplicitConversionSequence::CompareKind Result =
8727         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8728     if (Result == ImplicitConversionSequence::Indistinguishable)
8729       Result = CompareStandardConversionSequences(S, Loc,
8730                                                   Cand1.FinalConversion,
8731                                                   Cand2.FinalConversion);
8732 
8733     if (Result != ImplicitConversionSequence::Indistinguishable)
8734       return Result == ImplicitConversionSequence::Better;
8735 
8736     // FIXME: Compare kind of reference binding if conversion functions
8737     // convert to a reference type used in direct reference binding, per
8738     // C++14 [over.match.best]p1 section 2 bullet 3.
8739   }
8740 
8741   //    -- F1 is a non-template function and F2 is a function template
8742   //       specialization, or, if not that,
8743   bool Cand1IsSpecialization = Cand1.Function &&
8744                                Cand1.Function->getPrimaryTemplate();
8745   bool Cand2IsSpecialization = Cand2.Function &&
8746                                Cand2.Function->getPrimaryTemplate();
8747   if (Cand1IsSpecialization != Cand2IsSpecialization)
8748     return Cand2IsSpecialization;
8749 
8750   //   -- F1 and F2 are function template specializations, and the function
8751   //      template for F1 is more specialized than the template for F2
8752   //      according to the partial ordering rules described in 14.5.5.2, or,
8753   //      if not that,
8754   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8755     if (FunctionTemplateDecl *BetterTemplate
8756           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8757                                          Cand2.Function->getPrimaryTemplate(),
8758                                          Loc,
8759                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8760                                                              : TPOC_Call,
8761                                          Cand1.ExplicitCallArguments,
8762                                          Cand2.ExplicitCallArguments))
8763       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8764   }
8765 
8766   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8767   // A derived-class constructor beats an (inherited) base class constructor.
8768   bool Cand1IsInherited =
8769       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8770   bool Cand2IsInherited =
8771       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8772   if (Cand1IsInherited != Cand2IsInherited)
8773     return Cand2IsInherited;
8774   else if (Cand1IsInherited) {
8775     assert(Cand2IsInherited);
8776     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8777     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8778     if (Cand1Class->isDerivedFrom(Cand2Class))
8779       return true;
8780     if (Cand2Class->isDerivedFrom(Cand1Class))
8781       return false;
8782     // Inherited from sibling base classes: still ambiguous.
8783   }
8784 
8785   // Check for enable_if value-based overload resolution.
8786   if (Cand1.Function && Cand2.Function) {
8787     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8788     if (Cmp != Comparison::Equal)
8789       return Cmp == Comparison::Better;
8790   }
8791 
8792   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8793     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8794     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8795            S.IdentifyCUDAPreference(Caller, Cand2.Function);
8796   }
8797 
8798   bool HasPS1 = Cand1.Function != nullptr &&
8799                 functionHasPassObjectSizeParams(Cand1.Function);
8800   bool HasPS2 = Cand2.Function != nullptr &&
8801                 functionHasPassObjectSizeParams(Cand2.Function);
8802   return HasPS1 != HasPS2 && HasPS1;
8803 }
8804 
8805 /// Determine whether two declarations are "equivalent" for the purposes of
8806 /// name lookup and overload resolution. This applies when the same internal/no
8807 /// linkage entity is defined by two modules (probably by textually including
8808 /// the same header). In such a case, we don't consider the declarations to
8809 /// declare the same entity, but we also don't want lookups with both
8810 /// declarations visible to be ambiguous in some cases (this happens when using
8811 /// a modularized libstdc++).
8812 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8813                                                   const NamedDecl *B) {
8814   auto *VA = dyn_cast_or_null<ValueDecl>(A);
8815   auto *VB = dyn_cast_or_null<ValueDecl>(B);
8816   if (!VA || !VB)
8817     return false;
8818 
8819   // The declarations must be declaring the same name as an internal linkage
8820   // entity in different modules.
8821   if (!VA->getDeclContext()->getRedeclContext()->Equals(
8822           VB->getDeclContext()->getRedeclContext()) ||
8823       getOwningModule(const_cast<ValueDecl *>(VA)) ==
8824           getOwningModule(const_cast<ValueDecl *>(VB)) ||
8825       VA->isExternallyVisible() || VB->isExternallyVisible())
8826     return false;
8827 
8828   // Check that the declarations appear to be equivalent.
8829   //
8830   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8831   // For constants and functions, we should check the initializer or body is
8832   // the same. For non-constant variables, we shouldn't allow it at all.
8833   if (Context.hasSameType(VA->getType(), VB->getType()))
8834     return true;
8835 
8836   // Enum constants within unnamed enumerations will have different types, but
8837   // may still be similar enough to be interchangeable for our purposes.
8838   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8839     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8840       // Only handle anonymous enums. If the enumerations were named and
8841       // equivalent, they would have been merged to the same type.
8842       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8843       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8844       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8845           !Context.hasSameType(EnumA->getIntegerType(),
8846                                EnumB->getIntegerType()))
8847         return false;
8848       // Allow this only if the value is the same for both enumerators.
8849       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8850     }
8851   }
8852 
8853   // Nothing else is sufficiently similar.
8854   return false;
8855 }
8856 
8857 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8858     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8859   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8860 
8861   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8862   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8863       << !M << (M ? M->getFullModuleName() : "");
8864 
8865   for (auto *E : Equiv) {
8866     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8867     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8868         << !M << (M ? M->getFullModuleName() : "");
8869   }
8870 }
8871 
8872 /// \brief Computes the best viable function (C++ 13.3.3)
8873 /// within an overload candidate set.
8874 ///
8875 /// \param Loc The location of the function name (or operator symbol) for
8876 /// which overload resolution occurs.
8877 ///
8878 /// \param Best If overload resolution was successful or found a deleted
8879 /// function, \p Best points to the candidate function found.
8880 ///
8881 /// \returns The result of overload resolution.
8882 OverloadingResult
8883 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8884                                          iterator &Best,
8885                                          bool UserDefinedConversion) {
8886   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8887   std::transform(begin(), end(), std::back_inserter(Candidates),
8888                  [](OverloadCandidate &Cand) { return &Cand; });
8889 
8890   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8891   // are accepted by both clang and NVCC. However, during a particular
8892   // compilation mode only one call variant is viable. We need to
8893   // exclude non-viable overload candidates from consideration based
8894   // only on their host/device attributes. Specifically, if one
8895   // candidate call is WrongSide and the other is SameSide, we ignore
8896   // the WrongSide candidate.
8897   if (S.getLangOpts().CUDA) {
8898     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8899     bool ContainsSameSideCandidate =
8900         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8901           return Cand->Function &&
8902                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8903                      Sema::CFP_SameSide;
8904         });
8905     if (ContainsSameSideCandidate) {
8906       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8907         return Cand->Function &&
8908                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8909                    Sema::CFP_WrongSide;
8910       };
8911       Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8912                                       IsWrongSideCandidate),
8913                        Candidates.end());
8914     }
8915   }
8916 
8917   // Find the best viable function.
8918   Best = end();
8919   for (auto *Cand : Candidates)
8920     if (Cand->Viable)
8921       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8922                                                      UserDefinedConversion))
8923         Best = Cand;
8924 
8925   // If we didn't find any viable functions, abort.
8926   if (Best == end())
8927     return OR_No_Viable_Function;
8928 
8929   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8930 
8931   // Make sure that this function is better than every other viable
8932   // function. If not, we have an ambiguity.
8933   for (auto *Cand : Candidates) {
8934     if (Cand->Viable &&
8935         Cand != Best &&
8936         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8937                                    UserDefinedConversion)) {
8938       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8939                                                    Cand->Function)) {
8940         EquivalentCands.push_back(Cand->Function);
8941         continue;
8942       }
8943 
8944       Best = end();
8945       return OR_Ambiguous;
8946     }
8947   }
8948 
8949   // Best is the best viable function.
8950   if (Best->Function &&
8951       (Best->Function->isDeleted() ||
8952        S.isFunctionConsideredUnavailable(Best->Function)))
8953     return OR_Deleted;
8954 
8955   if (!EquivalentCands.empty())
8956     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8957                                                     EquivalentCands);
8958 
8959   return OR_Success;
8960 }
8961 
8962 namespace {
8963 
8964 enum OverloadCandidateKind {
8965   oc_function,
8966   oc_method,
8967   oc_constructor,
8968   oc_function_template,
8969   oc_method_template,
8970   oc_constructor_template,
8971   oc_implicit_default_constructor,
8972   oc_implicit_copy_constructor,
8973   oc_implicit_move_constructor,
8974   oc_implicit_copy_assignment,
8975   oc_implicit_move_assignment,
8976   oc_inherited_constructor,
8977   oc_inherited_constructor_template
8978 };
8979 
8980 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8981                                                 NamedDecl *Found,
8982                                                 FunctionDecl *Fn,
8983                                                 std::string &Description) {
8984   bool isTemplate = false;
8985 
8986   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8987     isTemplate = true;
8988     Description = S.getTemplateArgumentBindingsText(
8989       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8990   }
8991 
8992   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8993     if (!Ctor->isImplicit()) {
8994       if (isa<ConstructorUsingShadowDecl>(Found))
8995         return isTemplate ? oc_inherited_constructor_template
8996                           : oc_inherited_constructor;
8997       else
8998         return isTemplate ? oc_constructor_template : oc_constructor;
8999     }
9000 
9001     if (Ctor->isDefaultConstructor())
9002       return oc_implicit_default_constructor;
9003 
9004     if (Ctor->isMoveConstructor())
9005       return oc_implicit_move_constructor;
9006 
9007     assert(Ctor->isCopyConstructor() &&
9008            "unexpected sort of implicit constructor");
9009     return oc_implicit_copy_constructor;
9010   }
9011 
9012   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9013     // This actually gets spelled 'candidate function' for now, but
9014     // it doesn't hurt to split it out.
9015     if (!Meth->isImplicit())
9016       return isTemplate ? oc_method_template : oc_method;
9017 
9018     if (Meth->isMoveAssignmentOperator())
9019       return oc_implicit_move_assignment;
9020 
9021     if (Meth->isCopyAssignmentOperator())
9022       return oc_implicit_copy_assignment;
9023 
9024     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9025     return oc_method;
9026   }
9027 
9028   return isTemplate ? oc_function_template : oc_function;
9029 }
9030 
9031 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9032   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9033   // set.
9034   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9035     S.Diag(FoundDecl->getLocation(),
9036            diag::note_ovl_candidate_inherited_constructor)
9037       << Shadow->getNominatedBaseClass();
9038 }
9039 
9040 } // end anonymous namespace
9041 
9042 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9043                                     const FunctionDecl *FD) {
9044   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9045     bool AlwaysTrue;
9046     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9047       return false;
9048     if (!AlwaysTrue)
9049       return false;
9050   }
9051   return true;
9052 }
9053 
9054 /// \brief Returns true if we can take the address of the function.
9055 ///
9056 /// \param Complain - If true, we'll emit a diagnostic
9057 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9058 ///   we in overload resolution?
9059 /// \param Loc - The location of the statement we're complaining about. Ignored
9060 ///   if we're not complaining, or if we're in overload resolution.
9061 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9062                                               bool Complain,
9063                                               bool InOverloadResolution,
9064                                               SourceLocation Loc) {
9065   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9066     if (Complain) {
9067       if (InOverloadResolution)
9068         S.Diag(FD->getLocStart(),
9069                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9070       else
9071         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9072     }
9073     return false;
9074   }
9075 
9076   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9077     return P->hasAttr<PassObjectSizeAttr>();
9078   });
9079   if (I == FD->param_end())
9080     return true;
9081 
9082   if (Complain) {
9083     // Add one to ParamNo because it's user-facing
9084     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9085     if (InOverloadResolution)
9086       S.Diag(FD->getLocation(),
9087              diag::note_ovl_candidate_has_pass_object_size_params)
9088           << ParamNo;
9089     else
9090       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9091           << FD << ParamNo;
9092   }
9093   return false;
9094 }
9095 
9096 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9097                                                const FunctionDecl *FD) {
9098   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9099                                            /*InOverloadResolution=*/true,
9100                                            /*Loc=*/SourceLocation());
9101 }
9102 
9103 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9104                                              bool Complain,
9105                                              SourceLocation Loc) {
9106   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9107                                              /*InOverloadResolution=*/false,
9108                                              Loc);
9109 }
9110 
9111 // Notes the location of an overload candidate.
9112 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9113                                  QualType DestType, bool TakingAddress) {
9114   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9115     return;
9116 
9117   std::string FnDesc;
9118   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9119   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9120                              << (unsigned) K << FnDesc;
9121 
9122   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9123   Diag(Fn->getLocation(), PD);
9124   MaybeEmitInheritedConstructorNote(*this, Found);
9125 }
9126 
9127 // Notes the location of all overload candidates designated through
9128 // OverloadedExpr
9129 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9130                                      bool TakingAddress) {
9131   assert(OverloadedExpr->getType() == Context.OverloadTy);
9132 
9133   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9134   OverloadExpr *OvlExpr = Ovl.Expression;
9135 
9136   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9137                             IEnd = OvlExpr->decls_end();
9138        I != IEnd; ++I) {
9139     if (FunctionTemplateDecl *FunTmpl =
9140                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9141       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9142                             TakingAddress);
9143     } else if (FunctionDecl *Fun
9144                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9145       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9146     }
9147   }
9148 }
9149 
9150 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9151 /// "lead" diagnostic; it will be given two arguments, the source and
9152 /// target types of the conversion.
9153 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9154                                  Sema &S,
9155                                  SourceLocation CaretLoc,
9156                                  const PartialDiagnostic &PDiag) const {
9157   S.Diag(CaretLoc, PDiag)
9158     << Ambiguous.getFromType() << Ambiguous.getToType();
9159   // FIXME: The note limiting machinery is borrowed from
9160   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9161   // refactoring here.
9162   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9163   unsigned CandsShown = 0;
9164   AmbiguousConversionSequence::const_iterator I, E;
9165   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9166     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9167       break;
9168     ++CandsShown;
9169     S.NoteOverloadCandidate(I->first, I->second);
9170   }
9171   if (I != E)
9172     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9173 }
9174 
9175 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9176                                   unsigned I, bool TakingCandidateAddress) {
9177   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9178   assert(Conv.isBad());
9179   assert(Cand->Function && "for now, candidate must be a function");
9180   FunctionDecl *Fn = Cand->Function;
9181 
9182   // There's a conversion slot for the object argument if this is a
9183   // non-constructor method.  Note that 'I' corresponds the
9184   // conversion-slot index.
9185   bool isObjectArgument = false;
9186   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9187     if (I == 0)
9188       isObjectArgument = true;
9189     else
9190       I--;
9191   }
9192 
9193   std::string FnDesc;
9194   OverloadCandidateKind FnKind =
9195       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9196 
9197   Expr *FromExpr = Conv.Bad.FromExpr;
9198   QualType FromTy = Conv.Bad.getFromType();
9199   QualType ToTy = Conv.Bad.getToType();
9200 
9201   if (FromTy == S.Context.OverloadTy) {
9202     assert(FromExpr && "overload set argument came from implicit argument?");
9203     Expr *E = FromExpr->IgnoreParens();
9204     if (isa<UnaryOperator>(E))
9205       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9206     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9207 
9208     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9209       << (unsigned) FnKind << FnDesc
9210       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9211       << ToTy << Name << I+1;
9212     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9213     return;
9214   }
9215 
9216   // Do some hand-waving analysis to see if the non-viability is due
9217   // to a qualifier mismatch.
9218   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9219   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9220   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9221     CToTy = RT->getPointeeType();
9222   else {
9223     // TODO: detect and diagnose the full richness of const mismatches.
9224     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9225       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9226         CFromTy = FromPT->getPointeeType();
9227         CToTy = ToPT->getPointeeType();
9228       }
9229   }
9230 
9231   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9232       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9233     Qualifiers FromQs = CFromTy.getQualifiers();
9234     Qualifiers ToQs = CToTy.getQualifiers();
9235 
9236     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9237       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9238         << (unsigned) FnKind << FnDesc
9239         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9240         << FromTy
9241         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9242         << (unsigned) isObjectArgument << I+1;
9243       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9244       return;
9245     }
9246 
9247     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9248       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9249         << (unsigned) FnKind << FnDesc
9250         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9251         << FromTy
9252         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9253         << (unsigned) isObjectArgument << I+1;
9254       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9255       return;
9256     }
9257 
9258     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9259       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9260       << (unsigned) FnKind << FnDesc
9261       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9262       << FromTy
9263       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9264       << (unsigned) isObjectArgument << I+1;
9265       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9266       return;
9267     }
9268 
9269     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9270       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9271         << (unsigned) FnKind << FnDesc
9272         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9273         << FromTy << FromQs.hasUnaligned() << I+1;
9274       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9275       return;
9276     }
9277 
9278     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9279     assert(CVR && "unexpected qualifiers mismatch");
9280 
9281     if (isObjectArgument) {
9282       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9283         << (unsigned) FnKind << FnDesc
9284         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9285         << FromTy << (CVR - 1);
9286     } else {
9287       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9288         << (unsigned) FnKind << FnDesc
9289         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9290         << FromTy << (CVR - 1) << I+1;
9291     }
9292     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9293     return;
9294   }
9295 
9296   // Special diagnostic for failure to convert an initializer list, since
9297   // telling the user that it has type void is not useful.
9298   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9299     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9300       << (unsigned) FnKind << FnDesc
9301       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9302       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9303     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9304     return;
9305   }
9306 
9307   // Diagnose references or pointers to incomplete types differently,
9308   // since it's far from impossible that the incompleteness triggered
9309   // the failure.
9310   QualType TempFromTy = FromTy.getNonReferenceType();
9311   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9312     TempFromTy = PTy->getPointeeType();
9313   if (TempFromTy->isIncompleteType()) {
9314     // Emit the generic diagnostic and, optionally, add the hints to it.
9315     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9316       << (unsigned) FnKind << FnDesc
9317       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9318       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9319       << (unsigned) (Cand->Fix.Kind);
9320 
9321     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9322     return;
9323   }
9324 
9325   // Diagnose base -> derived pointer conversions.
9326   unsigned BaseToDerivedConversion = 0;
9327   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9328     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9329       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9330                                                FromPtrTy->getPointeeType()) &&
9331           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9332           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9333           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9334                           FromPtrTy->getPointeeType()))
9335         BaseToDerivedConversion = 1;
9336     }
9337   } else if (const ObjCObjectPointerType *FromPtrTy
9338                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9339     if (const ObjCObjectPointerType *ToPtrTy
9340                                         = ToTy->getAs<ObjCObjectPointerType>())
9341       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9342         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9343           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9344                                                 FromPtrTy->getPointeeType()) &&
9345               FromIface->isSuperClassOf(ToIface))
9346             BaseToDerivedConversion = 2;
9347   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9348     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9349         !FromTy->isIncompleteType() &&
9350         !ToRefTy->getPointeeType()->isIncompleteType() &&
9351         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9352       BaseToDerivedConversion = 3;
9353     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9354                ToTy.getNonReferenceType().getCanonicalType() ==
9355                FromTy.getNonReferenceType().getCanonicalType()) {
9356       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9357         << (unsigned) FnKind << FnDesc
9358         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9359         << (unsigned) isObjectArgument << I + 1;
9360       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9361       return;
9362     }
9363   }
9364 
9365   if (BaseToDerivedConversion) {
9366     S.Diag(Fn->getLocation(),
9367            diag::note_ovl_candidate_bad_base_to_derived_conv)
9368       << (unsigned) FnKind << FnDesc
9369       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9370       << (BaseToDerivedConversion - 1)
9371       << FromTy << ToTy << I+1;
9372     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9373     return;
9374   }
9375 
9376   if (isa<ObjCObjectPointerType>(CFromTy) &&
9377       isa<PointerType>(CToTy)) {
9378       Qualifiers FromQs = CFromTy.getQualifiers();
9379       Qualifiers ToQs = CToTy.getQualifiers();
9380       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9381         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9382         << (unsigned) FnKind << FnDesc
9383         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9384         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9385         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9386         return;
9387       }
9388   }
9389 
9390   if (TakingCandidateAddress &&
9391       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9392     return;
9393 
9394   // Emit the generic diagnostic and, optionally, add the hints to it.
9395   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9396   FDiag << (unsigned) FnKind << FnDesc
9397     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9398     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9399     << (unsigned) (Cand->Fix.Kind);
9400 
9401   // If we can fix the conversion, suggest the FixIts.
9402   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9403        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9404     FDiag << *HI;
9405   S.Diag(Fn->getLocation(), FDiag);
9406 
9407   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9408 }
9409 
9410 /// Additional arity mismatch diagnosis specific to a function overload
9411 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9412 /// over a candidate in any candidate set.
9413 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9414                                unsigned NumArgs) {
9415   FunctionDecl *Fn = Cand->Function;
9416   unsigned MinParams = Fn->getMinRequiredArguments();
9417 
9418   // With invalid overloaded operators, it's possible that we think we
9419   // have an arity mismatch when in fact it looks like we have the
9420   // right number of arguments, because only overloaded operators have
9421   // the weird behavior of overloading member and non-member functions.
9422   // Just don't report anything.
9423   if (Fn->isInvalidDecl() &&
9424       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9425     return true;
9426 
9427   if (NumArgs < MinParams) {
9428     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9429            (Cand->FailureKind == ovl_fail_bad_deduction &&
9430             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9431   } else {
9432     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9433            (Cand->FailureKind == ovl_fail_bad_deduction &&
9434             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9435   }
9436 
9437   return false;
9438 }
9439 
9440 /// General arity mismatch diagnosis over a candidate in a candidate set.
9441 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9442                                   unsigned NumFormalArgs) {
9443   assert(isa<FunctionDecl>(D) &&
9444       "The templated declaration should at least be a function"
9445       " when diagnosing bad template argument deduction due to too many"
9446       " or too few arguments");
9447 
9448   FunctionDecl *Fn = cast<FunctionDecl>(D);
9449 
9450   // TODO: treat calls to a missing default constructor as a special case
9451   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9452   unsigned MinParams = Fn->getMinRequiredArguments();
9453 
9454   // at least / at most / exactly
9455   unsigned mode, modeCount;
9456   if (NumFormalArgs < MinParams) {
9457     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9458         FnTy->isTemplateVariadic())
9459       mode = 0; // "at least"
9460     else
9461       mode = 2; // "exactly"
9462     modeCount = MinParams;
9463   } else {
9464     if (MinParams != FnTy->getNumParams())
9465       mode = 1; // "at most"
9466     else
9467       mode = 2; // "exactly"
9468     modeCount = FnTy->getNumParams();
9469   }
9470 
9471   std::string Description;
9472   OverloadCandidateKind FnKind =
9473       ClassifyOverloadCandidate(S, Found, Fn, Description);
9474 
9475   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9476     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9477       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9478       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9479   else
9480     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9481       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9482       << mode << modeCount << NumFormalArgs;
9483   MaybeEmitInheritedConstructorNote(S, Found);
9484 }
9485 
9486 /// Arity mismatch diagnosis specific to a function overload candidate.
9487 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9488                                   unsigned NumFormalArgs) {
9489   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9490     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9491 }
9492 
9493 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9494   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9495     return TD;
9496   llvm_unreachable("Unsupported: Getting the described template declaration"
9497                    " for bad deduction diagnosis");
9498 }
9499 
9500 /// Diagnose a failed template-argument deduction.
9501 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9502                                  DeductionFailureInfo &DeductionFailure,
9503                                  unsigned NumArgs,
9504                                  bool TakingCandidateAddress) {
9505   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9506   NamedDecl *ParamD;
9507   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9508   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9509   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9510   switch (DeductionFailure.Result) {
9511   case Sema::TDK_Success:
9512     llvm_unreachable("TDK_success while diagnosing bad deduction");
9513 
9514   case Sema::TDK_Incomplete: {
9515     assert(ParamD && "no parameter found for incomplete deduction result");
9516     S.Diag(Templated->getLocation(),
9517            diag::note_ovl_candidate_incomplete_deduction)
9518         << ParamD->getDeclName();
9519     MaybeEmitInheritedConstructorNote(S, Found);
9520     return;
9521   }
9522 
9523   case Sema::TDK_Underqualified: {
9524     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9525     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9526 
9527     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9528 
9529     // Param will have been canonicalized, but it should just be a
9530     // qualified version of ParamD, so move the qualifiers to that.
9531     QualifierCollector Qs;
9532     Qs.strip(Param);
9533     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9534     assert(S.Context.hasSameType(Param, NonCanonParam));
9535 
9536     // Arg has also been canonicalized, but there's nothing we can do
9537     // about that.  It also doesn't matter as much, because it won't
9538     // have any template parameters in it (because deduction isn't
9539     // done on dependent types).
9540     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9541 
9542     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9543         << ParamD->getDeclName() << Arg << NonCanonParam;
9544     MaybeEmitInheritedConstructorNote(S, Found);
9545     return;
9546   }
9547 
9548   case Sema::TDK_Inconsistent: {
9549     assert(ParamD && "no parameter found for inconsistent deduction result");
9550     int which = 0;
9551     if (isa<TemplateTypeParmDecl>(ParamD))
9552       which = 0;
9553     else if (isa<NonTypeTemplateParmDecl>(ParamD))
9554       which = 1;
9555     else {
9556       which = 2;
9557     }
9558 
9559     S.Diag(Templated->getLocation(),
9560            diag::note_ovl_candidate_inconsistent_deduction)
9561         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9562         << *DeductionFailure.getSecondArg();
9563     MaybeEmitInheritedConstructorNote(S, Found);
9564     return;
9565   }
9566 
9567   case Sema::TDK_InvalidExplicitArguments:
9568     assert(ParamD && "no parameter found for invalid explicit arguments");
9569     if (ParamD->getDeclName())
9570       S.Diag(Templated->getLocation(),
9571              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9572           << ParamD->getDeclName();
9573     else {
9574       int index = 0;
9575       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9576         index = TTP->getIndex();
9577       else if (NonTypeTemplateParmDecl *NTTP
9578                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9579         index = NTTP->getIndex();
9580       else
9581         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9582       S.Diag(Templated->getLocation(),
9583              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9584           << (index + 1);
9585     }
9586     MaybeEmitInheritedConstructorNote(S, Found);
9587     return;
9588 
9589   case Sema::TDK_TooManyArguments:
9590   case Sema::TDK_TooFewArguments:
9591     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9592     return;
9593 
9594   case Sema::TDK_InstantiationDepth:
9595     S.Diag(Templated->getLocation(),
9596            diag::note_ovl_candidate_instantiation_depth);
9597     MaybeEmitInheritedConstructorNote(S, Found);
9598     return;
9599 
9600   case Sema::TDK_SubstitutionFailure: {
9601     // Format the template argument list into the argument string.
9602     SmallString<128> TemplateArgString;
9603     if (TemplateArgumentList *Args =
9604             DeductionFailure.getTemplateArgumentList()) {
9605       TemplateArgString = " ";
9606       TemplateArgString += S.getTemplateArgumentBindingsText(
9607           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9608     }
9609 
9610     // If this candidate was disabled by enable_if, say so.
9611     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9612     if (PDiag && PDiag->second.getDiagID() ==
9613           diag::err_typename_nested_not_found_enable_if) {
9614       // FIXME: Use the source range of the condition, and the fully-qualified
9615       //        name of the enable_if template. These are both present in PDiag.
9616       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9617         << "'enable_if'" << TemplateArgString;
9618       return;
9619     }
9620 
9621     // Format the SFINAE diagnostic into the argument string.
9622     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9623     //        formatted message in another diagnostic.
9624     SmallString<128> SFINAEArgString;
9625     SourceRange R;
9626     if (PDiag) {
9627       SFINAEArgString = ": ";
9628       R = SourceRange(PDiag->first, PDiag->first);
9629       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9630     }
9631 
9632     S.Diag(Templated->getLocation(),
9633            diag::note_ovl_candidate_substitution_failure)
9634         << TemplateArgString << SFINAEArgString << R;
9635     MaybeEmitInheritedConstructorNote(S, Found);
9636     return;
9637   }
9638 
9639   case Sema::TDK_FailedOverloadResolution: {
9640     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9641     S.Diag(Templated->getLocation(),
9642            diag::note_ovl_candidate_failed_overload_resolution)
9643         << R.Expression->getName();
9644     return;
9645   }
9646 
9647   case Sema::TDK_DeducedMismatch: {
9648     // Format the template argument list into the argument string.
9649     SmallString<128> TemplateArgString;
9650     if (TemplateArgumentList *Args =
9651             DeductionFailure.getTemplateArgumentList()) {
9652       TemplateArgString = " ";
9653       TemplateArgString += S.getTemplateArgumentBindingsText(
9654           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9655     }
9656 
9657     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9658         << (*DeductionFailure.getCallArgIndex() + 1)
9659         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9660         << TemplateArgString;
9661     break;
9662   }
9663 
9664   case Sema::TDK_NonDeducedMismatch: {
9665     // FIXME: Provide a source location to indicate what we couldn't match.
9666     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9667     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9668     if (FirstTA.getKind() == TemplateArgument::Template &&
9669         SecondTA.getKind() == TemplateArgument::Template) {
9670       TemplateName FirstTN = FirstTA.getAsTemplate();
9671       TemplateName SecondTN = SecondTA.getAsTemplate();
9672       if (FirstTN.getKind() == TemplateName::Template &&
9673           SecondTN.getKind() == TemplateName::Template) {
9674         if (FirstTN.getAsTemplateDecl()->getName() ==
9675             SecondTN.getAsTemplateDecl()->getName()) {
9676           // FIXME: This fixes a bad diagnostic where both templates are named
9677           // the same.  This particular case is a bit difficult since:
9678           // 1) It is passed as a string to the diagnostic printer.
9679           // 2) The diagnostic printer only attempts to find a better
9680           //    name for types, not decls.
9681           // Ideally, this should folded into the diagnostic printer.
9682           S.Diag(Templated->getLocation(),
9683                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9684               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9685           return;
9686         }
9687       }
9688     }
9689 
9690     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9691         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9692       return;
9693 
9694     // FIXME: For generic lambda parameters, check if the function is a lambda
9695     // call operator, and if so, emit a prettier and more informative
9696     // diagnostic that mentions 'auto' and lambda in addition to
9697     // (or instead of?) the canonical template type parameters.
9698     S.Diag(Templated->getLocation(),
9699            diag::note_ovl_candidate_non_deduced_mismatch)
9700         << FirstTA << SecondTA;
9701     return;
9702   }
9703   // TODO: diagnose these individually, then kill off
9704   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9705   case Sema::TDK_MiscellaneousDeductionFailure:
9706     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9707     MaybeEmitInheritedConstructorNote(S, Found);
9708     return;
9709   }
9710 }
9711 
9712 /// Diagnose a failed template-argument deduction, for function calls.
9713 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9714                                  unsigned NumArgs,
9715                                  bool TakingCandidateAddress) {
9716   unsigned TDK = Cand->DeductionFailure.Result;
9717   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9718     if (CheckArityMismatch(S, Cand, NumArgs))
9719       return;
9720   }
9721   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9722                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9723 }
9724 
9725 /// CUDA: diagnose an invalid call across targets.
9726 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9727   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9728   FunctionDecl *Callee = Cand->Function;
9729 
9730   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9731                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9732 
9733   std::string FnDesc;
9734   OverloadCandidateKind FnKind =
9735       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9736 
9737   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9738       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9739 
9740   // This could be an implicit constructor for which we could not infer the
9741   // target due to a collsion. Diagnose that case.
9742   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9743   if (Meth != nullptr && Meth->isImplicit()) {
9744     CXXRecordDecl *ParentClass = Meth->getParent();
9745     Sema::CXXSpecialMember CSM;
9746 
9747     switch (FnKind) {
9748     default:
9749       return;
9750     case oc_implicit_default_constructor:
9751       CSM = Sema::CXXDefaultConstructor;
9752       break;
9753     case oc_implicit_copy_constructor:
9754       CSM = Sema::CXXCopyConstructor;
9755       break;
9756     case oc_implicit_move_constructor:
9757       CSM = Sema::CXXMoveConstructor;
9758       break;
9759     case oc_implicit_copy_assignment:
9760       CSM = Sema::CXXCopyAssignment;
9761       break;
9762     case oc_implicit_move_assignment:
9763       CSM = Sema::CXXMoveAssignment;
9764       break;
9765     };
9766 
9767     bool ConstRHS = false;
9768     if (Meth->getNumParams()) {
9769       if (const ReferenceType *RT =
9770               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9771         ConstRHS = RT->getPointeeType().isConstQualified();
9772       }
9773     }
9774 
9775     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9776                                               /* ConstRHS */ ConstRHS,
9777                                               /* Diagnose */ true);
9778   }
9779 }
9780 
9781 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9782   FunctionDecl *Callee = Cand->Function;
9783   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9784 
9785   S.Diag(Callee->getLocation(),
9786          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9787       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9788 }
9789 
9790 /// Generates a 'note' diagnostic for an overload candidate.  We've
9791 /// already generated a primary error at the call site.
9792 ///
9793 /// It really does need to be a single diagnostic with its caret
9794 /// pointed at the candidate declaration.  Yes, this creates some
9795 /// major challenges of technical writing.  Yes, this makes pointing
9796 /// out problems with specific arguments quite awkward.  It's still
9797 /// better than generating twenty screens of text for every failed
9798 /// overload.
9799 ///
9800 /// It would be great to be able to express per-candidate problems
9801 /// more richly for those diagnostic clients that cared, but we'd
9802 /// still have to be just as careful with the default diagnostics.
9803 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9804                                   unsigned NumArgs,
9805                                   bool TakingCandidateAddress) {
9806   FunctionDecl *Fn = Cand->Function;
9807 
9808   // Note deleted candidates, but only if they're viable.
9809   if (Cand->Viable && (Fn->isDeleted() ||
9810       S.isFunctionConsideredUnavailable(Fn))) {
9811     std::string FnDesc;
9812     OverloadCandidateKind FnKind =
9813         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9814 
9815     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9816       << FnKind << FnDesc
9817       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9818     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9819     return;
9820   }
9821 
9822   // We don't really have anything else to say about viable candidates.
9823   if (Cand->Viable) {
9824     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9825     return;
9826   }
9827 
9828   switch (Cand->FailureKind) {
9829   case ovl_fail_too_many_arguments:
9830   case ovl_fail_too_few_arguments:
9831     return DiagnoseArityMismatch(S, Cand, NumArgs);
9832 
9833   case ovl_fail_bad_deduction:
9834     return DiagnoseBadDeduction(S, Cand, NumArgs,
9835                                 TakingCandidateAddress);
9836 
9837   case ovl_fail_illegal_constructor: {
9838     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9839       << (Fn->getPrimaryTemplate() ? 1 : 0);
9840     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9841     return;
9842   }
9843 
9844   case ovl_fail_trivial_conversion:
9845   case ovl_fail_bad_final_conversion:
9846   case ovl_fail_final_conversion_not_exact:
9847     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9848 
9849   case ovl_fail_bad_conversion: {
9850     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9851     for (unsigned N = Cand->NumConversions; I != N; ++I)
9852       if (Cand->Conversions[I].isBad())
9853         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9854 
9855     // FIXME: this currently happens when we're called from SemaInit
9856     // when user-conversion overload fails.  Figure out how to handle
9857     // those conditions and diagnose them well.
9858     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9859   }
9860 
9861   case ovl_fail_bad_target:
9862     return DiagnoseBadTarget(S, Cand);
9863 
9864   case ovl_fail_enable_if:
9865     return DiagnoseFailedEnableIfAttr(S, Cand);
9866 
9867   case ovl_fail_addr_not_available: {
9868     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9869     (void)Available;
9870     assert(!Available);
9871     break;
9872   }
9873   }
9874 }
9875 
9876 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9877   // Desugar the type of the surrogate down to a function type,
9878   // retaining as many typedefs as possible while still showing
9879   // the function type (and, therefore, its parameter types).
9880   QualType FnType = Cand->Surrogate->getConversionType();
9881   bool isLValueReference = false;
9882   bool isRValueReference = false;
9883   bool isPointer = false;
9884   if (const LValueReferenceType *FnTypeRef =
9885         FnType->getAs<LValueReferenceType>()) {
9886     FnType = FnTypeRef->getPointeeType();
9887     isLValueReference = true;
9888   } else if (const RValueReferenceType *FnTypeRef =
9889                FnType->getAs<RValueReferenceType>()) {
9890     FnType = FnTypeRef->getPointeeType();
9891     isRValueReference = true;
9892   }
9893   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9894     FnType = FnTypePtr->getPointeeType();
9895     isPointer = true;
9896   }
9897   // Desugar down to a function type.
9898   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9899   // Reconstruct the pointer/reference as appropriate.
9900   if (isPointer) FnType = S.Context.getPointerType(FnType);
9901   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9902   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9903 
9904   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9905     << FnType;
9906 }
9907 
9908 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9909                                          SourceLocation OpLoc,
9910                                          OverloadCandidate *Cand) {
9911   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9912   std::string TypeStr("operator");
9913   TypeStr += Opc;
9914   TypeStr += "(";
9915   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9916   if (Cand->NumConversions == 1) {
9917     TypeStr += ")";
9918     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9919   } else {
9920     TypeStr += ", ";
9921     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9922     TypeStr += ")";
9923     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9924   }
9925 }
9926 
9927 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9928                                          OverloadCandidate *Cand) {
9929   unsigned NoOperands = Cand->NumConversions;
9930   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9931     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9932     if (ICS.isBad()) break; // all meaningless after first invalid
9933     if (!ICS.isAmbiguous()) continue;
9934 
9935     ICS.DiagnoseAmbiguousConversion(
9936         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
9937   }
9938 }
9939 
9940 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9941   if (Cand->Function)
9942     return Cand->Function->getLocation();
9943   if (Cand->IsSurrogate)
9944     return Cand->Surrogate->getLocation();
9945   return SourceLocation();
9946 }
9947 
9948 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9949   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9950   case Sema::TDK_Success:
9951     llvm_unreachable("TDK_success while diagnosing bad deduction");
9952 
9953   case Sema::TDK_Invalid:
9954   case Sema::TDK_Incomplete:
9955     return 1;
9956 
9957   case Sema::TDK_Underqualified:
9958   case Sema::TDK_Inconsistent:
9959     return 2;
9960 
9961   case Sema::TDK_SubstitutionFailure:
9962   case Sema::TDK_DeducedMismatch:
9963   case Sema::TDK_NonDeducedMismatch:
9964   case Sema::TDK_MiscellaneousDeductionFailure:
9965     return 3;
9966 
9967   case Sema::TDK_InstantiationDepth:
9968   case Sema::TDK_FailedOverloadResolution:
9969     return 4;
9970 
9971   case Sema::TDK_InvalidExplicitArguments:
9972     return 5;
9973 
9974   case Sema::TDK_TooManyArguments:
9975   case Sema::TDK_TooFewArguments:
9976     return 6;
9977   }
9978   llvm_unreachable("Unhandled deduction result");
9979 }
9980 
9981 namespace {
9982 struct CompareOverloadCandidatesForDisplay {
9983   Sema &S;
9984   SourceLocation Loc;
9985   size_t NumArgs;
9986 
9987   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9988       : S(S), NumArgs(nArgs) {}
9989 
9990   bool operator()(const OverloadCandidate *L,
9991                   const OverloadCandidate *R) {
9992     // Fast-path this check.
9993     if (L == R) return false;
9994 
9995     // Order first by viability.
9996     if (L->Viable) {
9997       if (!R->Viable) return true;
9998 
9999       // TODO: introduce a tri-valued comparison for overload
10000       // candidates.  Would be more worthwhile if we had a sort
10001       // that could exploit it.
10002       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10003       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10004     } else if (R->Viable)
10005       return false;
10006 
10007     assert(L->Viable == R->Viable);
10008 
10009     // Criteria by which we can sort non-viable candidates:
10010     if (!L->Viable) {
10011       // 1. Arity mismatches come after other candidates.
10012       if (L->FailureKind == ovl_fail_too_many_arguments ||
10013           L->FailureKind == ovl_fail_too_few_arguments) {
10014         if (R->FailureKind == ovl_fail_too_many_arguments ||
10015             R->FailureKind == ovl_fail_too_few_arguments) {
10016           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10017           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10018           if (LDist == RDist) {
10019             if (L->FailureKind == R->FailureKind)
10020               // Sort non-surrogates before surrogates.
10021               return !L->IsSurrogate && R->IsSurrogate;
10022             // Sort candidates requiring fewer parameters than there were
10023             // arguments given after candidates requiring more parameters
10024             // than there were arguments given.
10025             return L->FailureKind == ovl_fail_too_many_arguments;
10026           }
10027           return LDist < RDist;
10028         }
10029         return false;
10030       }
10031       if (R->FailureKind == ovl_fail_too_many_arguments ||
10032           R->FailureKind == ovl_fail_too_few_arguments)
10033         return true;
10034 
10035       // 2. Bad conversions come first and are ordered by the number
10036       // of bad conversions and quality of good conversions.
10037       if (L->FailureKind == ovl_fail_bad_conversion) {
10038         if (R->FailureKind != ovl_fail_bad_conversion)
10039           return true;
10040 
10041         // The conversion that can be fixed with a smaller number of changes,
10042         // comes first.
10043         unsigned numLFixes = L->Fix.NumConversionsFixed;
10044         unsigned numRFixes = R->Fix.NumConversionsFixed;
10045         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10046         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10047         if (numLFixes != numRFixes) {
10048           return numLFixes < numRFixes;
10049         }
10050 
10051         // If there's any ordering between the defined conversions...
10052         // FIXME: this might not be transitive.
10053         assert(L->NumConversions == R->NumConversions);
10054 
10055         int leftBetter = 0;
10056         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10057         for (unsigned E = L->NumConversions; I != E; ++I) {
10058           switch (CompareImplicitConversionSequences(S, Loc,
10059                                                      L->Conversions[I],
10060                                                      R->Conversions[I])) {
10061           case ImplicitConversionSequence::Better:
10062             leftBetter++;
10063             break;
10064 
10065           case ImplicitConversionSequence::Worse:
10066             leftBetter--;
10067             break;
10068 
10069           case ImplicitConversionSequence::Indistinguishable:
10070             break;
10071           }
10072         }
10073         if (leftBetter > 0) return true;
10074         if (leftBetter < 0) return false;
10075 
10076       } else if (R->FailureKind == ovl_fail_bad_conversion)
10077         return false;
10078 
10079       if (L->FailureKind == ovl_fail_bad_deduction) {
10080         if (R->FailureKind != ovl_fail_bad_deduction)
10081           return true;
10082 
10083         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10084           return RankDeductionFailure(L->DeductionFailure)
10085                < RankDeductionFailure(R->DeductionFailure);
10086       } else if (R->FailureKind == ovl_fail_bad_deduction)
10087         return false;
10088 
10089       // TODO: others?
10090     }
10091 
10092     // Sort everything else by location.
10093     SourceLocation LLoc = GetLocationForCandidate(L);
10094     SourceLocation RLoc = GetLocationForCandidate(R);
10095 
10096     // Put candidates without locations (e.g. builtins) at the end.
10097     if (LLoc.isInvalid()) return false;
10098     if (RLoc.isInvalid()) return true;
10099 
10100     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10101   }
10102 };
10103 }
10104 
10105 /// CompleteNonViableCandidate - Normally, overload resolution only
10106 /// computes up to the first. Produces the FixIt set if possible.
10107 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10108                                        ArrayRef<Expr *> Args) {
10109   assert(!Cand->Viable);
10110 
10111   // Don't do anything on failures other than bad conversion.
10112   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10113 
10114   // We only want the FixIts if all the arguments can be corrected.
10115   bool Unfixable = false;
10116   // Use a implicit copy initialization to check conversion fixes.
10117   Cand->Fix.setConversionChecker(TryCopyInitialization);
10118 
10119   // Skip forward to the first bad conversion.
10120   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10121   unsigned ConvCount = Cand->NumConversions;
10122   while (true) {
10123     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10124     ConvIdx++;
10125     if (Cand->Conversions[ConvIdx - 1].isBad()) {
10126       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
10127       break;
10128     }
10129   }
10130 
10131   if (ConvIdx == ConvCount)
10132     return;
10133 
10134   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10135          "remaining conversion is initialized?");
10136 
10137   // FIXME: this should probably be preserved from the overload
10138   // operation somehow.
10139   bool SuppressUserConversions = false;
10140 
10141   const FunctionProtoType* Proto;
10142   unsigned ArgIdx = ConvIdx;
10143 
10144   if (Cand->IsSurrogate) {
10145     QualType ConvType
10146       = Cand->Surrogate->getConversionType().getNonReferenceType();
10147     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10148       ConvType = ConvPtrType->getPointeeType();
10149     Proto = ConvType->getAs<FunctionProtoType>();
10150     ArgIdx--;
10151   } else if (Cand->Function) {
10152     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10153     if (isa<CXXMethodDecl>(Cand->Function) &&
10154         !isa<CXXConstructorDecl>(Cand->Function))
10155       ArgIdx--;
10156   } else {
10157     // Builtin binary operator with a bad first conversion.
10158     assert(ConvCount <= 3);
10159     for (; ConvIdx != ConvCount; ++ConvIdx)
10160       Cand->Conversions[ConvIdx]
10161         = TryCopyInitialization(S, Args[ConvIdx],
10162                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10163                                 SuppressUserConversions,
10164                                 /*InOverloadResolution*/ true,
10165                                 /*AllowObjCWritebackConversion=*/
10166                                   S.getLangOpts().ObjCAutoRefCount);
10167     return;
10168   }
10169 
10170   // Fill in the rest of the conversions.
10171   unsigned NumParams = Proto->getNumParams();
10172   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10173     if (ArgIdx < NumParams) {
10174       Cand->Conversions[ConvIdx] = TryCopyInitialization(
10175           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10176           /*InOverloadResolution=*/true,
10177           /*AllowObjCWritebackConversion=*/
10178           S.getLangOpts().ObjCAutoRefCount);
10179       // Store the FixIt in the candidate if it exists.
10180       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10181         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10182     }
10183     else
10184       Cand->Conversions[ConvIdx].setEllipsis();
10185   }
10186 }
10187 
10188 /// PrintOverloadCandidates - When overload resolution fails, prints
10189 /// diagnostic messages containing the candidates in the candidate
10190 /// set.
10191 void OverloadCandidateSet::NoteCandidates(
10192     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10193     StringRef Opc, SourceLocation OpLoc,
10194     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10195   // Sort the candidates by viability and position.  Sorting directly would
10196   // be prohibitive, so we make a set of pointers and sort those.
10197   SmallVector<OverloadCandidate*, 32> Cands;
10198   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10199   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10200     if (!Filter(*Cand))
10201       continue;
10202     if (Cand->Viable)
10203       Cands.push_back(Cand);
10204     else if (OCD == OCD_AllCandidates) {
10205       CompleteNonViableCandidate(S, Cand, Args);
10206       if (Cand->Function || Cand->IsSurrogate)
10207         Cands.push_back(Cand);
10208       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10209       // want to list every possible builtin candidate.
10210     }
10211   }
10212 
10213   std::sort(Cands.begin(), Cands.end(),
10214             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10215 
10216   bool ReportedAmbiguousConversions = false;
10217 
10218   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10219   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10220   unsigned CandsShown = 0;
10221   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10222     OverloadCandidate *Cand = *I;
10223 
10224     // Set an arbitrary limit on the number of candidate functions we'll spam
10225     // the user with.  FIXME: This limit should depend on details of the
10226     // candidate list.
10227     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10228       break;
10229     }
10230     ++CandsShown;
10231 
10232     if (Cand->Function)
10233       NoteFunctionCandidate(S, Cand, Args.size(),
10234                             /*TakingCandidateAddress=*/false);
10235     else if (Cand->IsSurrogate)
10236       NoteSurrogateCandidate(S, Cand);
10237     else {
10238       assert(Cand->Viable &&
10239              "Non-viable built-in candidates are not added to Cands.");
10240       // Generally we only see ambiguities including viable builtin
10241       // operators if overload resolution got screwed up by an
10242       // ambiguous user-defined conversion.
10243       //
10244       // FIXME: It's quite possible for different conversions to see
10245       // different ambiguities, though.
10246       if (!ReportedAmbiguousConversions) {
10247         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10248         ReportedAmbiguousConversions = true;
10249       }
10250 
10251       // If this is a viable builtin, print it.
10252       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10253     }
10254   }
10255 
10256   if (I != E)
10257     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10258 }
10259 
10260 static SourceLocation
10261 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10262   return Cand->Specialization ? Cand->Specialization->getLocation()
10263                               : SourceLocation();
10264 }
10265 
10266 namespace {
10267 struct CompareTemplateSpecCandidatesForDisplay {
10268   Sema &S;
10269   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10270 
10271   bool operator()(const TemplateSpecCandidate *L,
10272                   const TemplateSpecCandidate *R) {
10273     // Fast-path this check.
10274     if (L == R)
10275       return false;
10276 
10277     // Assuming that both candidates are not matches...
10278 
10279     // Sort by the ranking of deduction failures.
10280     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10281       return RankDeductionFailure(L->DeductionFailure) <
10282              RankDeductionFailure(R->DeductionFailure);
10283 
10284     // Sort everything else by location.
10285     SourceLocation LLoc = GetLocationForCandidate(L);
10286     SourceLocation RLoc = GetLocationForCandidate(R);
10287 
10288     // Put candidates without locations (e.g. builtins) at the end.
10289     if (LLoc.isInvalid())
10290       return false;
10291     if (RLoc.isInvalid())
10292       return true;
10293 
10294     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10295   }
10296 };
10297 }
10298 
10299 /// Diagnose a template argument deduction failure.
10300 /// We are treating these failures as overload failures due to bad
10301 /// deductions.
10302 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10303                                                  bool ForTakingAddress) {
10304   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10305                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10306 }
10307 
10308 void TemplateSpecCandidateSet::destroyCandidates() {
10309   for (iterator i = begin(), e = end(); i != e; ++i) {
10310     i->DeductionFailure.Destroy();
10311   }
10312 }
10313 
10314 void TemplateSpecCandidateSet::clear() {
10315   destroyCandidates();
10316   Candidates.clear();
10317 }
10318 
10319 /// NoteCandidates - When no template specialization match is found, prints
10320 /// diagnostic messages containing the non-matching specializations that form
10321 /// the candidate set.
10322 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10323 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10324 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10325   // Sort the candidates by position (assuming no candidate is a match).
10326   // Sorting directly would be prohibitive, so we make a set of pointers
10327   // and sort those.
10328   SmallVector<TemplateSpecCandidate *, 32> Cands;
10329   Cands.reserve(size());
10330   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10331     if (Cand->Specialization)
10332       Cands.push_back(Cand);
10333     // Otherwise, this is a non-matching builtin candidate.  We do not,
10334     // in general, want to list every possible builtin candidate.
10335   }
10336 
10337   std::sort(Cands.begin(), Cands.end(),
10338             CompareTemplateSpecCandidatesForDisplay(S));
10339 
10340   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10341   // for generalization purposes (?).
10342   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10343 
10344   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10345   unsigned CandsShown = 0;
10346   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10347     TemplateSpecCandidate *Cand = *I;
10348 
10349     // Set an arbitrary limit on the number of candidates we'll spam
10350     // the user with.  FIXME: This limit should depend on details of the
10351     // candidate list.
10352     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10353       break;
10354     ++CandsShown;
10355 
10356     assert(Cand->Specialization &&
10357            "Non-matching built-in candidates are not added to Cands.");
10358     Cand->NoteDeductionFailure(S, ForTakingAddress);
10359   }
10360 
10361   if (I != E)
10362     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10363 }
10364 
10365 // [PossiblyAFunctionType]  -->   [Return]
10366 // NonFunctionType --> NonFunctionType
10367 // R (A) --> R(A)
10368 // R (*)(A) --> R (A)
10369 // R (&)(A) --> R (A)
10370 // R (S::*)(A) --> R (A)
10371 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10372   QualType Ret = PossiblyAFunctionType;
10373   if (const PointerType *ToTypePtr =
10374     PossiblyAFunctionType->getAs<PointerType>())
10375     Ret = ToTypePtr->getPointeeType();
10376   else if (const ReferenceType *ToTypeRef =
10377     PossiblyAFunctionType->getAs<ReferenceType>())
10378     Ret = ToTypeRef->getPointeeType();
10379   else if (const MemberPointerType *MemTypePtr =
10380     PossiblyAFunctionType->getAs<MemberPointerType>())
10381     Ret = MemTypePtr->getPointeeType();
10382   Ret =
10383     Context.getCanonicalType(Ret).getUnqualifiedType();
10384   return Ret;
10385 }
10386 
10387 namespace {
10388 // A helper class to help with address of function resolution
10389 // - allows us to avoid passing around all those ugly parameters
10390 class AddressOfFunctionResolver {
10391   Sema& S;
10392   Expr* SourceExpr;
10393   const QualType& TargetType;
10394   QualType TargetFunctionType; // Extracted function type from target type
10395 
10396   bool Complain;
10397   //DeclAccessPair& ResultFunctionAccessPair;
10398   ASTContext& Context;
10399 
10400   bool TargetTypeIsNonStaticMemberFunction;
10401   bool FoundNonTemplateFunction;
10402   bool StaticMemberFunctionFromBoundPointer;
10403   bool HasComplained;
10404 
10405   OverloadExpr::FindResult OvlExprInfo;
10406   OverloadExpr *OvlExpr;
10407   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10408   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10409   TemplateSpecCandidateSet FailedCandidates;
10410 
10411 public:
10412   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10413                             const QualType &TargetType, bool Complain)
10414       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10415         Complain(Complain), Context(S.getASTContext()),
10416         TargetTypeIsNonStaticMemberFunction(
10417             !!TargetType->getAs<MemberPointerType>()),
10418         FoundNonTemplateFunction(false),
10419         StaticMemberFunctionFromBoundPointer(false),
10420         HasComplained(false),
10421         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10422         OvlExpr(OvlExprInfo.Expression),
10423         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10424     ExtractUnqualifiedFunctionTypeFromTargetType();
10425 
10426     if (TargetFunctionType->isFunctionType()) {
10427       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10428         if (!UME->isImplicitAccess() &&
10429             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10430           StaticMemberFunctionFromBoundPointer = true;
10431     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10432       DeclAccessPair dap;
10433       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10434               OvlExpr, false, &dap)) {
10435         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10436           if (!Method->isStatic()) {
10437             // If the target type is a non-function type and the function found
10438             // is a non-static member function, pretend as if that was the
10439             // target, it's the only possible type to end up with.
10440             TargetTypeIsNonStaticMemberFunction = true;
10441 
10442             // And skip adding the function if its not in the proper form.
10443             // We'll diagnose this due to an empty set of functions.
10444             if (!OvlExprInfo.HasFormOfMemberPointer)
10445               return;
10446           }
10447 
10448         Matches.push_back(std::make_pair(dap, Fn));
10449       }
10450       return;
10451     }
10452 
10453     if (OvlExpr->hasExplicitTemplateArgs())
10454       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10455 
10456     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10457       // C++ [over.over]p4:
10458       //   If more than one function is selected, [...]
10459       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10460         if (FoundNonTemplateFunction)
10461           EliminateAllTemplateMatches();
10462         else
10463           EliminateAllExceptMostSpecializedTemplate();
10464       }
10465     }
10466 
10467     if (S.getLangOpts().CUDA && Matches.size() > 1)
10468       EliminateSuboptimalCudaMatches();
10469   }
10470 
10471   bool hasComplained() const { return HasComplained; }
10472 
10473 private:
10474   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10475     QualType Discard;
10476     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10477            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10478   }
10479 
10480   /// \return true if A is considered a better overload candidate for the
10481   /// desired type than B.
10482   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10483     // If A doesn't have exactly the correct type, we don't want to classify it
10484     // as "better" than anything else. This way, the user is required to
10485     // disambiguate for us if there are multiple candidates and no exact match.
10486     return candidateHasExactlyCorrectType(A) &&
10487            (!candidateHasExactlyCorrectType(B) ||
10488             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10489   }
10490 
10491   /// \return true if we were able to eliminate all but one overload candidate,
10492   /// false otherwise.
10493   bool eliminiateSuboptimalOverloadCandidates() {
10494     // Same algorithm as overload resolution -- one pass to pick the "best",
10495     // another pass to be sure that nothing is better than the best.
10496     auto Best = Matches.begin();
10497     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10498       if (isBetterCandidate(I->second, Best->second))
10499         Best = I;
10500 
10501     const FunctionDecl *BestFn = Best->second;
10502     auto IsBestOrInferiorToBest = [this, BestFn](
10503         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10504       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10505     };
10506 
10507     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10508     // option, so we can potentially give the user a better error
10509     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10510       return false;
10511     Matches[0] = *Best;
10512     Matches.resize(1);
10513     return true;
10514   }
10515 
10516   bool isTargetTypeAFunction() const {
10517     return TargetFunctionType->isFunctionType();
10518   }
10519 
10520   // [ToType]     [Return]
10521 
10522   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10523   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10524   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10525   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10526     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10527   }
10528 
10529   // return true if any matching specializations were found
10530   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10531                                    const DeclAccessPair& CurAccessFunPair) {
10532     if (CXXMethodDecl *Method
10533               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10534       // Skip non-static function templates when converting to pointer, and
10535       // static when converting to member pointer.
10536       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10537         return false;
10538     }
10539     else if (TargetTypeIsNonStaticMemberFunction)
10540       return false;
10541 
10542     // C++ [over.over]p2:
10543     //   If the name is a function template, template argument deduction is
10544     //   done (14.8.2.2), and if the argument deduction succeeds, the
10545     //   resulting template argument list is used to generate a single
10546     //   function template specialization, which is added to the set of
10547     //   overloaded functions considered.
10548     FunctionDecl *Specialization = nullptr;
10549     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10550     if (Sema::TemplateDeductionResult Result
10551           = S.DeduceTemplateArguments(FunctionTemplate,
10552                                       &OvlExplicitTemplateArgs,
10553                                       TargetFunctionType, Specialization,
10554                                       Info, /*InOverloadResolution=*/true)) {
10555       // Make a note of the failed deduction for diagnostics.
10556       FailedCandidates.addCandidate()
10557           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10558                MakeDeductionFailureInfo(Context, Result, Info));
10559       return false;
10560     }
10561 
10562     // Template argument deduction ensures that we have an exact match or
10563     // compatible pointer-to-function arguments that would be adjusted by ICS.
10564     // This function template specicalization works.
10565     assert(S.isSameOrCompatibleFunctionType(
10566               Context.getCanonicalType(Specialization->getType()),
10567               Context.getCanonicalType(TargetFunctionType)));
10568 
10569     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10570       return false;
10571 
10572     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10573     return true;
10574   }
10575 
10576   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10577                                       const DeclAccessPair& CurAccessFunPair) {
10578     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10579       // Skip non-static functions when converting to pointer, and static
10580       // when converting to member pointer.
10581       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10582         return false;
10583     }
10584     else if (TargetTypeIsNonStaticMemberFunction)
10585       return false;
10586 
10587     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10588       if (S.getLangOpts().CUDA)
10589         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10590           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10591             return false;
10592 
10593       // If any candidate has a placeholder return type, trigger its deduction
10594       // now.
10595       if (S.getLangOpts().CPlusPlus14 &&
10596           FunDecl->getReturnType()->isUndeducedType() &&
10597           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10598         HasComplained |= Complain;
10599         return false;
10600       }
10601 
10602       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10603         return false;
10604 
10605       // If we're in C, we need to support types that aren't exactly identical.
10606       if (!S.getLangOpts().CPlusPlus ||
10607           candidateHasExactlyCorrectType(FunDecl)) {
10608         Matches.push_back(std::make_pair(
10609             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10610         FoundNonTemplateFunction = true;
10611         return true;
10612       }
10613     }
10614 
10615     return false;
10616   }
10617 
10618   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10619     bool Ret = false;
10620 
10621     // If the overload expression doesn't have the form of a pointer to
10622     // member, don't try to convert it to a pointer-to-member type.
10623     if (IsInvalidFormOfPointerToMemberFunction())
10624       return false;
10625 
10626     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10627                                E = OvlExpr->decls_end();
10628          I != E; ++I) {
10629       // Look through any using declarations to find the underlying function.
10630       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10631 
10632       // C++ [over.over]p3:
10633       //   Non-member functions and static member functions match
10634       //   targets of type "pointer-to-function" or "reference-to-function."
10635       //   Nonstatic member functions match targets of
10636       //   type "pointer-to-member-function."
10637       // Note that according to DR 247, the containing class does not matter.
10638       if (FunctionTemplateDecl *FunctionTemplate
10639                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10640         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10641           Ret = true;
10642       }
10643       // If we have explicit template arguments supplied, skip non-templates.
10644       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10645                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10646         Ret = true;
10647     }
10648     assert(Ret || Matches.empty());
10649     return Ret;
10650   }
10651 
10652   void EliminateAllExceptMostSpecializedTemplate() {
10653     //   [...] and any given function template specialization F1 is
10654     //   eliminated if the set contains a second function template
10655     //   specialization whose function template is more specialized
10656     //   than the function template of F1 according to the partial
10657     //   ordering rules of 14.5.5.2.
10658 
10659     // The algorithm specified above is quadratic. We instead use a
10660     // two-pass algorithm (similar to the one used to identify the
10661     // best viable function in an overload set) that identifies the
10662     // best function template (if it exists).
10663 
10664     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10665     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10666       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10667 
10668     // TODO: It looks like FailedCandidates does not serve much purpose
10669     // here, since the no_viable diagnostic has index 0.
10670     UnresolvedSetIterator Result = S.getMostSpecialized(
10671         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10672         SourceExpr->getLocStart(), S.PDiag(),
10673         S.PDiag(diag::err_addr_ovl_ambiguous)
10674           << Matches[0].second->getDeclName(),
10675         S.PDiag(diag::note_ovl_candidate)
10676           << (unsigned)oc_function_template,
10677         Complain, TargetFunctionType);
10678 
10679     if (Result != MatchesCopy.end()) {
10680       // Make it the first and only element
10681       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10682       Matches[0].second = cast<FunctionDecl>(*Result);
10683       Matches.resize(1);
10684     } else
10685       HasComplained |= Complain;
10686   }
10687 
10688   void EliminateAllTemplateMatches() {
10689     //   [...] any function template specializations in the set are
10690     //   eliminated if the set also contains a non-template function, [...]
10691     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10692       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10693         ++I;
10694       else {
10695         Matches[I] = Matches[--N];
10696         Matches.resize(N);
10697       }
10698     }
10699   }
10700 
10701   void EliminateSuboptimalCudaMatches() {
10702     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10703   }
10704 
10705 public:
10706   void ComplainNoMatchesFound() const {
10707     assert(Matches.empty());
10708     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10709         << OvlExpr->getName() << TargetFunctionType
10710         << OvlExpr->getSourceRange();
10711     if (FailedCandidates.empty())
10712       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10713                                   /*TakingAddress=*/true);
10714     else {
10715       // We have some deduction failure messages. Use them to diagnose
10716       // the function templates, and diagnose the non-template candidates
10717       // normally.
10718       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10719                                  IEnd = OvlExpr->decls_end();
10720            I != IEnd; ++I)
10721         if (FunctionDecl *Fun =
10722                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10723           if (!functionHasPassObjectSizeParams(Fun))
10724             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10725                                     /*TakingAddress=*/true);
10726       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10727     }
10728   }
10729 
10730   bool IsInvalidFormOfPointerToMemberFunction() const {
10731     return TargetTypeIsNonStaticMemberFunction &&
10732       !OvlExprInfo.HasFormOfMemberPointer;
10733   }
10734 
10735   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10736       // TODO: Should we condition this on whether any functions might
10737       // have matched, or is it more appropriate to do that in callers?
10738       // TODO: a fixit wouldn't hurt.
10739       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10740         << TargetType << OvlExpr->getSourceRange();
10741   }
10742 
10743   bool IsStaticMemberFunctionFromBoundPointer() const {
10744     return StaticMemberFunctionFromBoundPointer;
10745   }
10746 
10747   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10748     S.Diag(OvlExpr->getLocStart(),
10749            diag::err_invalid_form_pointer_member_function)
10750       << OvlExpr->getSourceRange();
10751   }
10752 
10753   void ComplainOfInvalidConversion() const {
10754     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10755       << OvlExpr->getName() << TargetType;
10756   }
10757 
10758   void ComplainMultipleMatchesFound() const {
10759     assert(Matches.size() > 1);
10760     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10761       << OvlExpr->getName()
10762       << OvlExpr->getSourceRange();
10763     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10764                                 /*TakingAddress=*/true);
10765   }
10766 
10767   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10768 
10769   int getNumMatches() const { return Matches.size(); }
10770 
10771   FunctionDecl* getMatchingFunctionDecl() const {
10772     if (Matches.size() != 1) return nullptr;
10773     return Matches[0].second;
10774   }
10775 
10776   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10777     if (Matches.size() != 1) return nullptr;
10778     return &Matches[0].first;
10779   }
10780 };
10781 }
10782 
10783 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10784 /// an overloaded function (C++ [over.over]), where @p From is an
10785 /// expression with overloaded function type and @p ToType is the type
10786 /// we're trying to resolve to. For example:
10787 ///
10788 /// @code
10789 /// int f(double);
10790 /// int f(int);
10791 ///
10792 /// int (*pfd)(double) = f; // selects f(double)
10793 /// @endcode
10794 ///
10795 /// This routine returns the resulting FunctionDecl if it could be
10796 /// resolved, and NULL otherwise. When @p Complain is true, this
10797 /// routine will emit diagnostics if there is an error.
10798 FunctionDecl *
10799 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10800                                          QualType TargetType,
10801                                          bool Complain,
10802                                          DeclAccessPair &FoundResult,
10803                                          bool *pHadMultipleCandidates) {
10804   assert(AddressOfExpr->getType() == Context.OverloadTy);
10805 
10806   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10807                                      Complain);
10808   int NumMatches = Resolver.getNumMatches();
10809   FunctionDecl *Fn = nullptr;
10810   bool ShouldComplain = Complain && !Resolver.hasComplained();
10811   if (NumMatches == 0 && ShouldComplain) {
10812     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10813       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10814     else
10815       Resolver.ComplainNoMatchesFound();
10816   }
10817   else if (NumMatches > 1 && ShouldComplain)
10818     Resolver.ComplainMultipleMatchesFound();
10819   else if (NumMatches == 1) {
10820     Fn = Resolver.getMatchingFunctionDecl();
10821     assert(Fn);
10822     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10823     if (Complain) {
10824       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10825         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10826       else
10827         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10828     }
10829   }
10830 
10831   if (pHadMultipleCandidates)
10832     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10833   return Fn;
10834 }
10835 
10836 /// \brief Given an expression that refers to an overloaded function, try to
10837 /// resolve that function to a single function that can have its address taken.
10838 /// This will modify `Pair` iff it returns non-null.
10839 ///
10840 /// This routine can only realistically succeed if all but one candidates in the
10841 /// overload set for SrcExpr cannot have their addresses taken.
10842 FunctionDecl *
10843 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10844                                                   DeclAccessPair &Pair) {
10845   OverloadExpr::FindResult R = OverloadExpr::find(E);
10846   OverloadExpr *Ovl = R.Expression;
10847   FunctionDecl *Result = nullptr;
10848   DeclAccessPair DAP;
10849   // Don't use the AddressOfResolver because we're specifically looking for
10850   // cases where we have one overload candidate that lacks
10851   // enable_if/pass_object_size/...
10852   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10853     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10854     if (!FD)
10855       return nullptr;
10856 
10857     if (!checkAddressOfFunctionIsAvailable(FD))
10858       continue;
10859 
10860     // We have more than one result; quit.
10861     if (Result)
10862       return nullptr;
10863     DAP = I.getPair();
10864     Result = FD;
10865   }
10866 
10867   if (Result)
10868     Pair = DAP;
10869   return Result;
10870 }
10871 
10872 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
10873 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10874 /// will perform access checks, diagnose the use of the resultant decl, and, if
10875 /// necessary, perform a function-to-pointer decay.
10876 ///
10877 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10878 /// Otherwise, returns true. This may emit diagnostics and return true.
10879 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10880     ExprResult &SrcExpr) {
10881   Expr *E = SrcExpr.get();
10882   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10883 
10884   DeclAccessPair DAP;
10885   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10886   if (!Found)
10887     return false;
10888 
10889   // Emitting multiple diagnostics for a function that is both inaccessible and
10890   // unavailable is consistent with our behavior elsewhere. So, always check
10891   // for both.
10892   DiagnoseUseOfDecl(Found, E->getExprLoc());
10893   CheckAddressOfMemberAccess(E, DAP);
10894   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10895   if (Fixed->getType()->isFunctionType())
10896     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10897   else
10898     SrcExpr = Fixed;
10899   return true;
10900 }
10901 
10902 /// \brief Given an expression that refers to an overloaded function, try to
10903 /// resolve that overloaded function expression down to a single function.
10904 ///
10905 /// This routine can only resolve template-ids that refer to a single function
10906 /// template, where that template-id refers to a single template whose template
10907 /// arguments are either provided by the template-id or have defaults,
10908 /// as described in C++0x [temp.arg.explicit]p3.
10909 ///
10910 /// If no template-ids are found, no diagnostics are emitted and NULL is
10911 /// returned.
10912 FunctionDecl *
10913 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10914                                                   bool Complain,
10915                                                   DeclAccessPair *FoundResult) {
10916   // C++ [over.over]p1:
10917   //   [...] [Note: any redundant set of parentheses surrounding the
10918   //   overloaded function name is ignored (5.1). ]
10919   // C++ [over.over]p1:
10920   //   [...] The overloaded function name can be preceded by the &
10921   //   operator.
10922 
10923   // If we didn't actually find any template-ids, we're done.
10924   if (!ovl->hasExplicitTemplateArgs())
10925     return nullptr;
10926 
10927   TemplateArgumentListInfo ExplicitTemplateArgs;
10928   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10929   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10930 
10931   // Look through all of the overloaded functions, searching for one
10932   // whose type matches exactly.
10933   FunctionDecl *Matched = nullptr;
10934   for (UnresolvedSetIterator I = ovl->decls_begin(),
10935          E = ovl->decls_end(); I != E; ++I) {
10936     // C++0x [temp.arg.explicit]p3:
10937     //   [...] In contexts where deduction is done and fails, or in contexts
10938     //   where deduction is not done, if a template argument list is
10939     //   specified and it, along with any default template arguments,
10940     //   identifies a single function template specialization, then the
10941     //   template-id is an lvalue for the function template specialization.
10942     FunctionTemplateDecl *FunctionTemplate
10943       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10944 
10945     // C++ [over.over]p2:
10946     //   If the name is a function template, template argument deduction is
10947     //   done (14.8.2.2), and if the argument deduction succeeds, the
10948     //   resulting template argument list is used to generate a single
10949     //   function template specialization, which is added to the set of
10950     //   overloaded functions considered.
10951     FunctionDecl *Specialization = nullptr;
10952     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10953     if (TemplateDeductionResult Result
10954           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10955                                     Specialization, Info,
10956                                     /*InOverloadResolution=*/true)) {
10957       // Make a note of the failed deduction for diagnostics.
10958       // TODO: Actually use the failed-deduction info?
10959       FailedCandidates.addCandidate()
10960           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
10961                MakeDeductionFailureInfo(Context, Result, Info));
10962       continue;
10963     }
10964 
10965     assert(Specialization && "no specialization and no error?");
10966 
10967     // Multiple matches; we can't resolve to a single declaration.
10968     if (Matched) {
10969       if (Complain) {
10970         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10971           << ovl->getName();
10972         NoteAllOverloadCandidates(ovl);
10973       }
10974       return nullptr;
10975     }
10976 
10977     Matched = Specialization;
10978     if (FoundResult) *FoundResult = I.getPair();
10979   }
10980 
10981   if (Matched && getLangOpts().CPlusPlus14 &&
10982       Matched->getReturnType()->isUndeducedType() &&
10983       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10984     return nullptr;
10985 
10986   return Matched;
10987 }
10988 
10989 
10990 
10991 
10992 // Resolve and fix an overloaded expression that can be resolved
10993 // because it identifies a single function template specialization.
10994 //
10995 // Last three arguments should only be supplied if Complain = true
10996 //
10997 // Return true if it was logically possible to so resolve the
10998 // expression, regardless of whether or not it succeeded.  Always
10999 // returns true if 'complain' is set.
11000 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11001                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11002                       bool complain, SourceRange OpRangeForComplaining,
11003                                            QualType DestTypeForComplaining,
11004                                             unsigned DiagIDForComplaining) {
11005   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11006 
11007   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11008 
11009   DeclAccessPair found;
11010   ExprResult SingleFunctionExpression;
11011   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11012                            ovl.Expression, /*complain*/ false, &found)) {
11013     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11014       SrcExpr = ExprError();
11015       return true;
11016     }
11017 
11018     // It is only correct to resolve to an instance method if we're
11019     // resolving a form that's permitted to be a pointer to member.
11020     // Otherwise we'll end up making a bound member expression, which
11021     // is illegal in all the contexts we resolve like this.
11022     if (!ovl.HasFormOfMemberPointer &&
11023         isa<CXXMethodDecl>(fn) &&
11024         cast<CXXMethodDecl>(fn)->isInstance()) {
11025       if (!complain) return false;
11026 
11027       Diag(ovl.Expression->getExprLoc(),
11028            diag::err_bound_member_function)
11029         << 0 << ovl.Expression->getSourceRange();
11030 
11031       // TODO: I believe we only end up here if there's a mix of
11032       // static and non-static candidates (otherwise the expression
11033       // would have 'bound member' type, not 'overload' type).
11034       // Ideally we would note which candidate was chosen and why
11035       // the static candidates were rejected.
11036       SrcExpr = ExprError();
11037       return true;
11038     }
11039 
11040     // Fix the expression to refer to 'fn'.
11041     SingleFunctionExpression =
11042         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11043 
11044     // If desired, do function-to-pointer decay.
11045     if (doFunctionPointerConverion) {
11046       SingleFunctionExpression =
11047         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11048       if (SingleFunctionExpression.isInvalid()) {
11049         SrcExpr = ExprError();
11050         return true;
11051       }
11052     }
11053   }
11054 
11055   if (!SingleFunctionExpression.isUsable()) {
11056     if (complain) {
11057       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11058         << ovl.Expression->getName()
11059         << DestTypeForComplaining
11060         << OpRangeForComplaining
11061         << ovl.Expression->getQualifierLoc().getSourceRange();
11062       NoteAllOverloadCandidates(SrcExpr.get());
11063 
11064       SrcExpr = ExprError();
11065       return true;
11066     }
11067 
11068     return false;
11069   }
11070 
11071   SrcExpr = SingleFunctionExpression;
11072   return true;
11073 }
11074 
11075 /// \brief Add a single candidate to the overload set.
11076 static void AddOverloadedCallCandidate(Sema &S,
11077                                        DeclAccessPair FoundDecl,
11078                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11079                                        ArrayRef<Expr *> Args,
11080                                        OverloadCandidateSet &CandidateSet,
11081                                        bool PartialOverloading,
11082                                        bool KnownValid) {
11083   NamedDecl *Callee = FoundDecl.getDecl();
11084   if (isa<UsingShadowDecl>(Callee))
11085     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11086 
11087   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11088     if (ExplicitTemplateArgs) {
11089       assert(!KnownValid && "Explicit template arguments?");
11090       return;
11091     }
11092     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11093                            /*SuppressUsedConversions=*/false,
11094                            PartialOverloading);
11095     return;
11096   }
11097 
11098   if (FunctionTemplateDecl *FuncTemplate
11099       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11100     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11101                                    ExplicitTemplateArgs, Args, CandidateSet,
11102                                    /*SuppressUsedConversions=*/false,
11103                                    PartialOverloading);
11104     return;
11105   }
11106 
11107   assert(!KnownValid && "unhandled case in overloaded call candidate");
11108 }
11109 
11110 /// \brief Add the overload candidates named by callee and/or found by argument
11111 /// dependent lookup to the given overload set.
11112 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11113                                        ArrayRef<Expr *> Args,
11114                                        OverloadCandidateSet &CandidateSet,
11115                                        bool PartialOverloading) {
11116 
11117 #ifndef NDEBUG
11118   // Verify that ArgumentDependentLookup is consistent with the rules
11119   // in C++0x [basic.lookup.argdep]p3:
11120   //
11121   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11122   //   and let Y be the lookup set produced by argument dependent
11123   //   lookup (defined as follows). If X contains
11124   //
11125   //     -- a declaration of a class member, or
11126   //
11127   //     -- a block-scope function declaration that is not a
11128   //        using-declaration, or
11129   //
11130   //     -- a declaration that is neither a function or a function
11131   //        template
11132   //
11133   //   then Y is empty.
11134 
11135   if (ULE->requiresADL()) {
11136     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11137            E = ULE->decls_end(); I != E; ++I) {
11138       assert(!(*I)->getDeclContext()->isRecord());
11139       assert(isa<UsingShadowDecl>(*I) ||
11140              !(*I)->getDeclContext()->isFunctionOrMethod());
11141       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11142     }
11143   }
11144 #endif
11145 
11146   // It would be nice to avoid this copy.
11147   TemplateArgumentListInfo TABuffer;
11148   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11149   if (ULE->hasExplicitTemplateArgs()) {
11150     ULE->copyTemplateArgumentsInto(TABuffer);
11151     ExplicitTemplateArgs = &TABuffer;
11152   }
11153 
11154   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11155          E = ULE->decls_end(); I != E; ++I)
11156     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11157                                CandidateSet, PartialOverloading,
11158                                /*KnownValid*/ true);
11159 
11160   if (ULE->requiresADL())
11161     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11162                                          Args, ExplicitTemplateArgs,
11163                                          CandidateSet, PartialOverloading);
11164 }
11165 
11166 /// Determine whether a declaration with the specified name could be moved into
11167 /// a different namespace.
11168 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11169   switch (Name.getCXXOverloadedOperator()) {
11170   case OO_New: case OO_Array_New:
11171   case OO_Delete: case OO_Array_Delete:
11172     return false;
11173 
11174   default:
11175     return true;
11176   }
11177 }
11178 
11179 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11180 /// template, where the non-dependent name was declared after the template
11181 /// was defined. This is common in code written for a compilers which do not
11182 /// correctly implement two-stage name lookup.
11183 ///
11184 /// Returns true if a viable candidate was found and a diagnostic was issued.
11185 static bool
11186 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11187                        const CXXScopeSpec &SS, LookupResult &R,
11188                        OverloadCandidateSet::CandidateSetKind CSK,
11189                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11190                        ArrayRef<Expr *> Args,
11191                        bool *DoDiagnoseEmptyLookup = nullptr) {
11192   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11193     return false;
11194 
11195   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11196     if (DC->isTransparentContext())
11197       continue;
11198 
11199     SemaRef.LookupQualifiedName(R, DC);
11200 
11201     if (!R.empty()) {
11202       R.suppressDiagnostics();
11203 
11204       if (isa<CXXRecordDecl>(DC)) {
11205         // Don't diagnose names we find in classes; we get much better
11206         // diagnostics for these from DiagnoseEmptyLookup.
11207         R.clear();
11208         if (DoDiagnoseEmptyLookup)
11209           *DoDiagnoseEmptyLookup = true;
11210         return false;
11211       }
11212 
11213       OverloadCandidateSet Candidates(FnLoc, CSK);
11214       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11215         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11216                                    ExplicitTemplateArgs, Args,
11217                                    Candidates, false, /*KnownValid*/ false);
11218 
11219       OverloadCandidateSet::iterator Best;
11220       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11221         // No viable functions. Don't bother the user with notes for functions
11222         // which don't work and shouldn't be found anyway.
11223         R.clear();
11224         return false;
11225       }
11226 
11227       // Find the namespaces where ADL would have looked, and suggest
11228       // declaring the function there instead.
11229       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11230       Sema::AssociatedClassSet AssociatedClasses;
11231       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11232                                                  AssociatedNamespaces,
11233                                                  AssociatedClasses);
11234       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11235       if (canBeDeclaredInNamespace(R.getLookupName())) {
11236         DeclContext *Std = SemaRef.getStdNamespace();
11237         for (Sema::AssociatedNamespaceSet::iterator
11238                it = AssociatedNamespaces.begin(),
11239                end = AssociatedNamespaces.end(); it != end; ++it) {
11240           // Never suggest declaring a function within namespace 'std'.
11241           if (Std && Std->Encloses(*it))
11242             continue;
11243 
11244           // Never suggest declaring a function within a namespace with a
11245           // reserved name, like __gnu_cxx.
11246           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11247           if (NS &&
11248               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11249             continue;
11250 
11251           SuggestedNamespaces.insert(*it);
11252         }
11253       }
11254 
11255       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11256         << R.getLookupName();
11257       if (SuggestedNamespaces.empty()) {
11258         SemaRef.Diag(Best->Function->getLocation(),
11259                      diag::note_not_found_by_two_phase_lookup)
11260           << R.getLookupName() << 0;
11261       } else if (SuggestedNamespaces.size() == 1) {
11262         SemaRef.Diag(Best->Function->getLocation(),
11263                      diag::note_not_found_by_two_phase_lookup)
11264           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11265       } else {
11266         // FIXME: It would be useful to list the associated namespaces here,
11267         // but the diagnostics infrastructure doesn't provide a way to produce
11268         // a localized representation of a list of items.
11269         SemaRef.Diag(Best->Function->getLocation(),
11270                      diag::note_not_found_by_two_phase_lookup)
11271           << R.getLookupName() << 2;
11272       }
11273 
11274       // Try to recover by calling this function.
11275       return true;
11276     }
11277 
11278     R.clear();
11279   }
11280 
11281   return false;
11282 }
11283 
11284 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11285 /// template, where the non-dependent operator was declared after the template
11286 /// was defined.
11287 ///
11288 /// Returns true if a viable candidate was found and a diagnostic was issued.
11289 static bool
11290 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11291                                SourceLocation OpLoc,
11292                                ArrayRef<Expr *> Args) {
11293   DeclarationName OpName =
11294     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11295   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11296   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11297                                 OverloadCandidateSet::CSK_Operator,
11298                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11299 }
11300 
11301 namespace {
11302 class BuildRecoveryCallExprRAII {
11303   Sema &SemaRef;
11304 public:
11305   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11306     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11307     SemaRef.IsBuildingRecoveryCallExpr = true;
11308   }
11309 
11310   ~BuildRecoveryCallExprRAII() {
11311     SemaRef.IsBuildingRecoveryCallExpr = false;
11312   }
11313 };
11314 
11315 }
11316 
11317 static std::unique_ptr<CorrectionCandidateCallback>
11318 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11319               bool HasTemplateArgs, bool AllowTypoCorrection) {
11320   if (!AllowTypoCorrection)
11321     return llvm::make_unique<NoTypoCorrectionCCC>();
11322   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11323                                                   HasTemplateArgs, ME);
11324 }
11325 
11326 /// Attempts to recover from a call where no functions were found.
11327 ///
11328 /// Returns true if new candidates were found.
11329 static ExprResult
11330 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11331                       UnresolvedLookupExpr *ULE,
11332                       SourceLocation LParenLoc,
11333                       MutableArrayRef<Expr *> Args,
11334                       SourceLocation RParenLoc,
11335                       bool EmptyLookup, bool AllowTypoCorrection) {
11336   // Do not try to recover if it is already building a recovery call.
11337   // This stops infinite loops for template instantiations like
11338   //
11339   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11340   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11341   //
11342   if (SemaRef.IsBuildingRecoveryCallExpr)
11343     return ExprError();
11344   BuildRecoveryCallExprRAII RCE(SemaRef);
11345 
11346   CXXScopeSpec SS;
11347   SS.Adopt(ULE->getQualifierLoc());
11348   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11349 
11350   TemplateArgumentListInfo TABuffer;
11351   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11352   if (ULE->hasExplicitTemplateArgs()) {
11353     ULE->copyTemplateArgumentsInto(TABuffer);
11354     ExplicitTemplateArgs = &TABuffer;
11355   }
11356 
11357   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11358                  Sema::LookupOrdinaryName);
11359   bool DoDiagnoseEmptyLookup = EmptyLookup;
11360   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11361                               OverloadCandidateSet::CSK_Normal,
11362                               ExplicitTemplateArgs, Args,
11363                               &DoDiagnoseEmptyLookup) &&
11364     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11365         S, SS, R,
11366         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11367                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11368         ExplicitTemplateArgs, Args)))
11369     return ExprError();
11370 
11371   assert(!R.empty() && "lookup results empty despite recovery");
11372 
11373   // Build an implicit member call if appropriate.  Just drop the
11374   // casts and such from the call, we don't really care.
11375   ExprResult NewFn = ExprError();
11376   if ((*R.begin())->isCXXClassMember())
11377     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11378                                                     ExplicitTemplateArgs, S);
11379   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11380     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11381                                         ExplicitTemplateArgs);
11382   else
11383     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11384 
11385   if (NewFn.isInvalid())
11386     return ExprError();
11387 
11388   // This shouldn't cause an infinite loop because we're giving it
11389   // an expression with viable lookup results, which should never
11390   // end up here.
11391   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11392                                MultiExprArg(Args.data(), Args.size()),
11393                                RParenLoc);
11394 }
11395 
11396 /// \brief Constructs and populates an OverloadedCandidateSet from
11397 /// the given function.
11398 /// \returns true when an the ExprResult output parameter has been set.
11399 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11400                                   UnresolvedLookupExpr *ULE,
11401                                   MultiExprArg Args,
11402                                   SourceLocation RParenLoc,
11403                                   OverloadCandidateSet *CandidateSet,
11404                                   ExprResult *Result) {
11405 #ifndef NDEBUG
11406   if (ULE->requiresADL()) {
11407     // To do ADL, we must have found an unqualified name.
11408     assert(!ULE->getQualifier() && "qualified name with ADL");
11409 
11410     // We don't perform ADL for implicit declarations of builtins.
11411     // Verify that this was correctly set up.
11412     FunctionDecl *F;
11413     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11414         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11415         F->getBuiltinID() && F->isImplicit())
11416       llvm_unreachable("performing ADL for builtin");
11417 
11418     // We don't perform ADL in C.
11419     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11420   }
11421 #endif
11422 
11423   UnbridgedCastsSet UnbridgedCasts;
11424   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11425     *Result = ExprError();
11426     return true;
11427   }
11428 
11429   // Add the functions denoted by the callee to the set of candidate
11430   // functions, including those from argument-dependent lookup.
11431   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11432 
11433   if (getLangOpts().MSVCCompat &&
11434       CurContext->isDependentContext() && !isSFINAEContext() &&
11435       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11436 
11437     OverloadCandidateSet::iterator Best;
11438     if (CandidateSet->empty() ||
11439         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11440             OR_No_Viable_Function) {
11441       // In Microsoft mode, if we are inside a template class member function then
11442       // create a type dependent CallExpr. The goal is to postpone name lookup
11443       // to instantiation time to be able to search into type dependent base
11444       // classes.
11445       CallExpr *CE = new (Context) CallExpr(
11446           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11447       CE->setTypeDependent(true);
11448       CE->setValueDependent(true);
11449       CE->setInstantiationDependent(true);
11450       *Result = CE;
11451       return true;
11452     }
11453   }
11454 
11455   if (CandidateSet->empty())
11456     return false;
11457 
11458   UnbridgedCasts.restore();
11459   return false;
11460 }
11461 
11462 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11463 /// the completed call expression. If overload resolution fails, emits
11464 /// diagnostics and returns ExprError()
11465 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11466                                            UnresolvedLookupExpr *ULE,
11467                                            SourceLocation LParenLoc,
11468                                            MultiExprArg Args,
11469                                            SourceLocation RParenLoc,
11470                                            Expr *ExecConfig,
11471                                            OverloadCandidateSet *CandidateSet,
11472                                            OverloadCandidateSet::iterator *Best,
11473                                            OverloadingResult OverloadResult,
11474                                            bool AllowTypoCorrection) {
11475   if (CandidateSet->empty())
11476     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11477                                  RParenLoc, /*EmptyLookup=*/true,
11478                                  AllowTypoCorrection);
11479 
11480   switch (OverloadResult) {
11481   case OR_Success: {
11482     FunctionDecl *FDecl = (*Best)->Function;
11483     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11484     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11485       return ExprError();
11486     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11487     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11488                                          ExecConfig);
11489   }
11490 
11491   case OR_No_Viable_Function: {
11492     // Try to recover by looking for viable functions which the user might
11493     // have meant to call.
11494     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11495                                                 Args, RParenLoc,
11496                                                 /*EmptyLookup=*/false,
11497                                                 AllowTypoCorrection);
11498     if (!Recovery.isInvalid())
11499       return Recovery;
11500 
11501     // If the user passes in a function that we can't take the address of, we
11502     // generally end up emitting really bad error messages. Here, we attempt to
11503     // emit better ones.
11504     for (const Expr *Arg : Args) {
11505       if (!Arg->getType()->isFunctionType())
11506         continue;
11507       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11508         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11509         if (FD &&
11510             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11511                                                        Arg->getExprLoc()))
11512           return ExprError();
11513       }
11514     }
11515 
11516     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11517         << ULE->getName() << Fn->getSourceRange();
11518     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11519     break;
11520   }
11521 
11522   case OR_Ambiguous:
11523     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11524       << ULE->getName() << Fn->getSourceRange();
11525     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11526     break;
11527 
11528   case OR_Deleted: {
11529     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11530       << (*Best)->Function->isDeleted()
11531       << ULE->getName()
11532       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11533       << Fn->getSourceRange();
11534     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11535 
11536     // We emitted an error for the unvailable/deleted function call but keep
11537     // the call in the AST.
11538     FunctionDecl *FDecl = (*Best)->Function;
11539     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11540     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11541                                          ExecConfig);
11542   }
11543   }
11544 
11545   // Overload resolution failed.
11546   return ExprError();
11547 }
11548 
11549 static void markUnaddressableCandidatesUnviable(Sema &S,
11550                                                 OverloadCandidateSet &CS) {
11551   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11552     if (I->Viable &&
11553         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11554       I->Viable = false;
11555       I->FailureKind = ovl_fail_addr_not_available;
11556     }
11557   }
11558 }
11559 
11560 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11561 /// (which eventually refers to the declaration Func) and the call
11562 /// arguments Args/NumArgs, attempt to resolve the function call down
11563 /// to a specific function. If overload resolution succeeds, returns
11564 /// the call expression produced by overload resolution.
11565 /// Otherwise, emits diagnostics and returns ExprError.
11566 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11567                                          UnresolvedLookupExpr *ULE,
11568                                          SourceLocation LParenLoc,
11569                                          MultiExprArg Args,
11570                                          SourceLocation RParenLoc,
11571                                          Expr *ExecConfig,
11572                                          bool AllowTypoCorrection,
11573                                          bool CalleesAddressIsTaken) {
11574   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11575                                     OverloadCandidateSet::CSK_Normal);
11576   ExprResult result;
11577 
11578   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11579                              &result))
11580     return result;
11581 
11582   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11583   // functions that aren't addressible are considered unviable.
11584   if (CalleesAddressIsTaken)
11585     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11586 
11587   OverloadCandidateSet::iterator Best;
11588   OverloadingResult OverloadResult =
11589       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11590 
11591   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11592                                   RParenLoc, ExecConfig, &CandidateSet,
11593                                   &Best, OverloadResult,
11594                                   AllowTypoCorrection);
11595 }
11596 
11597 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11598   return Functions.size() > 1 ||
11599     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11600 }
11601 
11602 /// \brief Create a unary operation that may resolve to an overloaded
11603 /// operator.
11604 ///
11605 /// \param OpLoc The location of the operator itself (e.g., '*').
11606 ///
11607 /// \param Opc The UnaryOperatorKind that describes this operator.
11608 ///
11609 /// \param Fns The set of non-member functions that will be
11610 /// considered by overload resolution. The caller needs to build this
11611 /// set based on the context using, e.g.,
11612 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11613 /// set should not contain any member functions; those will be added
11614 /// by CreateOverloadedUnaryOp().
11615 ///
11616 /// \param Input The input argument.
11617 ExprResult
11618 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11619                               const UnresolvedSetImpl &Fns,
11620                               Expr *Input) {
11621   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11622   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11623   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11624   // TODO: provide better source location info.
11625   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11626 
11627   if (checkPlaceholderForOverload(*this, Input))
11628     return ExprError();
11629 
11630   Expr *Args[2] = { Input, nullptr };
11631   unsigned NumArgs = 1;
11632 
11633   // For post-increment and post-decrement, add the implicit '0' as
11634   // the second argument, so that we know this is a post-increment or
11635   // post-decrement.
11636   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11637     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11638     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11639                                      SourceLocation());
11640     NumArgs = 2;
11641   }
11642 
11643   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11644 
11645   if (Input->isTypeDependent()) {
11646     if (Fns.empty())
11647       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11648                                          VK_RValue, OK_Ordinary, OpLoc);
11649 
11650     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11651     UnresolvedLookupExpr *Fn
11652       = UnresolvedLookupExpr::Create(Context, NamingClass,
11653                                      NestedNameSpecifierLoc(), OpNameInfo,
11654                                      /*ADL*/ true, IsOverloaded(Fns),
11655                                      Fns.begin(), Fns.end());
11656     return new (Context)
11657         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11658                             VK_RValue, OpLoc, false);
11659   }
11660 
11661   // Build an empty overload set.
11662   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11663 
11664   // Add the candidates from the given function set.
11665   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11666 
11667   // Add operator candidates that are member functions.
11668   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11669 
11670   // Add candidates from ADL.
11671   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11672                                        /*ExplicitTemplateArgs*/nullptr,
11673                                        CandidateSet);
11674 
11675   // Add builtin operator candidates.
11676   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11677 
11678   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11679 
11680   // Perform overload resolution.
11681   OverloadCandidateSet::iterator Best;
11682   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11683   case OR_Success: {
11684     // We found a built-in operator or an overloaded operator.
11685     FunctionDecl *FnDecl = Best->Function;
11686 
11687     if (FnDecl) {
11688       // We matched an overloaded operator. Build a call to that
11689       // operator.
11690 
11691       // Convert the arguments.
11692       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11693         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11694 
11695         ExprResult InputRes =
11696           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11697                                               Best->FoundDecl, Method);
11698         if (InputRes.isInvalid())
11699           return ExprError();
11700         Input = InputRes.get();
11701       } else {
11702         // Convert the arguments.
11703         ExprResult InputInit
11704           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11705                                                       Context,
11706                                                       FnDecl->getParamDecl(0)),
11707                                       SourceLocation(),
11708                                       Input);
11709         if (InputInit.isInvalid())
11710           return ExprError();
11711         Input = InputInit.get();
11712       }
11713 
11714       // Build the actual expression node.
11715       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11716                                                 HadMultipleCandidates, OpLoc);
11717       if (FnExpr.isInvalid())
11718         return ExprError();
11719 
11720       // Determine the result type.
11721       QualType ResultTy = FnDecl->getReturnType();
11722       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11723       ResultTy = ResultTy.getNonLValueExprType(Context);
11724 
11725       Args[0] = Input;
11726       CallExpr *TheCall =
11727         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11728                                           ResultTy, VK, OpLoc, false);
11729 
11730       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11731         return ExprError();
11732 
11733       return MaybeBindToTemporary(TheCall);
11734     } else {
11735       // We matched a built-in operator. Convert the arguments, then
11736       // break out so that we will build the appropriate built-in
11737       // operator node.
11738       ExprResult InputRes =
11739         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11740                                   Best->Conversions[0], AA_Passing);
11741       if (InputRes.isInvalid())
11742         return ExprError();
11743       Input = InputRes.get();
11744       break;
11745     }
11746   }
11747 
11748   case OR_No_Viable_Function:
11749     // This is an erroneous use of an operator which can be overloaded by
11750     // a non-member function. Check for non-member operators which were
11751     // defined too late to be candidates.
11752     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11753       // FIXME: Recover by calling the found function.
11754       return ExprError();
11755 
11756     // No viable function; fall through to handling this as a
11757     // built-in operator, which will produce an error message for us.
11758     break;
11759 
11760   case OR_Ambiguous:
11761     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11762         << UnaryOperator::getOpcodeStr(Opc)
11763         << Input->getType()
11764         << Input->getSourceRange();
11765     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11766                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11767     return ExprError();
11768 
11769   case OR_Deleted:
11770     Diag(OpLoc, diag::err_ovl_deleted_oper)
11771       << Best->Function->isDeleted()
11772       << UnaryOperator::getOpcodeStr(Opc)
11773       << getDeletedOrUnavailableSuffix(Best->Function)
11774       << Input->getSourceRange();
11775     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11776                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11777     return ExprError();
11778   }
11779 
11780   // Either we found no viable overloaded operator or we matched a
11781   // built-in operator. In either case, fall through to trying to
11782   // build a built-in operation.
11783   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11784 }
11785 
11786 /// \brief Create a binary operation that may resolve to an overloaded
11787 /// operator.
11788 ///
11789 /// \param OpLoc The location of the operator itself (e.g., '+').
11790 ///
11791 /// \param Opc The BinaryOperatorKind that describes this operator.
11792 ///
11793 /// \param Fns The set of non-member functions that will be
11794 /// considered by overload resolution. The caller needs to build this
11795 /// set based on the context using, e.g.,
11796 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11797 /// set should not contain any member functions; those will be added
11798 /// by CreateOverloadedBinOp().
11799 ///
11800 /// \param LHS Left-hand argument.
11801 /// \param RHS Right-hand argument.
11802 ExprResult
11803 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11804                             BinaryOperatorKind Opc,
11805                             const UnresolvedSetImpl &Fns,
11806                             Expr *LHS, Expr *RHS) {
11807   Expr *Args[2] = { LHS, RHS };
11808   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11809 
11810   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11811   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11812 
11813   // If either side is type-dependent, create an appropriate dependent
11814   // expression.
11815   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11816     if (Fns.empty()) {
11817       // If there are no functions to store, just build a dependent
11818       // BinaryOperator or CompoundAssignment.
11819       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11820         return new (Context) BinaryOperator(
11821             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11822             OpLoc, FPFeatures.fp_contract);
11823 
11824       return new (Context) CompoundAssignOperator(
11825           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11826           Context.DependentTy, Context.DependentTy, OpLoc,
11827           FPFeatures.fp_contract);
11828     }
11829 
11830     // FIXME: save results of ADL from here?
11831     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11832     // TODO: provide better source location info in DNLoc component.
11833     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11834     UnresolvedLookupExpr *Fn
11835       = UnresolvedLookupExpr::Create(Context, NamingClass,
11836                                      NestedNameSpecifierLoc(), OpNameInfo,
11837                                      /*ADL*/ true, IsOverloaded(Fns),
11838                                      Fns.begin(), Fns.end());
11839     return new (Context)
11840         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11841                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11842   }
11843 
11844   // Always do placeholder-like conversions on the RHS.
11845   if (checkPlaceholderForOverload(*this, Args[1]))
11846     return ExprError();
11847 
11848   // Do placeholder-like conversion on the LHS; note that we should
11849   // not get here with a PseudoObject LHS.
11850   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11851   if (checkPlaceholderForOverload(*this, Args[0]))
11852     return ExprError();
11853 
11854   // If this is the assignment operator, we only perform overload resolution
11855   // if the left-hand side is a class or enumeration type. This is actually
11856   // a hack. The standard requires that we do overload resolution between the
11857   // various built-in candidates, but as DR507 points out, this can lead to
11858   // problems. So we do it this way, which pretty much follows what GCC does.
11859   // Note that we go the traditional code path for compound assignment forms.
11860   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11861     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11862 
11863   // If this is the .* operator, which is not overloadable, just
11864   // create a built-in binary operator.
11865   if (Opc == BO_PtrMemD)
11866     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11867 
11868   // Build an empty overload set.
11869   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11870 
11871   // Add the candidates from the given function set.
11872   AddFunctionCandidates(Fns, Args, CandidateSet);
11873 
11874   // Add operator candidates that are member functions.
11875   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11876 
11877   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11878   // performed for an assignment operator (nor for operator[] nor operator->,
11879   // which don't get here).
11880   if (Opc != BO_Assign)
11881     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11882                                          /*ExplicitTemplateArgs*/ nullptr,
11883                                          CandidateSet);
11884 
11885   // Add builtin operator candidates.
11886   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11887 
11888   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11889 
11890   // Perform overload resolution.
11891   OverloadCandidateSet::iterator Best;
11892   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11893     case OR_Success: {
11894       // We found a built-in operator or an overloaded operator.
11895       FunctionDecl *FnDecl = Best->Function;
11896 
11897       if (FnDecl) {
11898         // We matched an overloaded operator. Build a call to that
11899         // operator.
11900 
11901         // Convert the arguments.
11902         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11903           // Best->Access is only meaningful for class members.
11904           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11905 
11906           ExprResult Arg1 =
11907             PerformCopyInitialization(
11908               InitializedEntity::InitializeParameter(Context,
11909                                                      FnDecl->getParamDecl(0)),
11910               SourceLocation(), Args[1]);
11911           if (Arg1.isInvalid())
11912             return ExprError();
11913 
11914           ExprResult Arg0 =
11915             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11916                                                 Best->FoundDecl, Method);
11917           if (Arg0.isInvalid())
11918             return ExprError();
11919           Args[0] = Arg0.getAs<Expr>();
11920           Args[1] = RHS = Arg1.getAs<Expr>();
11921         } else {
11922           // Convert the arguments.
11923           ExprResult Arg0 = PerformCopyInitialization(
11924             InitializedEntity::InitializeParameter(Context,
11925                                                    FnDecl->getParamDecl(0)),
11926             SourceLocation(), Args[0]);
11927           if (Arg0.isInvalid())
11928             return ExprError();
11929 
11930           ExprResult Arg1 =
11931             PerformCopyInitialization(
11932               InitializedEntity::InitializeParameter(Context,
11933                                                      FnDecl->getParamDecl(1)),
11934               SourceLocation(), Args[1]);
11935           if (Arg1.isInvalid())
11936             return ExprError();
11937           Args[0] = LHS = Arg0.getAs<Expr>();
11938           Args[1] = RHS = Arg1.getAs<Expr>();
11939         }
11940 
11941         // Build the actual expression node.
11942         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11943                                                   Best->FoundDecl,
11944                                                   HadMultipleCandidates, OpLoc);
11945         if (FnExpr.isInvalid())
11946           return ExprError();
11947 
11948         // Determine the result type.
11949         QualType ResultTy = FnDecl->getReturnType();
11950         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11951         ResultTy = ResultTy.getNonLValueExprType(Context);
11952 
11953         CXXOperatorCallExpr *TheCall =
11954           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11955                                             Args, ResultTy, VK, OpLoc,
11956                                             FPFeatures.fp_contract);
11957 
11958         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11959                                 FnDecl))
11960           return ExprError();
11961 
11962         ArrayRef<const Expr *> ArgsArray(Args, 2);
11963         // Cut off the implicit 'this'.
11964         if (isa<CXXMethodDecl>(FnDecl))
11965           ArgsArray = ArgsArray.slice(1);
11966 
11967         // Check for a self move.
11968         if (Op == OO_Equal)
11969           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11970 
11971         checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11972                   TheCall->getSourceRange(), VariadicDoesNotApply);
11973 
11974         return MaybeBindToTemporary(TheCall);
11975       } else {
11976         // We matched a built-in operator. Convert the arguments, then
11977         // break out so that we will build the appropriate built-in
11978         // operator node.
11979         ExprResult ArgsRes0 =
11980           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11981                                     Best->Conversions[0], AA_Passing);
11982         if (ArgsRes0.isInvalid())
11983           return ExprError();
11984         Args[0] = ArgsRes0.get();
11985 
11986         ExprResult ArgsRes1 =
11987           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11988                                     Best->Conversions[1], AA_Passing);
11989         if (ArgsRes1.isInvalid())
11990           return ExprError();
11991         Args[1] = ArgsRes1.get();
11992         break;
11993       }
11994     }
11995 
11996     case OR_No_Viable_Function: {
11997       // C++ [over.match.oper]p9:
11998       //   If the operator is the operator , [...] and there are no
11999       //   viable functions, then the operator is assumed to be the
12000       //   built-in operator and interpreted according to clause 5.
12001       if (Opc == BO_Comma)
12002         break;
12003 
12004       // For class as left operand for assignment or compound assigment
12005       // operator do not fall through to handling in built-in, but report that
12006       // no overloaded assignment operator found
12007       ExprResult Result = ExprError();
12008       if (Args[0]->getType()->isRecordType() &&
12009           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12010         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12011              << BinaryOperator::getOpcodeStr(Opc)
12012              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12013         if (Args[0]->getType()->isIncompleteType()) {
12014           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12015             << Args[0]->getType()
12016             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12017         }
12018       } else {
12019         // This is an erroneous use of an operator which can be overloaded by
12020         // a non-member function. Check for non-member operators which were
12021         // defined too late to be candidates.
12022         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12023           // FIXME: Recover by calling the found function.
12024           return ExprError();
12025 
12026         // No viable function; try to create a built-in operation, which will
12027         // produce an error. Then, show the non-viable candidates.
12028         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12029       }
12030       assert(Result.isInvalid() &&
12031              "C++ binary operator overloading is missing candidates!");
12032       if (Result.isInvalid())
12033         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12034                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12035       return Result;
12036     }
12037 
12038     case OR_Ambiguous:
12039       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12040           << BinaryOperator::getOpcodeStr(Opc)
12041           << Args[0]->getType() << Args[1]->getType()
12042           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12043       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12044                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12045       return ExprError();
12046 
12047     case OR_Deleted:
12048       if (isImplicitlyDeleted(Best->Function)) {
12049         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12050         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12051           << Context.getRecordType(Method->getParent())
12052           << getSpecialMember(Method);
12053 
12054         // The user probably meant to call this special member. Just
12055         // explain why it's deleted.
12056         NoteDeletedFunction(Method);
12057         return ExprError();
12058       } else {
12059         Diag(OpLoc, diag::err_ovl_deleted_oper)
12060           << Best->Function->isDeleted()
12061           << BinaryOperator::getOpcodeStr(Opc)
12062           << getDeletedOrUnavailableSuffix(Best->Function)
12063           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12064       }
12065       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12066                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12067       return ExprError();
12068   }
12069 
12070   // We matched a built-in operator; build it.
12071   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12072 }
12073 
12074 ExprResult
12075 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12076                                          SourceLocation RLoc,
12077                                          Expr *Base, Expr *Idx) {
12078   Expr *Args[2] = { Base, Idx };
12079   DeclarationName OpName =
12080       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12081 
12082   // If either side is type-dependent, create an appropriate dependent
12083   // expression.
12084   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12085 
12086     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12087     // CHECKME: no 'operator' keyword?
12088     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12089     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12090     UnresolvedLookupExpr *Fn
12091       = UnresolvedLookupExpr::Create(Context, NamingClass,
12092                                      NestedNameSpecifierLoc(), OpNameInfo,
12093                                      /*ADL*/ true, /*Overloaded*/ false,
12094                                      UnresolvedSetIterator(),
12095                                      UnresolvedSetIterator());
12096     // Can't add any actual overloads yet
12097 
12098     return new (Context)
12099         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12100                             Context.DependentTy, VK_RValue, RLoc, false);
12101   }
12102 
12103   // Handle placeholders on both operands.
12104   if (checkPlaceholderForOverload(*this, Args[0]))
12105     return ExprError();
12106   if (checkPlaceholderForOverload(*this, Args[1]))
12107     return ExprError();
12108 
12109   // Build an empty overload set.
12110   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12111 
12112   // Subscript can only be overloaded as a member function.
12113 
12114   // Add operator candidates that are member functions.
12115   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12116 
12117   // Add builtin operator candidates.
12118   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12119 
12120   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12121 
12122   // Perform overload resolution.
12123   OverloadCandidateSet::iterator Best;
12124   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12125     case OR_Success: {
12126       // We found a built-in operator or an overloaded operator.
12127       FunctionDecl *FnDecl = Best->Function;
12128 
12129       if (FnDecl) {
12130         // We matched an overloaded operator. Build a call to that
12131         // operator.
12132 
12133         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12134 
12135         // Convert the arguments.
12136         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12137         ExprResult Arg0 =
12138           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12139                                               Best->FoundDecl, Method);
12140         if (Arg0.isInvalid())
12141           return ExprError();
12142         Args[0] = Arg0.get();
12143 
12144         // Convert the arguments.
12145         ExprResult InputInit
12146           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12147                                                       Context,
12148                                                       FnDecl->getParamDecl(0)),
12149                                       SourceLocation(),
12150                                       Args[1]);
12151         if (InputInit.isInvalid())
12152           return ExprError();
12153 
12154         Args[1] = InputInit.getAs<Expr>();
12155 
12156         // Build the actual expression node.
12157         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12158         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12159         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12160                                                   Best->FoundDecl,
12161                                                   HadMultipleCandidates,
12162                                                   OpLocInfo.getLoc(),
12163                                                   OpLocInfo.getInfo());
12164         if (FnExpr.isInvalid())
12165           return ExprError();
12166 
12167         // Determine the result type
12168         QualType ResultTy = FnDecl->getReturnType();
12169         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12170         ResultTy = ResultTy.getNonLValueExprType(Context);
12171 
12172         CXXOperatorCallExpr *TheCall =
12173           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12174                                             FnExpr.get(), Args,
12175                                             ResultTy, VK, RLoc,
12176                                             false);
12177 
12178         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12179           return ExprError();
12180 
12181         return MaybeBindToTemporary(TheCall);
12182       } else {
12183         // We matched a built-in operator. Convert the arguments, then
12184         // break out so that we will build the appropriate built-in
12185         // operator node.
12186         ExprResult ArgsRes0 =
12187           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12188                                     Best->Conversions[0], AA_Passing);
12189         if (ArgsRes0.isInvalid())
12190           return ExprError();
12191         Args[0] = ArgsRes0.get();
12192 
12193         ExprResult ArgsRes1 =
12194           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12195                                     Best->Conversions[1], AA_Passing);
12196         if (ArgsRes1.isInvalid())
12197           return ExprError();
12198         Args[1] = ArgsRes1.get();
12199 
12200         break;
12201       }
12202     }
12203 
12204     case OR_No_Viable_Function: {
12205       if (CandidateSet.empty())
12206         Diag(LLoc, diag::err_ovl_no_oper)
12207           << Args[0]->getType() << /*subscript*/ 0
12208           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12209       else
12210         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12211           << Args[0]->getType()
12212           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12213       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12214                                   "[]", LLoc);
12215       return ExprError();
12216     }
12217 
12218     case OR_Ambiguous:
12219       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12220           << "[]"
12221           << Args[0]->getType() << Args[1]->getType()
12222           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12223       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12224                                   "[]", LLoc);
12225       return ExprError();
12226 
12227     case OR_Deleted:
12228       Diag(LLoc, diag::err_ovl_deleted_oper)
12229         << Best->Function->isDeleted() << "[]"
12230         << getDeletedOrUnavailableSuffix(Best->Function)
12231         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12232       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12233                                   "[]", LLoc);
12234       return ExprError();
12235     }
12236 
12237   // We matched a built-in operator; build it.
12238   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12239 }
12240 
12241 /// BuildCallToMemberFunction - Build a call to a member
12242 /// function. MemExpr is the expression that refers to the member
12243 /// function (and includes the object parameter), Args/NumArgs are the
12244 /// arguments to the function call (not including the object
12245 /// parameter). The caller needs to validate that the member
12246 /// expression refers to a non-static member function or an overloaded
12247 /// member function.
12248 ExprResult
12249 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12250                                 SourceLocation LParenLoc,
12251                                 MultiExprArg Args,
12252                                 SourceLocation RParenLoc) {
12253   assert(MemExprE->getType() == Context.BoundMemberTy ||
12254          MemExprE->getType() == Context.OverloadTy);
12255 
12256   // Dig out the member expression. This holds both the object
12257   // argument and the member function we're referring to.
12258   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12259 
12260   // Determine whether this is a call to a pointer-to-member function.
12261   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12262     assert(op->getType() == Context.BoundMemberTy);
12263     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12264 
12265     QualType fnType =
12266       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12267 
12268     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12269     QualType resultType = proto->getCallResultType(Context);
12270     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12271 
12272     // Check that the object type isn't more qualified than the
12273     // member function we're calling.
12274     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12275 
12276     QualType objectType = op->getLHS()->getType();
12277     if (op->getOpcode() == BO_PtrMemI)
12278       objectType = objectType->castAs<PointerType>()->getPointeeType();
12279     Qualifiers objectQuals = objectType.getQualifiers();
12280 
12281     Qualifiers difference = objectQuals - funcQuals;
12282     difference.removeObjCGCAttr();
12283     difference.removeAddressSpace();
12284     if (difference) {
12285       std::string qualsString = difference.getAsString();
12286       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12287         << fnType.getUnqualifiedType()
12288         << qualsString
12289         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12290     }
12291 
12292     CXXMemberCallExpr *call
12293       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12294                                         resultType, valueKind, RParenLoc);
12295 
12296     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12297                             call, nullptr))
12298       return ExprError();
12299 
12300     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12301       return ExprError();
12302 
12303     if (CheckOtherCall(call, proto))
12304       return ExprError();
12305 
12306     return MaybeBindToTemporary(call);
12307   }
12308 
12309   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12310     return new (Context)
12311         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12312 
12313   UnbridgedCastsSet UnbridgedCasts;
12314   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12315     return ExprError();
12316 
12317   MemberExpr *MemExpr;
12318   CXXMethodDecl *Method = nullptr;
12319   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12320   NestedNameSpecifier *Qualifier = nullptr;
12321   if (isa<MemberExpr>(NakedMemExpr)) {
12322     MemExpr = cast<MemberExpr>(NakedMemExpr);
12323     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12324     FoundDecl = MemExpr->getFoundDecl();
12325     Qualifier = MemExpr->getQualifier();
12326     UnbridgedCasts.restore();
12327   } else {
12328     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12329     Qualifier = UnresExpr->getQualifier();
12330 
12331     QualType ObjectType = UnresExpr->getBaseType();
12332     Expr::Classification ObjectClassification
12333       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12334                             : UnresExpr->getBase()->Classify(Context);
12335 
12336     // Add overload candidates
12337     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12338                                       OverloadCandidateSet::CSK_Normal);
12339 
12340     // FIXME: avoid copy.
12341     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12342     if (UnresExpr->hasExplicitTemplateArgs()) {
12343       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12344       TemplateArgs = &TemplateArgsBuffer;
12345     }
12346 
12347     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12348            E = UnresExpr->decls_end(); I != E; ++I) {
12349 
12350       NamedDecl *Func = *I;
12351       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12352       if (isa<UsingShadowDecl>(Func))
12353         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12354 
12355 
12356       // Microsoft supports direct constructor calls.
12357       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12358         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12359                              Args, CandidateSet);
12360       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12361         // If explicit template arguments were provided, we can't call a
12362         // non-template member function.
12363         if (TemplateArgs)
12364           continue;
12365 
12366         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12367                            ObjectClassification, Args, CandidateSet,
12368                            /*SuppressUserConversions=*/false);
12369       } else {
12370         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12371                                    I.getPair(), ActingDC, TemplateArgs,
12372                                    ObjectType,  ObjectClassification,
12373                                    Args, CandidateSet,
12374                                    /*SuppressUsedConversions=*/false);
12375       }
12376     }
12377 
12378     DeclarationName DeclName = UnresExpr->getMemberName();
12379 
12380     UnbridgedCasts.restore();
12381 
12382     OverloadCandidateSet::iterator Best;
12383     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12384                                             Best)) {
12385     case OR_Success:
12386       Method = cast<CXXMethodDecl>(Best->Function);
12387       FoundDecl = Best->FoundDecl;
12388       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12389       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12390         return ExprError();
12391       // If FoundDecl is different from Method (such as if one is a template
12392       // and the other a specialization), make sure DiagnoseUseOfDecl is
12393       // called on both.
12394       // FIXME: This would be more comprehensively addressed by modifying
12395       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12396       // being used.
12397       if (Method != FoundDecl.getDecl() &&
12398                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12399         return ExprError();
12400       break;
12401 
12402     case OR_No_Viable_Function:
12403       Diag(UnresExpr->getMemberLoc(),
12404            diag::err_ovl_no_viable_member_function_in_call)
12405         << DeclName << MemExprE->getSourceRange();
12406       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12407       // FIXME: Leaking incoming expressions!
12408       return ExprError();
12409 
12410     case OR_Ambiguous:
12411       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12412         << DeclName << MemExprE->getSourceRange();
12413       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12414       // FIXME: Leaking incoming expressions!
12415       return ExprError();
12416 
12417     case OR_Deleted:
12418       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12419         << Best->Function->isDeleted()
12420         << DeclName
12421         << getDeletedOrUnavailableSuffix(Best->Function)
12422         << MemExprE->getSourceRange();
12423       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12424       // FIXME: Leaking incoming expressions!
12425       return ExprError();
12426     }
12427 
12428     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12429 
12430     // If overload resolution picked a static member, build a
12431     // non-member call based on that function.
12432     if (Method->isStatic()) {
12433       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12434                                    RParenLoc);
12435     }
12436 
12437     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12438   }
12439 
12440   QualType ResultType = Method->getReturnType();
12441   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12442   ResultType = ResultType.getNonLValueExprType(Context);
12443 
12444   assert(Method && "Member call to something that isn't a method?");
12445   CXXMemberCallExpr *TheCall =
12446     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12447                                     ResultType, VK, RParenLoc);
12448 
12449   // Check for a valid return type.
12450   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12451                           TheCall, Method))
12452     return ExprError();
12453 
12454   // Convert the object argument (for a non-static member function call).
12455   // We only need to do this if there was actually an overload; otherwise
12456   // it was done at lookup.
12457   if (!Method->isStatic()) {
12458     ExprResult ObjectArg =
12459       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12460                                           FoundDecl, Method);
12461     if (ObjectArg.isInvalid())
12462       return ExprError();
12463     MemExpr->setBase(ObjectArg.get());
12464   }
12465 
12466   // Convert the rest of the arguments
12467   const FunctionProtoType *Proto =
12468     Method->getType()->getAs<FunctionProtoType>();
12469   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12470                               RParenLoc))
12471     return ExprError();
12472 
12473   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12474 
12475   if (CheckFunctionCall(Method, TheCall, Proto))
12476     return ExprError();
12477 
12478   // In the case the method to call was not selected by the overloading
12479   // resolution process, we still need to handle the enable_if attribute. Do
12480   // that here, so it will not hide previous -- and more relevant -- errors
12481   if (isa<MemberExpr>(NakedMemExpr)) {
12482     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12483       Diag(MemExprE->getLocStart(),
12484            diag::err_ovl_no_viable_member_function_in_call)
12485           << Method << Method->getSourceRange();
12486       Diag(Method->getLocation(),
12487            diag::note_ovl_candidate_disabled_by_enable_if_attr)
12488           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12489       return ExprError();
12490     }
12491   }
12492 
12493   if ((isa<CXXConstructorDecl>(CurContext) ||
12494        isa<CXXDestructorDecl>(CurContext)) &&
12495       TheCall->getMethodDecl()->isPure()) {
12496     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12497 
12498     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12499         MemExpr->performsVirtualDispatch(getLangOpts())) {
12500       Diag(MemExpr->getLocStart(),
12501            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12502         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12503         << MD->getParent()->getDeclName();
12504 
12505       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12506       if (getLangOpts().AppleKext)
12507         Diag(MemExpr->getLocStart(),
12508              diag::note_pure_qualified_call_kext)
12509              << MD->getParent()->getDeclName()
12510              << MD->getDeclName();
12511     }
12512   }
12513 
12514   if (CXXDestructorDecl *DD =
12515           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12516     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12517     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12518     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12519                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12520                          MemExpr->getMemberLoc());
12521   }
12522 
12523   return MaybeBindToTemporary(TheCall);
12524 }
12525 
12526 /// BuildCallToObjectOfClassType - Build a call to an object of class
12527 /// type (C++ [over.call.object]), which can end up invoking an
12528 /// overloaded function call operator (@c operator()) or performing a
12529 /// user-defined conversion on the object argument.
12530 ExprResult
12531 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12532                                    SourceLocation LParenLoc,
12533                                    MultiExprArg Args,
12534                                    SourceLocation RParenLoc) {
12535   if (checkPlaceholderForOverload(*this, Obj))
12536     return ExprError();
12537   ExprResult Object = Obj;
12538 
12539   UnbridgedCastsSet UnbridgedCasts;
12540   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12541     return ExprError();
12542 
12543   assert(Object.get()->getType()->isRecordType() &&
12544          "Requires object type argument");
12545   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12546 
12547   // C++ [over.call.object]p1:
12548   //  If the primary-expression E in the function call syntax
12549   //  evaluates to a class object of type "cv T", then the set of
12550   //  candidate functions includes at least the function call
12551   //  operators of T. The function call operators of T are obtained by
12552   //  ordinary lookup of the name operator() in the context of
12553   //  (E).operator().
12554   OverloadCandidateSet CandidateSet(LParenLoc,
12555                                     OverloadCandidateSet::CSK_Operator);
12556   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12557 
12558   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12559                           diag::err_incomplete_object_call, Object.get()))
12560     return true;
12561 
12562   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12563   LookupQualifiedName(R, Record->getDecl());
12564   R.suppressDiagnostics();
12565 
12566   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12567        Oper != OperEnd; ++Oper) {
12568     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12569                        Object.get()->Classify(Context),
12570                        Args, CandidateSet,
12571                        /*SuppressUserConversions=*/ false);
12572   }
12573 
12574   // C++ [over.call.object]p2:
12575   //   In addition, for each (non-explicit in C++0x) conversion function
12576   //   declared in T of the form
12577   //
12578   //        operator conversion-type-id () cv-qualifier;
12579   //
12580   //   where cv-qualifier is the same cv-qualification as, or a
12581   //   greater cv-qualification than, cv, and where conversion-type-id
12582   //   denotes the type "pointer to function of (P1,...,Pn) returning
12583   //   R", or the type "reference to pointer to function of
12584   //   (P1,...,Pn) returning R", or the type "reference to function
12585   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12586   //   is also considered as a candidate function. Similarly,
12587   //   surrogate call functions are added to the set of candidate
12588   //   functions for each conversion function declared in an
12589   //   accessible base class provided the function is not hidden
12590   //   within T by another intervening declaration.
12591   const auto &Conversions =
12592       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12593   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12594     NamedDecl *D = *I;
12595     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12596     if (isa<UsingShadowDecl>(D))
12597       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12598 
12599     // Skip over templated conversion functions; they aren't
12600     // surrogates.
12601     if (isa<FunctionTemplateDecl>(D))
12602       continue;
12603 
12604     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12605     if (!Conv->isExplicit()) {
12606       // Strip the reference type (if any) and then the pointer type (if
12607       // any) to get down to what might be a function type.
12608       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12609       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12610         ConvType = ConvPtrType->getPointeeType();
12611 
12612       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12613       {
12614         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12615                               Object.get(), Args, CandidateSet);
12616       }
12617     }
12618   }
12619 
12620   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12621 
12622   // Perform overload resolution.
12623   OverloadCandidateSet::iterator Best;
12624   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12625                              Best)) {
12626   case OR_Success:
12627     // Overload resolution succeeded; we'll build the appropriate call
12628     // below.
12629     break;
12630 
12631   case OR_No_Viable_Function:
12632     if (CandidateSet.empty())
12633       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12634         << Object.get()->getType() << /*call*/ 1
12635         << Object.get()->getSourceRange();
12636     else
12637       Diag(Object.get()->getLocStart(),
12638            diag::err_ovl_no_viable_object_call)
12639         << Object.get()->getType() << Object.get()->getSourceRange();
12640     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12641     break;
12642 
12643   case OR_Ambiguous:
12644     Diag(Object.get()->getLocStart(),
12645          diag::err_ovl_ambiguous_object_call)
12646       << Object.get()->getType() << Object.get()->getSourceRange();
12647     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12648     break;
12649 
12650   case OR_Deleted:
12651     Diag(Object.get()->getLocStart(),
12652          diag::err_ovl_deleted_object_call)
12653       << Best->Function->isDeleted()
12654       << Object.get()->getType()
12655       << getDeletedOrUnavailableSuffix(Best->Function)
12656       << Object.get()->getSourceRange();
12657     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12658     break;
12659   }
12660 
12661   if (Best == CandidateSet.end())
12662     return true;
12663 
12664   UnbridgedCasts.restore();
12665 
12666   if (Best->Function == nullptr) {
12667     // Since there is no function declaration, this is one of the
12668     // surrogate candidates. Dig out the conversion function.
12669     CXXConversionDecl *Conv
12670       = cast<CXXConversionDecl>(
12671                          Best->Conversions[0].UserDefined.ConversionFunction);
12672 
12673     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12674                               Best->FoundDecl);
12675     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12676       return ExprError();
12677     assert(Conv == Best->FoundDecl.getDecl() &&
12678              "Found Decl & conversion-to-functionptr should be same, right?!");
12679     // We selected one of the surrogate functions that converts the
12680     // object parameter to a function pointer. Perform the conversion
12681     // on the object argument, then let ActOnCallExpr finish the job.
12682 
12683     // Create an implicit member expr to refer to the conversion operator.
12684     // and then call it.
12685     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12686                                              Conv, HadMultipleCandidates);
12687     if (Call.isInvalid())
12688       return ExprError();
12689     // Record usage of conversion in an implicit cast.
12690     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12691                                     CK_UserDefinedConversion, Call.get(),
12692                                     nullptr, VK_RValue);
12693 
12694     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12695   }
12696 
12697   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12698 
12699   // We found an overloaded operator(). Build a CXXOperatorCallExpr
12700   // that calls this method, using Object for the implicit object
12701   // parameter and passing along the remaining arguments.
12702   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12703 
12704   // An error diagnostic has already been printed when parsing the declaration.
12705   if (Method->isInvalidDecl())
12706     return ExprError();
12707 
12708   const FunctionProtoType *Proto =
12709     Method->getType()->getAs<FunctionProtoType>();
12710 
12711   unsigned NumParams = Proto->getNumParams();
12712 
12713   DeclarationNameInfo OpLocInfo(
12714                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12715   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12716   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12717                                            HadMultipleCandidates,
12718                                            OpLocInfo.getLoc(),
12719                                            OpLocInfo.getInfo());
12720   if (NewFn.isInvalid())
12721     return true;
12722 
12723   // Build the full argument list for the method call (the implicit object
12724   // parameter is placed at the beginning of the list).
12725   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12726   MethodArgs[0] = Object.get();
12727   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12728 
12729   // Once we've built TheCall, all of the expressions are properly
12730   // owned.
12731   QualType ResultTy = Method->getReturnType();
12732   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12733   ResultTy = ResultTy.getNonLValueExprType(Context);
12734 
12735   CXXOperatorCallExpr *TheCall = new (Context)
12736       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12737                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12738                           ResultTy, VK, RParenLoc, false);
12739   MethodArgs.reset();
12740 
12741   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12742     return true;
12743 
12744   // We may have default arguments. If so, we need to allocate more
12745   // slots in the call for them.
12746   if (Args.size() < NumParams)
12747     TheCall->setNumArgs(Context, NumParams + 1);
12748 
12749   bool IsError = false;
12750 
12751   // Initialize the implicit object parameter.
12752   ExprResult ObjRes =
12753     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12754                                         Best->FoundDecl, Method);
12755   if (ObjRes.isInvalid())
12756     IsError = true;
12757   else
12758     Object = ObjRes;
12759   TheCall->setArg(0, Object.get());
12760 
12761   // Check the argument types.
12762   for (unsigned i = 0; i != NumParams; i++) {
12763     Expr *Arg;
12764     if (i < Args.size()) {
12765       Arg = Args[i];
12766 
12767       // Pass the argument.
12768 
12769       ExprResult InputInit
12770         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12771                                                     Context,
12772                                                     Method->getParamDecl(i)),
12773                                     SourceLocation(), Arg);
12774 
12775       IsError |= InputInit.isInvalid();
12776       Arg = InputInit.getAs<Expr>();
12777     } else {
12778       ExprResult DefArg
12779         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12780       if (DefArg.isInvalid()) {
12781         IsError = true;
12782         break;
12783       }
12784 
12785       Arg = DefArg.getAs<Expr>();
12786     }
12787 
12788     TheCall->setArg(i + 1, Arg);
12789   }
12790 
12791   // If this is a variadic call, handle args passed through "...".
12792   if (Proto->isVariadic()) {
12793     // Promote the arguments (C99 6.5.2.2p7).
12794     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12795       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12796                                                         nullptr);
12797       IsError |= Arg.isInvalid();
12798       TheCall->setArg(i + 1, Arg.get());
12799     }
12800   }
12801 
12802   if (IsError) return true;
12803 
12804   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12805 
12806   if (CheckFunctionCall(Method, TheCall, Proto))
12807     return true;
12808 
12809   return MaybeBindToTemporary(TheCall);
12810 }
12811 
12812 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12813 ///  (if one exists), where @c Base is an expression of class type and
12814 /// @c Member is the name of the member we're trying to find.
12815 ExprResult
12816 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12817                                bool *NoArrowOperatorFound) {
12818   assert(Base->getType()->isRecordType() &&
12819          "left-hand side must have class type");
12820 
12821   if (checkPlaceholderForOverload(*this, Base))
12822     return ExprError();
12823 
12824   SourceLocation Loc = Base->getExprLoc();
12825 
12826   // C++ [over.ref]p1:
12827   //
12828   //   [...] An expression x->m is interpreted as (x.operator->())->m
12829   //   for a class object x of type T if T::operator->() exists and if
12830   //   the operator is selected as the best match function by the
12831   //   overload resolution mechanism (13.3).
12832   DeclarationName OpName =
12833     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12834   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12835   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12836 
12837   if (RequireCompleteType(Loc, Base->getType(),
12838                           diag::err_typecheck_incomplete_tag, Base))
12839     return ExprError();
12840 
12841   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12842   LookupQualifiedName(R, BaseRecord->getDecl());
12843   R.suppressDiagnostics();
12844 
12845   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12846        Oper != OperEnd; ++Oper) {
12847     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12848                        None, CandidateSet, /*SuppressUserConversions=*/false);
12849   }
12850 
12851   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12852 
12853   // Perform overload resolution.
12854   OverloadCandidateSet::iterator Best;
12855   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12856   case OR_Success:
12857     // Overload resolution succeeded; we'll build the call below.
12858     break;
12859 
12860   case OR_No_Viable_Function:
12861     if (CandidateSet.empty()) {
12862       QualType BaseType = Base->getType();
12863       if (NoArrowOperatorFound) {
12864         // Report this specific error to the caller instead of emitting a
12865         // diagnostic, as requested.
12866         *NoArrowOperatorFound = true;
12867         return ExprError();
12868       }
12869       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12870         << BaseType << Base->getSourceRange();
12871       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12872         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12873           << FixItHint::CreateReplacement(OpLoc, ".");
12874       }
12875     } else
12876       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12877         << "operator->" << Base->getSourceRange();
12878     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12879     return ExprError();
12880 
12881   case OR_Ambiguous:
12882     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12883       << "->" << Base->getType() << Base->getSourceRange();
12884     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12885     return ExprError();
12886 
12887   case OR_Deleted:
12888     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12889       << Best->Function->isDeleted()
12890       << "->"
12891       << getDeletedOrUnavailableSuffix(Best->Function)
12892       << Base->getSourceRange();
12893     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12894     return ExprError();
12895   }
12896 
12897   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12898 
12899   // Convert the object parameter.
12900   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12901   ExprResult BaseResult =
12902     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12903                                         Best->FoundDecl, Method);
12904   if (BaseResult.isInvalid())
12905     return ExprError();
12906   Base = BaseResult.get();
12907 
12908   // Build the operator call.
12909   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12910                                             HadMultipleCandidates, OpLoc);
12911   if (FnExpr.isInvalid())
12912     return ExprError();
12913 
12914   QualType ResultTy = Method->getReturnType();
12915   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12916   ResultTy = ResultTy.getNonLValueExprType(Context);
12917   CXXOperatorCallExpr *TheCall =
12918     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12919                                       Base, ResultTy, VK, OpLoc, false);
12920 
12921   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12922           return ExprError();
12923 
12924   return MaybeBindToTemporary(TheCall);
12925 }
12926 
12927 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12928 /// a literal operator described by the provided lookup results.
12929 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12930                                           DeclarationNameInfo &SuffixInfo,
12931                                           ArrayRef<Expr*> Args,
12932                                           SourceLocation LitEndLoc,
12933                                        TemplateArgumentListInfo *TemplateArgs) {
12934   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12935 
12936   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12937                                     OverloadCandidateSet::CSK_Normal);
12938   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12939                         /*SuppressUserConversions=*/true);
12940 
12941   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12942 
12943   // Perform overload resolution. This will usually be trivial, but might need
12944   // to perform substitutions for a literal operator template.
12945   OverloadCandidateSet::iterator Best;
12946   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12947   case OR_Success:
12948   case OR_Deleted:
12949     break;
12950 
12951   case OR_No_Viable_Function:
12952     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12953       << R.getLookupName();
12954     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12955     return ExprError();
12956 
12957   case OR_Ambiguous:
12958     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12959     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12960     return ExprError();
12961   }
12962 
12963   FunctionDecl *FD = Best->Function;
12964   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12965                                         HadMultipleCandidates,
12966                                         SuffixInfo.getLoc(),
12967                                         SuffixInfo.getInfo());
12968   if (Fn.isInvalid())
12969     return true;
12970 
12971   // Check the argument types. This should almost always be a no-op, except
12972   // that array-to-pointer decay is applied to string literals.
12973   Expr *ConvArgs[2];
12974   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12975     ExprResult InputInit = PerformCopyInitialization(
12976       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12977       SourceLocation(), Args[ArgIdx]);
12978     if (InputInit.isInvalid())
12979       return true;
12980     ConvArgs[ArgIdx] = InputInit.get();
12981   }
12982 
12983   QualType ResultTy = FD->getReturnType();
12984   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12985   ResultTy = ResultTy.getNonLValueExprType(Context);
12986 
12987   UserDefinedLiteral *UDL =
12988     new (Context) UserDefinedLiteral(Context, Fn.get(),
12989                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12990                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12991 
12992   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12993     return ExprError();
12994 
12995   if (CheckFunctionCall(FD, UDL, nullptr))
12996     return ExprError();
12997 
12998   return MaybeBindToTemporary(UDL);
12999 }
13000 
13001 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13002 /// given LookupResult is non-empty, it is assumed to describe a member which
13003 /// will be invoked. Otherwise, the function will be found via argument
13004 /// dependent lookup.
13005 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13006 /// otherwise CallExpr is set to ExprError() and some non-success value
13007 /// is returned.
13008 Sema::ForRangeStatus
13009 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13010                                 SourceLocation RangeLoc,
13011                                 const DeclarationNameInfo &NameInfo,
13012                                 LookupResult &MemberLookup,
13013                                 OverloadCandidateSet *CandidateSet,
13014                                 Expr *Range, ExprResult *CallExpr) {
13015   Scope *S = nullptr;
13016 
13017   CandidateSet->clear();
13018   if (!MemberLookup.empty()) {
13019     ExprResult MemberRef =
13020         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13021                                  /*IsPtr=*/false, CXXScopeSpec(),
13022                                  /*TemplateKWLoc=*/SourceLocation(),
13023                                  /*FirstQualifierInScope=*/nullptr,
13024                                  MemberLookup,
13025                                  /*TemplateArgs=*/nullptr, S);
13026     if (MemberRef.isInvalid()) {
13027       *CallExpr = ExprError();
13028       return FRS_DiagnosticIssued;
13029     }
13030     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13031     if (CallExpr->isInvalid()) {
13032       *CallExpr = ExprError();
13033       return FRS_DiagnosticIssued;
13034     }
13035   } else {
13036     UnresolvedSet<0> FoundNames;
13037     UnresolvedLookupExpr *Fn =
13038       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13039                                    NestedNameSpecifierLoc(), NameInfo,
13040                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13041                                    FoundNames.begin(), FoundNames.end());
13042 
13043     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13044                                                     CandidateSet, CallExpr);
13045     if (CandidateSet->empty() || CandidateSetError) {
13046       *CallExpr = ExprError();
13047       return FRS_NoViableFunction;
13048     }
13049     OverloadCandidateSet::iterator Best;
13050     OverloadingResult OverloadResult =
13051         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13052 
13053     if (OverloadResult == OR_No_Viable_Function) {
13054       *CallExpr = ExprError();
13055       return FRS_NoViableFunction;
13056     }
13057     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13058                                          Loc, nullptr, CandidateSet, &Best,
13059                                          OverloadResult,
13060                                          /*AllowTypoCorrection=*/false);
13061     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13062       *CallExpr = ExprError();
13063       return FRS_DiagnosticIssued;
13064     }
13065   }
13066   return FRS_Success;
13067 }
13068 
13069 
13070 /// FixOverloadedFunctionReference - E is an expression that refers to
13071 /// a C++ overloaded function (possibly with some parentheses and
13072 /// perhaps a '&' around it). We have resolved the overloaded function
13073 /// to the function declaration Fn, so patch up the expression E to
13074 /// refer (possibly indirectly) to Fn. Returns the new expr.
13075 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13076                                            FunctionDecl *Fn) {
13077   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13078     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13079                                                    Found, Fn);
13080     if (SubExpr == PE->getSubExpr())
13081       return PE;
13082 
13083     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13084   }
13085 
13086   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13087     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13088                                                    Found, Fn);
13089     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13090                                SubExpr->getType()) &&
13091            "Implicit cast type cannot be determined from overload");
13092     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13093     if (SubExpr == ICE->getSubExpr())
13094       return ICE;
13095 
13096     return ImplicitCastExpr::Create(Context, ICE->getType(),
13097                                     ICE->getCastKind(),
13098                                     SubExpr, nullptr,
13099                                     ICE->getValueKind());
13100   }
13101 
13102   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13103     if (!GSE->isResultDependent()) {
13104       Expr *SubExpr =
13105           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13106       if (SubExpr == GSE->getResultExpr())
13107         return GSE;
13108 
13109       // Replace the resulting type information before rebuilding the generic
13110       // selection expression.
13111       ArrayRef<Expr *> A = GSE->getAssocExprs();
13112       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13113       unsigned ResultIdx = GSE->getResultIndex();
13114       AssocExprs[ResultIdx] = SubExpr;
13115 
13116       return new (Context) GenericSelectionExpr(
13117           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13118           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13119           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13120           ResultIdx);
13121     }
13122     // Rather than fall through to the unreachable, return the original generic
13123     // selection expression.
13124     return GSE;
13125   }
13126 
13127   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13128     assert(UnOp->getOpcode() == UO_AddrOf &&
13129            "Can only take the address of an overloaded function");
13130     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13131       if (Method->isStatic()) {
13132         // Do nothing: static member functions aren't any different
13133         // from non-member functions.
13134       } else {
13135         // Fix the subexpression, which really has to be an
13136         // UnresolvedLookupExpr holding an overloaded member function
13137         // or template.
13138         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13139                                                        Found, Fn);
13140         if (SubExpr == UnOp->getSubExpr())
13141           return UnOp;
13142 
13143         assert(isa<DeclRefExpr>(SubExpr)
13144                && "fixed to something other than a decl ref");
13145         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13146                && "fixed to a member ref with no nested name qualifier");
13147 
13148         // We have taken the address of a pointer to member
13149         // function. Perform the computation here so that we get the
13150         // appropriate pointer to member type.
13151         QualType ClassType
13152           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13153         QualType MemPtrType
13154           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13155         // Under the MS ABI, lock down the inheritance model now.
13156         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13157           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13158 
13159         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13160                                            VK_RValue, OK_Ordinary,
13161                                            UnOp->getOperatorLoc());
13162       }
13163     }
13164     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13165                                                    Found, Fn);
13166     if (SubExpr == UnOp->getSubExpr())
13167       return UnOp;
13168 
13169     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13170                                      Context.getPointerType(SubExpr->getType()),
13171                                        VK_RValue, OK_Ordinary,
13172                                        UnOp->getOperatorLoc());
13173   }
13174 
13175   // C++ [except.spec]p17:
13176   //   An exception-specification is considered to be needed when:
13177   //   - in an expression the function is the unique lookup result or the
13178   //     selected member of a set of overloaded functions
13179   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13180     ResolveExceptionSpec(E->getExprLoc(), FPT);
13181 
13182   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13183     // FIXME: avoid copy.
13184     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13185     if (ULE->hasExplicitTemplateArgs()) {
13186       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13187       TemplateArgs = &TemplateArgsBuffer;
13188     }
13189 
13190     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13191                                            ULE->getQualifierLoc(),
13192                                            ULE->getTemplateKeywordLoc(),
13193                                            Fn,
13194                                            /*enclosing*/ false, // FIXME?
13195                                            ULE->getNameLoc(),
13196                                            Fn->getType(),
13197                                            VK_LValue,
13198                                            Found.getDecl(),
13199                                            TemplateArgs);
13200     MarkDeclRefReferenced(DRE);
13201     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13202     return DRE;
13203   }
13204 
13205   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13206     // FIXME: avoid copy.
13207     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13208     if (MemExpr->hasExplicitTemplateArgs()) {
13209       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13210       TemplateArgs = &TemplateArgsBuffer;
13211     }
13212 
13213     Expr *Base;
13214 
13215     // If we're filling in a static method where we used to have an
13216     // implicit member access, rewrite to a simple decl ref.
13217     if (MemExpr->isImplicitAccess()) {
13218       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13219         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13220                                                MemExpr->getQualifierLoc(),
13221                                                MemExpr->getTemplateKeywordLoc(),
13222                                                Fn,
13223                                                /*enclosing*/ false,
13224                                                MemExpr->getMemberLoc(),
13225                                                Fn->getType(),
13226                                                VK_LValue,
13227                                                Found.getDecl(),
13228                                                TemplateArgs);
13229         MarkDeclRefReferenced(DRE);
13230         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13231         return DRE;
13232       } else {
13233         SourceLocation Loc = MemExpr->getMemberLoc();
13234         if (MemExpr->getQualifier())
13235           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13236         CheckCXXThisCapture(Loc);
13237         Base = new (Context) CXXThisExpr(Loc,
13238                                          MemExpr->getBaseType(),
13239                                          /*isImplicit=*/true);
13240       }
13241     } else
13242       Base = MemExpr->getBase();
13243 
13244     ExprValueKind valueKind;
13245     QualType type;
13246     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13247       valueKind = VK_LValue;
13248       type = Fn->getType();
13249     } else {
13250       valueKind = VK_RValue;
13251       type = Context.BoundMemberTy;
13252     }
13253 
13254     MemberExpr *ME = MemberExpr::Create(
13255         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13256         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13257         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13258         OK_Ordinary);
13259     ME->setHadMultipleCandidates(true);
13260     MarkMemberReferenced(ME);
13261     return ME;
13262   }
13263 
13264   llvm_unreachable("Invalid reference to overloaded function");
13265 }
13266 
13267 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13268                                                 DeclAccessPair Found,
13269                                                 FunctionDecl *Fn) {
13270   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13271 }
13272