]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304460, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaOverload.cpp
1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include <algorithm>
37 #include <cstdlib>
38
39 using namespace clang;
40 using namespace sema;
41
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44     return P->hasAttr<PassObjectSizeAttr>();
45   });
46 }
47
48 /// A convenience routine for creating a decayed reference to a function.
49 static ExprResult
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51                       bool HadMultipleCandidates,
52                       SourceLocation Loc = SourceLocation(),
53                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55     return ExprError();
56   // If FoundDecl is different from Fn (such as if one is a template
57   // and the other a specialization), make sure DiagnoseUseOfDecl is
58   // called on both.
59   // FIXME: This would be more comprehensively addressed by modifying
60   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61   // being used.
62   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63     return ExprError();
64   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65     S.ResolveExceptionSpec(Loc, FPT);
66   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67                                                  VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70
71   S.MarkDeclRefReferenced(DRE);
72   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73                              CK_FunctionToPointerDecay);
74 }
75
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77                                  bool InOverloadResolution,
78                                  StandardConversionSequence &SCS,
79                                  bool CStyle,
80                                  bool AllowObjCWritebackConversion);
81
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83                                                  QualType &ToType,
84                                                  bool InOverloadResolution,
85                                                  StandardConversionSequence &SCS,
86                                                  bool CStyle);
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89                         UserDefinedConversionSequence& User,
90                         OverloadCandidateSet& Conversions,
91                         bool AllowExplicit,
92                         bool AllowObjCConversionOnExplicit);
93
94
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97                                    const StandardConversionSequence& SCS1,
98                                    const StandardConversionSequence& SCS2);
99
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113   static const ImplicitConversionRank
114     Rank[(int)ICK_Num_Conversion_Kinds] = {
115     ICR_Exact_Match,
116     ICR_Exact_Match,
117     ICR_Exact_Match,
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Promotion,
122     ICR_Promotion,
123     ICR_Promotion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_OCL_Scalar_Widening,
135     ICR_Complex_Real_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Writeback_Conversion,
139     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140                      // it was omitted by the patch that added
141                      // ICK_Zero_Event_Conversion
142     ICR_C_Conversion,
143     ICR_C_Conversion_Extension
144   };
145   return Rank[(int)Kind];
146 }
147
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152     "No conversion",
153     "Lvalue-to-rvalue",
154     "Array-to-pointer",
155     "Function-to-pointer",
156     "Function pointer conversion",
157     "Qualification",
158     "Integral promotion",
159     "Floating point promotion",
160     "Complex promotion",
161     "Integral conversion",
162     "Floating conversion",
163     "Complex conversion",
164     "Floating-integral conversion",
165     "Pointer conversion",
166     "Pointer-to-member conversion",
167     "Boolean conversion",
168     "Compatible-types conversion",
169     "Derived-to-base conversion",
170     "Vector conversion",
171     "Vector splat",
172     "Complex-real conversion",
173     "Block Pointer conversion",
174     "Transparent Union Conversion",
175     "Writeback conversion",
176     "OpenCL Zero Event Conversion",
177     "C specific type conversion",
178     "Incompatible pointer conversion"
179   };
180   return Name[Kind];
181 }
182
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186   First = ICK_Identity;
187   Second = ICK_Identity;
188   Third = ICK_Identity;
189   DeprecatedStringLiteralToCharPtr = false;
190   QualificationIncludesObjCLifetime = false;
191   ReferenceBinding = false;
192   DirectBinding = false;
193   IsLvalueReference = true;
194   BindsToFunctionLvalue = false;
195   BindsToRvalue = false;
196   BindsImplicitObjectArgumentWithoutRefQualifier = false;
197   ObjCLifetimeConversionBinding = false;
198   CopyConstructor = nullptr;
199 }
200
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205   ImplicitConversionRank Rank = ICR_Exact_Match;
206   if  (GetConversionRank(First) > Rank)
207     Rank = GetConversionRank(First);
208   if  (GetConversionRank(Second) > Rank)
209     Rank = GetConversionRank(Second);
210   if  (GetConversionRank(Third) > Rank)
211     Rank = GetConversionRank(Third);
212   return Rank;
213 }
214
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220   // Note that FromType has not necessarily been transformed by the
221   // array-to-pointer or function-to-pointer implicit conversions, so
222   // check for their presence as well as checking whether FromType is
223   // a pointer.
224   if (getToType(1)->isBooleanType() &&
225       (getFromType()->isPointerType() ||
226        getFromType()->isObjCObjectPointerType() ||
227        getFromType()->isBlockPointerType() ||
228        getFromType()->isNullPtrType() ||
229        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230     return true;
231
232   return false;
233 }
234
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
238 /// 13.3.3.2p4).
239 bool
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242   QualType FromType = getFromType();
243   QualType ToType = getToType(1);
244
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer implicit conversion, so check for its presence
247   // and redo the conversion to get a pointer.
248   if (First == ICK_Array_To_Pointer)
249     FromType = Context.getArrayDecayedType(FromType);
250
251   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253       return ToPtrType->getPointeeType()->isVoidType();
254
255   return false;
256 }
257
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262     switch (ICE->getCastKind()) {
263     case CK_NoOp:
264     case CK_IntegralCast:
265     case CK_IntegralToBoolean:
266     case CK_IntegralToFloating:
267     case CK_BooleanToSignedIntegral:
268     case CK_FloatingToIntegral:
269     case CK_FloatingToBoolean:
270     case CK_FloatingCast:
271       Converted = ICE->getSubExpr();
272       continue;
273
274     default:
275       return Converted;
276     }
277   }
278
279   return Converted;
280 }
281
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
284 ///
285 /// \param Ctx  The AST context.
286 /// \param Converted  The result of applying this standard conversion sequence.
287 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
288 ///        value of the expression prior to the narrowing conversion.
289 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
290 ///        type of the expression prior to the narrowing conversion.
291 NarrowingKind
292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293                                              const Expr *Converted,
294                                              APValue &ConstantValue,
295                                              QualType &ConstantType) const {
296   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297
298   // C++11 [dcl.init.list]p7:
299   //   A narrowing conversion is an implicit conversion ...
300   QualType FromType = getToType(0);
301   QualType ToType = getToType(1);
302
303   // A conversion to an enumeration type is narrowing if the conversion to
304   // the underlying type is narrowing. This only arises for expressions of
305   // the form 'Enum{init}'.
306   if (auto *ET = ToType->getAs<EnumType>())
307     ToType = ET->getDecl()->getIntegerType();
308
309   switch (Second) {
310   // 'bool' is an integral type; dispatch to the right place to handle it.
311   case ICK_Boolean_Conversion:
312     if (FromType->isRealFloatingType())
313       goto FloatingIntegralConversion;
314     if (FromType->isIntegralOrUnscopedEnumerationType())
315       goto IntegralConversion;
316     // Boolean conversions can be from pointers and pointers to members
317     // [conv.bool], and those aren't considered narrowing conversions.
318     return NK_Not_Narrowing;
319
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327   FloatingIntegralConversion:
328     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329       return NK_Type_Narrowing;
330     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331       llvm::APSInt IntConstantValue;
332       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333       assert(Initializer && "Unknown conversion expression");
334
335       // If it's value-dependent, we can't tell whether it's narrowing.
336       if (Initializer->isValueDependent())
337         return NK_Dependent_Narrowing;
338
339       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340         // Convert the integer to the floating type.
341         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343                                 llvm::APFloat::rmNearestTiesToEven);
344         // And back.
345         llvm::APSInt ConvertedValue = IntConstantValue;
346         bool ignored;
347         Result.convertToInteger(ConvertedValue,
348                                 llvm::APFloat::rmTowardZero, &ignored);
349         // If the resulting value is different, this was a narrowing conversion.
350         if (IntConstantValue != ConvertedValue) {
351           ConstantValue = APValue(IntConstantValue);
352           ConstantType = Initializer->getType();
353           return NK_Constant_Narrowing;
354         }
355       } else {
356         // Variables are always narrowings.
357         return NK_Variable_Narrowing;
358       }
359     }
360     return NK_Not_Narrowing;
361
362   // -- from long double to double or float, or from double to float, except
363   //    where the source is a constant expression and the actual value after
364   //    conversion is within the range of values that can be represented (even
365   //    if it cannot be represented exactly), or
366   case ICK_Floating_Conversion:
367     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369       // FromType is larger than ToType.
370       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
371
372       // If it's value-dependent, we can't tell whether it's narrowing.
373       if (Initializer->isValueDependent())
374         return NK_Dependent_Narrowing;
375
376       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377         // Constant!
378         assert(ConstantValue.isFloat());
379         llvm::APFloat FloatVal = ConstantValue.getFloat();
380         // Convert the source value into the target type.
381         bool ignored;
382         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383           Ctx.getFloatTypeSemantics(ToType),
384           llvm::APFloat::rmNearestTiesToEven, &ignored);
385         // If there was no overflow, the source value is within the range of
386         // values that can be represented.
387         if (ConvertStatus & llvm::APFloat::opOverflow) {
388           ConstantType = Initializer->getType();
389           return NK_Constant_Narrowing;
390         }
391       } else {
392         return NK_Variable_Narrowing;
393       }
394     }
395     return NK_Not_Narrowing;
396
397   // -- from an integer type or unscoped enumeration type to an integer type
398   //    that cannot represent all the values of the original type, except where
399   //    the source is a constant expression and the actual value after
400   //    conversion will fit into the target type and will produce the original
401   //    value when converted back to the original type.
402   case ICK_Integral_Conversion:
403   IntegralConversion: {
404     assert(FromType->isIntegralOrUnscopedEnumerationType());
405     assert(ToType->isIntegralOrUnscopedEnumerationType());
406     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407     const unsigned FromWidth = Ctx.getIntWidth(FromType);
408     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409     const unsigned ToWidth = Ctx.getIntWidth(ToType);
410
411     if (FromWidth > ToWidth ||
412         (FromWidth == ToWidth && FromSigned != ToSigned) ||
413         (FromSigned && !ToSigned)) {
414       // Not all values of FromType can be represented in ToType.
415       llvm::APSInt InitializerValue;
416       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
417
418       // If it's value-dependent, we can't tell whether it's narrowing.
419       if (Initializer->isValueDependent())
420         return NK_Dependent_Narrowing;
421
422       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423         // Such conversions on variables are always narrowing.
424         return NK_Variable_Narrowing;
425       }
426       bool Narrowing = false;
427       if (FromWidth < ToWidth) {
428         // Negative -> unsigned is narrowing. Otherwise, more bits is never
429         // narrowing.
430         if (InitializerValue.isSigned() && InitializerValue.isNegative())
431           Narrowing = true;
432       } else {
433         // Add a bit to the InitializerValue so we don't have to worry about
434         // signed vs. unsigned comparisons.
435         InitializerValue = InitializerValue.extend(
436           InitializerValue.getBitWidth() + 1);
437         // Convert the initializer to and from the target width and signed-ness.
438         llvm::APSInt ConvertedValue = InitializerValue;
439         ConvertedValue = ConvertedValue.trunc(ToWidth);
440         ConvertedValue.setIsSigned(ToSigned);
441         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442         ConvertedValue.setIsSigned(InitializerValue.isSigned());
443         // If the result is different, this was a narrowing conversion.
444         if (ConvertedValue != InitializerValue)
445           Narrowing = true;
446       }
447       if (Narrowing) {
448         ConstantType = Initializer->getType();
449         ConstantValue = APValue(InitializerValue);
450         return NK_Constant_Narrowing;
451       }
452     }
453     return NK_Not_Narrowing;
454   }
455
456   default:
457     // Other kinds of conversions are not narrowings.
458     return NK_Not_Narrowing;
459   }
460 }
461
462 /// dump - Print this standard conversion sequence to standard
463 /// error. Useful for debugging overloading issues.
464 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
465   raw_ostream &OS = llvm::errs();
466   bool PrintedSomething = false;
467   if (First != ICK_Identity) {
468     OS << GetImplicitConversionName(First);
469     PrintedSomething = true;
470   }
471
472   if (Second != ICK_Identity) {
473     if (PrintedSomething) {
474       OS << " -> ";
475     }
476     OS << GetImplicitConversionName(Second);
477
478     if (CopyConstructor) {
479       OS << " (by copy constructor)";
480     } else if (DirectBinding) {
481       OS << " (direct reference binding)";
482     } else if (ReferenceBinding) {
483       OS << " (reference binding)";
484     }
485     PrintedSomething = true;
486   }
487
488   if (Third != ICK_Identity) {
489     if (PrintedSomething) {
490       OS << " -> ";
491     }
492     OS << GetImplicitConversionName(Third);
493     PrintedSomething = true;
494   }
495
496   if (!PrintedSomething) {
497     OS << "No conversions required";
498   }
499 }
500
501 /// dump - Print this user-defined conversion sequence to standard
502 /// error. Useful for debugging overloading issues.
503 void UserDefinedConversionSequence::dump() const {
504   raw_ostream &OS = llvm::errs();
505   if (Before.First || Before.Second || Before.Third) {
506     Before.dump();
507     OS << " -> ";
508   }
509   if (ConversionFunction)
510     OS << '\'' << *ConversionFunction << '\'';
511   else
512     OS << "aggregate initialization";
513   if (After.First || After.Second || After.Third) {
514     OS << " -> ";
515     After.dump();
516   }
517 }
518
519 /// dump - Print this implicit conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void ImplicitConversionSequence::dump() const {
522   raw_ostream &OS = llvm::errs();
523   if (isStdInitializerListElement())
524     OS << "Worst std::initializer_list element conversion: ";
525   switch (ConversionKind) {
526   case StandardConversion:
527     OS << "Standard conversion: ";
528     Standard.dump();
529     break;
530   case UserDefinedConversion:
531     OS << "User-defined conversion: ";
532     UserDefined.dump();
533     break;
534   case EllipsisConversion:
535     OS << "Ellipsis conversion";
536     break;
537   case AmbiguousConversion:
538     OS << "Ambiguous conversion";
539     break;
540   case BadConversion:
541     OS << "Bad conversion";
542     break;
543   }
544
545   OS << "\n";
546 }
547
548 void AmbiguousConversionSequence::construct() {
549   new (&conversions()) ConversionSet();
550 }
551
552 void AmbiguousConversionSequence::destruct() {
553   conversions().~ConversionSet();
554 }
555
556 void
557 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558   FromTypePtr = O.FromTypePtr;
559   ToTypePtr = O.ToTypePtr;
560   new (&conversions()) ConversionSet(O.conversions());
561 }
562
563 namespace {
564   // Structure used by DeductionFailureInfo to store
565   // template argument information.
566   struct DFIArguments {
567     TemplateArgument FirstArg;
568     TemplateArgument SecondArg;
569   };
570   // Structure used by DeductionFailureInfo to store
571   // template parameter and template argument information.
572   struct DFIParamWithArguments : DFIArguments {
573     TemplateParameter Param;
574   };
575   // Structure used by DeductionFailureInfo to store template argument
576   // information and the index of the problematic call argument.
577   struct DFIDeducedMismatchArgs : DFIArguments {
578     TemplateArgumentList *TemplateArgs;
579     unsigned CallArgIndex;
580   };
581 }
582
583 /// \brief Convert from Sema's representation of template deduction information
584 /// to the form used in overload-candidate information.
585 DeductionFailureInfo
586 clang::MakeDeductionFailureInfo(ASTContext &Context,
587                                 Sema::TemplateDeductionResult TDK,
588                                 TemplateDeductionInfo &Info) {
589   DeductionFailureInfo Result;
590   Result.Result = static_cast<unsigned>(TDK);
591   Result.HasDiagnostic = false;
592   switch (TDK) {
593   case Sema::TDK_Invalid:
594   case Sema::TDK_InstantiationDepth:
595   case Sema::TDK_TooManyArguments:
596   case Sema::TDK_TooFewArguments:
597   case Sema::TDK_MiscellaneousDeductionFailure:
598   case Sema::TDK_CUDATargetMismatch:
599     Result.Data = nullptr;
600     break;
601
602   case Sema::TDK_Incomplete:
603   case Sema::TDK_InvalidExplicitArguments:
604     Result.Data = Info.Param.getOpaqueValue();
605     break;
606
607   case Sema::TDK_DeducedMismatch:
608   case Sema::TDK_DeducedMismatchNested: {
609     // FIXME: Should allocate from normal heap so that we can free this later.
610     auto *Saved = new (Context) DFIDeducedMismatchArgs;
611     Saved->FirstArg = Info.FirstArg;
612     Saved->SecondArg = Info.SecondArg;
613     Saved->TemplateArgs = Info.take();
614     Saved->CallArgIndex = Info.CallArgIndex;
615     Result.Data = Saved;
616     break;
617   }
618
619   case Sema::TDK_NonDeducedMismatch: {
620     // FIXME: Should allocate from normal heap so that we can free this later.
621     DFIArguments *Saved = new (Context) DFIArguments;
622     Saved->FirstArg = Info.FirstArg;
623     Saved->SecondArg = Info.SecondArg;
624     Result.Data = Saved;
625     break;
626   }
627
628   case Sema::TDK_Inconsistent:
629   case Sema::TDK_Underqualified: {
630     // FIXME: Should allocate from normal heap so that we can free this later.
631     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
632     Saved->Param = Info.Param;
633     Saved->FirstArg = Info.FirstArg;
634     Saved->SecondArg = Info.SecondArg;
635     Result.Data = Saved;
636     break;
637   }
638
639   case Sema::TDK_SubstitutionFailure:
640     Result.Data = Info.take();
641     if (Info.hasSFINAEDiagnostic()) {
642       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643           SourceLocation(), PartialDiagnostic::NullDiagnostic());
644       Info.takeSFINAEDiagnostic(*Diag);
645       Result.HasDiagnostic = true;
646     }
647     break;
648
649   case Sema::TDK_Success:
650   case Sema::TDK_NonDependentConversionFailure:
651     llvm_unreachable("not a deduction failure");
652   }
653
654   return Result;
655 }
656
657 void DeductionFailureInfo::Destroy() {
658   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659   case Sema::TDK_Success:
660   case Sema::TDK_Invalid:
661   case Sema::TDK_InstantiationDepth:
662   case Sema::TDK_Incomplete:
663   case Sema::TDK_TooManyArguments:
664   case Sema::TDK_TooFewArguments:
665   case Sema::TDK_InvalidExplicitArguments:
666   case Sema::TDK_CUDATargetMismatch:
667   case Sema::TDK_NonDependentConversionFailure:
668     break;
669
670   case Sema::TDK_Inconsistent:
671   case Sema::TDK_Underqualified:
672   case Sema::TDK_DeducedMismatch:
673   case Sema::TDK_DeducedMismatchNested:
674   case Sema::TDK_NonDeducedMismatch:
675     // FIXME: Destroy the data?
676     Data = nullptr;
677     break;
678
679   case Sema::TDK_SubstitutionFailure:
680     // FIXME: Destroy the template argument list?
681     Data = nullptr;
682     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683       Diag->~PartialDiagnosticAt();
684       HasDiagnostic = false;
685     }
686     break;
687
688   // Unhandled
689   case Sema::TDK_MiscellaneousDeductionFailure:
690     break;
691   }
692 }
693
694 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
695   if (HasDiagnostic)
696     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
697   return nullptr;
698 }
699
700 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
701   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702   case Sema::TDK_Success:
703   case Sema::TDK_Invalid:
704   case Sema::TDK_InstantiationDepth:
705   case Sema::TDK_TooManyArguments:
706   case Sema::TDK_TooFewArguments:
707   case Sema::TDK_SubstitutionFailure:
708   case Sema::TDK_DeducedMismatch:
709   case Sema::TDK_DeducedMismatchNested:
710   case Sema::TDK_NonDeducedMismatch:
711   case Sema::TDK_CUDATargetMismatch:
712   case Sema::TDK_NonDependentConversionFailure:
713     return TemplateParameter();
714
715   case Sema::TDK_Incomplete:
716   case Sema::TDK_InvalidExplicitArguments:
717     return TemplateParameter::getFromOpaqueValue(Data);
718
719   case Sema::TDK_Inconsistent:
720   case Sema::TDK_Underqualified:
721     return static_cast<DFIParamWithArguments*>(Data)->Param;
722
723   // Unhandled
724   case Sema::TDK_MiscellaneousDeductionFailure:
725     break;
726   }
727
728   return TemplateParameter();
729 }
730
731 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
732   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733   case Sema::TDK_Success:
734   case Sema::TDK_Invalid:
735   case Sema::TDK_InstantiationDepth:
736   case Sema::TDK_TooManyArguments:
737   case Sema::TDK_TooFewArguments:
738   case Sema::TDK_Incomplete:
739   case Sema::TDK_InvalidExplicitArguments:
740   case Sema::TDK_Inconsistent:
741   case Sema::TDK_Underqualified:
742   case Sema::TDK_NonDeducedMismatch:
743   case Sema::TDK_CUDATargetMismatch:
744   case Sema::TDK_NonDependentConversionFailure:
745     return nullptr;
746
747   case Sema::TDK_DeducedMismatch:
748   case Sema::TDK_DeducedMismatchNested:
749     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750
751   case Sema::TDK_SubstitutionFailure:
752     return static_cast<TemplateArgumentList*>(Data);
753
754   // Unhandled
755   case Sema::TDK_MiscellaneousDeductionFailure:
756     break;
757   }
758
759   return nullptr;
760 }
761
762 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
763   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764   case Sema::TDK_Success:
765   case Sema::TDK_Invalid:
766   case Sema::TDK_InstantiationDepth:
767   case Sema::TDK_Incomplete:
768   case Sema::TDK_TooManyArguments:
769   case Sema::TDK_TooFewArguments:
770   case Sema::TDK_InvalidExplicitArguments:
771   case Sema::TDK_SubstitutionFailure:
772   case Sema::TDK_CUDATargetMismatch:
773   case Sema::TDK_NonDependentConversionFailure:
774     return nullptr;
775
776   case Sema::TDK_Inconsistent:
777   case Sema::TDK_Underqualified:
778   case Sema::TDK_DeducedMismatch:
779   case Sema::TDK_DeducedMismatchNested:
780   case Sema::TDK_NonDeducedMismatch:
781     return &static_cast<DFIArguments*>(Data)->FirstArg;
782
783   // Unhandled
784   case Sema::TDK_MiscellaneousDeductionFailure:
785     break;
786   }
787
788   return nullptr;
789 }
790
791 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
792   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793   case Sema::TDK_Success:
794   case Sema::TDK_Invalid:
795   case Sema::TDK_InstantiationDepth:
796   case Sema::TDK_Incomplete:
797   case Sema::TDK_TooManyArguments:
798   case Sema::TDK_TooFewArguments:
799   case Sema::TDK_InvalidExplicitArguments:
800   case Sema::TDK_SubstitutionFailure:
801   case Sema::TDK_CUDATargetMismatch:
802   case Sema::TDK_NonDependentConversionFailure:
803     return nullptr;
804
805   case Sema::TDK_Inconsistent:
806   case Sema::TDK_Underqualified:
807   case Sema::TDK_DeducedMismatch:
808   case Sema::TDK_DeducedMismatchNested:
809   case Sema::TDK_NonDeducedMismatch:
810     return &static_cast<DFIArguments*>(Data)->SecondArg;
811
812   // Unhandled
813   case Sema::TDK_MiscellaneousDeductionFailure:
814     break;
815   }
816
817   return nullptr;
818 }
819
820 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
821   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822   case Sema::TDK_DeducedMismatch:
823   case Sema::TDK_DeducedMismatchNested:
824     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825
826   default:
827     return llvm::None;
828   }
829 }
830
831 void OverloadCandidateSet::destroyCandidates() {
832   for (iterator i = begin(), e = end(); i != e; ++i) {
833     for (auto &C : i->Conversions)
834       C.~ImplicitConversionSequence();
835     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836       i->DeductionFailure.Destroy();
837   }
838 }
839
840 void OverloadCandidateSet::clear() {
841   destroyCandidates();
842   SlabAllocator.Reset();
843   NumInlineBytesUsed = 0;
844   Candidates.clear();
845   Functions.clear();
846 }
847
848 namespace {
849   class UnbridgedCastsSet {
850     struct Entry {
851       Expr **Addr;
852       Expr *Saved;
853     };
854     SmallVector<Entry, 2> Entries;
855
856   public:
857     void save(Sema &S, Expr *&E) {
858       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
859       Entry entry = { &E, E };
860       Entries.push_back(entry);
861       E = S.stripARCUnbridgedCast(E);
862     }
863
864     void restore() {
865       for (SmallVectorImpl<Entry>::iterator
866              i = Entries.begin(), e = Entries.end(); i != e; ++i)
867         *i->Addr = i->Saved;
868     }
869   };
870 }
871
872 /// checkPlaceholderForOverload - Do any interesting placeholder-like
873 /// preprocessing on the given expression.
874 ///
875 /// \param unbridgedCasts a collection to which to add unbridged casts;
876 ///   without this, they will be immediately diagnosed as errors
877 ///
878 /// Return true on unrecoverable error.
879 static bool
880 checkPlaceholderForOverload(Sema &S, Expr *&E,
881                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
882   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
883     // We can't handle overloaded expressions here because overload
884     // resolution might reasonably tweak them.
885     if (placeholder->getKind() == BuiltinType::Overload) return false;
886
887     // If the context potentially accepts unbridged ARC casts, strip
888     // the unbridged cast and add it to the collection for later restoration.
889     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
890         unbridgedCasts) {
891       unbridgedCasts->save(S, E);
892       return false;
893     }
894
895     // Go ahead and check everything else.
896     ExprResult result = S.CheckPlaceholderExpr(E);
897     if (result.isInvalid())
898       return true;
899
900     E = result.get();
901     return false;
902   }
903
904   // Nothing to do.
905   return false;
906 }
907
908 /// checkArgPlaceholdersForOverload - Check a set of call operands for
909 /// placeholders.
910 static bool checkArgPlaceholdersForOverload(Sema &S,
911                                             MultiExprArg Args,
912                                             UnbridgedCastsSet &unbridged) {
913   for (unsigned i = 0, e = Args.size(); i != e; ++i)
914     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
915       return true;
916
917   return false;
918 }
919
920 /// Determine whether the given New declaration is an overload of the
921 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
922 /// New and Old cannot be overloaded, e.g., if New has the same signature as
923 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
924 /// functions (or function templates) at all. When it does return Ovl_Match or
925 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
926 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
927 /// declaration.
928 ///
929 /// Example: Given the following input:
930 ///
931 ///   void f(int, float); // #1
932 ///   void f(int, int); // #2
933 ///   int f(int, int); // #3
934 ///
935 /// When we process #1, there is no previous declaration of "f", so IsOverload
936 /// will not be used.
937 ///
938 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
939 /// the parameter types, we see that #1 and #2 are overloaded (since they have
940 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
941 /// unchanged.
942 ///
943 /// When we process #3, Old is an overload set containing #1 and #2. We compare
944 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
945 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
946 /// functions are not part of the signature), IsOverload returns Ovl_Match and
947 /// MatchedDecl will be set to point to the FunctionDecl for #2.
948 ///
949 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
950 /// by a using declaration. The rules for whether to hide shadow declarations
951 /// ignore some properties which otherwise figure into a function template's
952 /// signature.
953 Sema::OverloadKind
954 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
955                     NamedDecl *&Match, bool NewIsUsingDecl) {
956   for (LookupResult::iterator I = Old.begin(), E = Old.end();
957          I != E; ++I) {
958     NamedDecl *OldD = *I;
959
960     bool OldIsUsingDecl = false;
961     if (isa<UsingShadowDecl>(OldD)) {
962       OldIsUsingDecl = true;
963
964       // We can always introduce two using declarations into the same
965       // context, even if they have identical signatures.
966       if (NewIsUsingDecl) continue;
967
968       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
969     }
970
971     // A using-declaration does not conflict with another declaration
972     // if one of them is hidden.
973     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
974       continue;
975
976     // If either declaration was introduced by a using declaration,
977     // we'll need to use slightly different rules for matching.
978     // Essentially, these rules are the normal rules, except that
979     // function templates hide function templates with different
980     // return types or template parameter lists.
981     bool UseMemberUsingDeclRules =
982       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
983       !New->getFriendObjectKind();
984
985     if (FunctionDecl *OldF = OldD->getAsFunction()) {
986       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
987         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
988           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
989           continue;
990         }
991
992         if (!isa<FunctionTemplateDecl>(OldD) &&
993             !shouldLinkPossiblyHiddenDecl(*I, New))
994           continue;
995
996         Match = *I;
997         return Ovl_Match;
998       }
999     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1000       // We can overload with these, which can show up when doing
1001       // redeclaration checks for UsingDecls.
1002       assert(Old.getLookupKind() == LookupUsingDeclName);
1003     } else if (isa<TagDecl>(OldD)) {
1004       // We can always overload with tags by hiding them.
1005     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1006       // Optimistically assume that an unresolved using decl will
1007       // overload; if it doesn't, we'll have to diagnose during
1008       // template instantiation.
1009       //
1010       // Exception: if the scope is dependent and this is not a class
1011       // member, the using declaration can only introduce an enumerator.
1012       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1013         Match = *I;
1014         return Ovl_NonFunction;
1015       }
1016     } else {
1017       // (C++ 13p1):
1018       //   Only function declarations can be overloaded; object and type
1019       //   declarations cannot be overloaded.
1020       Match = *I;
1021       return Ovl_NonFunction;
1022     }
1023   }
1024
1025   return Ovl_Overload;
1026 }
1027
1028 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1029                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1030   // C++ [basic.start.main]p2: This function shall not be overloaded.
1031   if (New->isMain())
1032     return false;
1033
1034   // MSVCRT user defined entry points cannot be overloaded.
1035   if (New->isMSVCRTEntryPoint())
1036     return false;
1037
1038   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1039   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1040
1041   // C++ [temp.fct]p2:
1042   //   A function template can be overloaded with other function templates
1043   //   and with normal (non-template) functions.
1044   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1045     return true;
1046
1047   // Is the function New an overload of the function Old?
1048   QualType OldQType = Context.getCanonicalType(Old->getType());
1049   QualType NewQType = Context.getCanonicalType(New->getType());
1050
1051   // Compare the signatures (C++ 1.3.10) of the two functions to
1052   // determine whether they are overloads. If we find any mismatch
1053   // in the signature, they are overloads.
1054
1055   // If either of these functions is a K&R-style function (no
1056   // prototype), then we consider them to have matching signatures.
1057   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1058       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1059     return false;
1060
1061   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1062   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1063
1064   // The signature of a function includes the types of its
1065   // parameters (C++ 1.3.10), which includes the presence or absence
1066   // of the ellipsis; see C++ DR 357).
1067   if (OldQType != NewQType &&
1068       (OldType->getNumParams() != NewType->getNumParams() ||
1069        OldType->isVariadic() != NewType->isVariadic() ||
1070        !FunctionParamTypesAreEqual(OldType, NewType)))
1071     return true;
1072
1073   // C++ [temp.over.link]p4:
1074   //   The signature of a function template consists of its function
1075   //   signature, its return type and its template parameter list. The names
1076   //   of the template parameters are significant only for establishing the
1077   //   relationship between the template parameters and the rest of the
1078   //   signature.
1079   //
1080   // We check the return type and template parameter lists for function
1081   // templates first; the remaining checks follow.
1082   //
1083   // However, we don't consider either of these when deciding whether
1084   // a member introduced by a shadow declaration is hidden.
1085   if (!UseMemberUsingDeclRules && NewTemplate &&
1086       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1087                                        OldTemplate->getTemplateParameters(),
1088                                        false, TPL_TemplateMatch) ||
1089        OldType->getReturnType() != NewType->getReturnType()))
1090     return true;
1091
1092   // If the function is a class member, its signature includes the
1093   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1094   //
1095   // As part of this, also check whether one of the member functions
1096   // is static, in which case they are not overloads (C++
1097   // 13.1p2). While not part of the definition of the signature,
1098   // this check is important to determine whether these functions
1099   // can be overloaded.
1100   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1101   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1102   if (OldMethod && NewMethod &&
1103       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1104     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1105       if (!UseMemberUsingDeclRules &&
1106           (OldMethod->getRefQualifier() == RQ_None ||
1107            NewMethod->getRefQualifier() == RQ_None)) {
1108         // C++0x [over.load]p2:
1109         //   - Member function declarations with the same name and the same
1110         //     parameter-type-list as well as member function template
1111         //     declarations with the same name, the same parameter-type-list, and
1112         //     the same template parameter lists cannot be overloaded if any of
1113         //     them, but not all, have a ref-qualifier (8.3.5).
1114         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1115           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1116         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1117       }
1118       return true;
1119     }
1120
1121     // We may not have applied the implicit const for a constexpr member
1122     // function yet (because we haven't yet resolved whether this is a static
1123     // or non-static member function). Add it now, on the assumption that this
1124     // is a redeclaration of OldMethod.
1125     unsigned OldQuals = OldMethod->getTypeQualifiers();
1126     unsigned NewQuals = NewMethod->getTypeQualifiers();
1127     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1128         !isa<CXXConstructorDecl>(NewMethod))
1129       NewQuals |= Qualifiers::Const;
1130
1131     // We do not allow overloading based off of '__restrict'.
1132     OldQuals &= ~Qualifiers::Restrict;
1133     NewQuals &= ~Qualifiers::Restrict;
1134     if (OldQuals != NewQuals)
1135       return true;
1136   }
1137
1138   // Though pass_object_size is placed on parameters and takes an argument, we
1139   // consider it to be a function-level modifier for the sake of function
1140   // identity. Either the function has one or more parameters with
1141   // pass_object_size or it doesn't.
1142   if (functionHasPassObjectSizeParams(New) !=
1143       functionHasPassObjectSizeParams(Old))
1144     return true;
1145
1146   // enable_if attributes are an order-sensitive part of the signature.
1147   for (specific_attr_iterator<EnableIfAttr>
1148          NewI = New->specific_attr_begin<EnableIfAttr>(),
1149          NewE = New->specific_attr_end<EnableIfAttr>(),
1150          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1151          OldE = Old->specific_attr_end<EnableIfAttr>();
1152        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1153     if (NewI == NewE || OldI == OldE)
1154       return true;
1155     llvm::FoldingSetNodeID NewID, OldID;
1156     NewI->getCond()->Profile(NewID, Context, true);
1157     OldI->getCond()->Profile(OldID, Context, true);
1158     if (NewID != OldID)
1159       return true;
1160   }
1161
1162   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1163     // Don't allow overloading of destructors.  (In theory we could, but it
1164     // would be a giant change to clang.)
1165     if (isa<CXXDestructorDecl>(New))
1166       return false;
1167
1168     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1169                        OldTarget = IdentifyCUDATarget(Old);
1170     if (NewTarget == CFT_InvalidTarget)
1171       return false;
1172
1173     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1174
1175     // Allow overloading of functions with same signature and different CUDA
1176     // target attributes.
1177     return NewTarget != OldTarget;
1178   }
1179
1180   // The signatures match; this is not an overload.
1181   return false;
1182 }
1183
1184 /// \brief Checks availability of the function depending on the current
1185 /// function context. Inside an unavailable function, unavailability is ignored.
1186 ///
1187 /// \returns true if \arg FD is unavailable and current context is inside
1188 /// an available function, false otherwise.
1189 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1190   if (!FD->isUnavailable())
1191     return false;
1192
1193   // Walk up the context of the caller.
1194   Decl *C = cast<Decl>(CurContext);
1195   do {
1196     if (C->isUnavailable())
1197       return false;
1198   } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1199   return true;
1200 }
1201
1202 /// \brief Tries a user-defined conversion from From to ToType.
1203 ///
1204 /// Produces an implicit conversion sequence for when a standard conversion
1205 /// is not an option. See TryImplicitConversion for more information.
1206 static ImplicitConversionSequence
1207 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1208                          bool SuppressUserConversions,
1209                          bool AllowExplicit,
1210                          bool InOverloadResolution,
1211                          bool CStyle,
1212                          bool AllowObjCWritebackConversion,
1213                          bool AllowObjCConversionOnExplicit) {
1214   ImplicitConversionSequence ICS;
1215
1216   if (SuppressUserConversions) {
1217     // We're not in the case above, so there is no conversion that
1218     // we can perform.
1219     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1220     return ICS;
1221   }
1222
1223   // Attempt user-defined conversion.
1224   OverloadCandidateSet Conversions(From->getExprLoc(),
1225                                    OverloadCandidateSet::CSK_Normal);
1226   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1227                                   Conversions, AllowExplicit,
1228                                   AllowObjCConversionOnExplicit)) {
1229   case OR_Success:
1230   case OR_Deleted:
1231     ICS.setUserDefined();
1232     // C++ [over.ics.user]p4:
1233     //   A conversion of an expression of class type to the same class
1234     //   type is given Exact Match rank, and a conversion of an
1235     //   expression of class type to a base class of that type is
1236     //   given Conversion rank, in spite of the fact that a copy
1237     //   constructor (i.e., a user-defined conversion function) is
1238     //   called for those cases.
1239     if (CXXConstructorDecl *Constructor
1240           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1241       QualType FromCanon
1242         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1243       QualType ToCanon
1244         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1245       if (Constructor->isCopyConstructor() &&
1246           (FromCanon == ToCanon ||
1247            S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1248         // Turn this into a "standard" conversion sequence, so that it
1249         // gets ranked with standard conversion sequences.
1250         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1251         ICS.setStandard();
1252         ICS.Standard.setAsIdentityConversion();
1253         ICS.Standard.setFromType(From->getType());
1254         ICS.Standard.setAllToTypes(ToType);
1255         ICS.Standard.CopyConstructor = Constructor;
1256         ICS.Standard.FoundCopyConstructor = Found;
1257         if (ToCanon != FromCanon)
1258           ICS.Standard.Second = ICK_Derived_To_Base;
1259       }
1260     }
1261     break;
1262
1263   case OR_Ambiguous:
1264     ICS.setAmbiguous();
1265     ICS.Ambiguous.setFromType(From->getType());
1266     ICS.Ambiguous.setToType(ToType);
1267     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1268          Cand != Conversions.end(); ++Cand)
1269       if (Cand->Viable)
1270         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1271     break;
1272
1273     // Fall through.
1274   case OR_No_Viable_Function:
1275     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1276     break;
1277   }
1278
1279   return ICS;
1280 }
1281
1282 /// TryImplicitConversion - Attempt to perform an implicit conversion
1283 /// from the given expression (Expr) to the given type (ToType). This
1284 /// function returns an implicit conversion sequence that can be used
1285 /// to perform the initialization. Given
1286 ///
1287 ///   void f(float f);
1288 ///   void g(int i) { f(i); }
1289 ///
1290 /// this routine would produce an implicit conversion sequence to
1291 /// describe the initialization of f from i, which will be a standard
1292 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1293 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1294 //
1295 /// Note that this routine only determines how the conversion can be
1296 /// performed; it does not actually perform the conversion. As such,
1297 /// it will not produce any diagnostics if no conversion is available,
1298 /// but will instead return an implicit conversion sequence of kind
1299 /// "BadConversion".
1300 ///
1301 /// If @p SuppressUserConversions, then user-defined conversions are
1302 /// not permitted.
1303 /// If @p AllowExplicit, then explicit user-defined conversions are
1304 /// permitted.
1305 ///
1306 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1307 /// writeback conversion, which allows __autoreleasing id* parameters to
1308 /// be initialized with __strong id* or __weak id* arguments.
1309 static ImplicitConversionSequence
1310 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1311                       bool SuppressUserConversions,
1312                       bool AllowExplicit,
1313                       bool InOverloadResolution,
1314                       bool CStyle,
1315                       bool AllowObjCWritebackConversion,
1316                       bool AllowObjCConversionOnExplicit) {
1317   ImplicitConversionSequence ICS;
1318   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1319                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1320     ICS.setStandard();
1321     return ICS;
1322   }
1323
1324   if (!S.getLangOpts().CPlusPlus) {
1325     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1326     return ICS;
1327   }
1328
1329   // C++ [over.ics.user]p4:
1330   //   A conversion of an expression of class type to the same class
1331   //   type is given Exact Match rank, and a conversion of an
1332   //   expression of class type to a base class of that type is
1333   //   given Conversion rank, in spite of the fact that a copy/move
1334   //   constructor (i.e., a user-defined conversion function) is
1335   //   called for those cases.
1336   QualType FromType = From->getType();
1337   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1338       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1339        S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1340     ICS.setStandard();
1341     ICS.Standard.setAsIdentityConversion();
1342     ICS.Standard.setFromType(FromType);
1343     ICS.Standard.setAllToTypes(ToType);
1344
1345     // We don't actually check at this point whether there is a valid
1346     // copy/move constructor, since overloading just assumes that it
1347     // exists. When we actually perform initialization, we'll find the
1348     // appropriate constructor to copy the returned object, if needed.
1349     ICS.Standard.CopyConstructor = nullptr;
1350
1351     // Determine whether this is considered a derived-to-base conversion.
1352     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1353       ICS.Standard.Second = ICK_Derived_To_Base;
1354
1355     return ICS;
1356   }
1357
1358   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1359                                   AllowExplicit, InOverloadResolution, CStyle,
1360                                   AllowObjCWritebackConversion,
1361                                   AllowObjCConversionOnExplicit);
1362 }
1363
1364 ImplicitConversionSequence
1365 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1366                             bool SuppressUserConversions,
1367                             bool AllowExplicit,
1368                             bool InOverloadResolution,
1369                             bool CStyle,
1370                             bool AllowObjCWritebackConversion) {
1371   return ::TryImplicitConversion(*this, From, ToType,
1372                                  SuppressUserConversions, AllowExplicit,
1373                                  InOverloadResolution, CStyle,
1374                                  AllowObjCWritebackConversion,
1375                                  /*AllowObjCConversionOnExplicit=*/false);
1376 }
1377
1378 /// PerformImplicitConversion - Perform an implicit conversion of the
1379 /// expression From to the type ToType. Returns the
1380 /// converted expression. Flavor is the kind of conversion we're
1381 /// performing, used in the error message. If @p AllowExplicit,
1382 /// explicit user-defined conversions are permitted.
1383 ExprResult
1384 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1385                                 AssignmentAction Action, bool AllowExplicit) {
1386   ImplicitConversionSequence ICS;
1387   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1388 }
1389
1390 ExprResult
1391 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1392                                 AssignmentAction Action, bool AllowExplicit,
1393                                 ImplicitConversionSequence& ICS) {
1394   if (checkPlaceholderForOverload(*this, From))
1395     return ExprError();
1396
1397   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1398   bool AllowObjCWritebackConversion
1399     = getLangOpts().ObjCAutoRefCount &&
1400       (Action == AA_Passing || Action == AA_Sending);
1401   if (getLangOpts().ObjC1)
1402     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1403                                       ToType, From->getType(), From);
1404   ICS = ::TryImplicitConversion(*this, From, ToType,
1405                                 /*SuppressUserConversions=*/false,
1406                                 AllowExplicit,
1407                                 /*InOverloadResolution=*/false,
1408                                 /*CStyle=*/false,
1409                                 AllowObjCWritebackConversion,
1410                                 /*AllowObjCConversionOnExplicit=*/false);
1411   return PerformImplicitConversion(From, ToType, ICS, Action);
1412 }
1413
1414 /// \brief Determine whether the conversion from FromType to ToType is a valid
1415 /// conversion that strips "noexcept" or "noreturn" off the nested function
1416 /// type.
1417 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1418                                 QualType &ResultTy) {
1419   if (Context.hasSameUnqualifiedType(FromType, ToType))
1420     return false;
1421
1422   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1423   //                    or F(t noexcept) -> F(t)
1424   // where F adds one of the following at most once:
1425   //   - a pointer
1426   //   - a member pointer
1427   //   - a block pointer
1428   // Changes here need matching changes in FindCompositePointerType.
1429   CanQualType CanTo = Context.getCanonicalType(ToType);
1430   CanQualType CanFrom = Context.getCanonicalType(FromType);
1431   Type::TypeClass TyClass = CanTo->getTypeClass();
1432   if (TyClass != CanFrom->getTypeClass()) return false;
1433   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1434     if (TyClass == Type::Pointer) {
1435       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1436       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1437     } else if (TyClass == Type::BlockPointer) {
1438       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1439       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1440     } else if (TyClass == Type::MemberPointer) {
1441       auto ToMPT = CanTo.getAs<MemberPointerType>();
1442       auto FromMPT = CanFrom.getAs<MemberPointerType>();
1443       // A function pointer conversion cannot change the class of the function.
1444       if (ToMPT->getClass() != FromMPT->getClass())
1445         return false;
1446       CanTo = ToMPT->getPointeeType();
1447       CanFrom = FromMPT->getPointeeType();
1448     } else {
1449       return false;
1450     }
1451
1452     TyClass = CanTo->getTypeClass();
1453     if (TyClass != CanFrom->getTypeClass()) return false;
1454     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1455       return false;
1456   }
1457
1458   const auto *FromFn = cast<FunctionType>(CanFrom);
1459   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1460
1461   const auto *ToFn = cast<FunctionType>(CanTo);
1462   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1463
1464   bool Changed = false;
1465
1466   // Drop 'noreturn' if not present in target type.
1467   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1468     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1469     Changed = true;
1470   }
1471
1472   // Drop 'noexcept' if not present in target type.
1473   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1474     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1475     if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1476       FromFn = cast<FunctionType>(
1477           Context.getFunctionType(FromFPT->getReturnType(),
1478                                   FromFPT->getParamTypes(),
1479                                   FromFPT->getExtProtoInfo().withExceptionSpec(
1480                                       FunctionProtoType::ExceptionSpecInfo()))
1481                  .getTypePtr());
1482       Changed = true;
1483     }
1484   }
1485
1486   if (!Changed)
1487     return false;
1488
1489   assert(QualType(FromFn, 0).isCanonical());
1490   if (QualType(FromFn, 0) != CanTo) return false;
1491
1492   ResultTy = ToType;
1493   return true;
1494 }
1495
1496 /// \brief Determine whether the conversion from FromType to ToType is a valid
1497 /// vector conversion.
1498 ///
1499 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1500 /// conversion.
1501 static bool IsVectorConversion(Sema &S, QualType FromType,
1502                                QualType ToType, ImplicitConversionKind &ICK) {
1503   // We need at least one of these types to be a vector type to have a vector
1504   // conversion.
1505   if (!ToType->isVectorType() && !FromType->isVectorType())
1506     return false;
1507
1508   // Identical types require no conversions.
1509   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1510     return false;
1511
1512   // There are no conversions between extended vector types, only identity.
1513   if (ToType->isExtVectorType()) {
1514     // There are no conversions between extended vector types other than the
1515     // identity conversion.
1516     if (FromType->isExtVectorType())
1517       return false;
1518
1519     // Vector splat from any arithmetic type to a vector.
1520     if (FromType->isArithmeticType()) {
1521       ICK = ICK_Vector_Splat;
1522       return true;
1523     }
1524   }
1525
1526   // We can perform the conversion between vector types in the following cases:
1527   // 1)vector types are equivalent AltiVec and GCC vector types
1528   // 2)lax vector conversions are permitted and the vector types are of the
1529   //   same size
1530   if (ToType->isVectorType() && FromType->isVectorType()) {
1531     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1532         S.isLaxVectorConversion(FromType, ToType)) {
1533       ICK = ICK_Vector_Conversion;
1534       return true;
1535     }
1536   }
1537
1538   return false;
1539 }
1540
1541 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1542                                 bool InOverloadResolution,
1543                                 StandardConversionSequence &SCS,
1544                                 bool CStyle);
1545
1546 /// IsStandardConversion - Determines whether there is a standard
1547 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1548 /// expression From to the type ToType. Standard conversion sequences
1549 /// only consider non-class types; for conversions that involve class
1550 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1551 /// contain the standard conversion sequence required to perform this
1552 /// conversion and this routine will return true. Otherwise, this
1553 /// routine will return false and the value of SCS is unspecified.
1554 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1555                                  bool InOverloadResolution,
1556                                  StandardConversionSequence &SCS,
1557                                  bool CStyle,
1558                                  bool AllowObjCWritebackConversion) {
1559   QualType FromType = From->getType();
1560
1561   // Standard conversions (C++ [conv])
1562   SCS.setAsIdentityConversion();
1563   SCS.IncompatibleObjC = false;
1564   SCS.setFromType(FromType);
1565   SCS.CopyConstructor = nullptr;
1566
1567   // There are no standard conversions for class types in C++, so
1568   // abort early. When overloading in C, however, we do permit them.
1569   if (S.getLangOpts().CPlusPlus &&
1570       (FromType->isRecordType() || ToType->isRecordType()))
1571     return false;
1572
1573   // The first conversion can be an lvalue-to-rvalue conversion,
1574   // array-to-pointer conversion, or function-to-pointer conversion
1575   // (C++ 4p1).
1576
1577   if (FromType == S.Context.OverloadTy) {
1578     DeclAccessPair AccessPair;
1579     if (FunctionDecl *Fn
1580           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1581                                                  AccessPair)) {
1582       // We were able to resolve the address of the overloaded function,
1583       // so we can convert to the type of that function.
1584       FromType = Fn->getType();
1585       SCS.setFromType(FromType);
1586
1587       // we can sometimes resolve &foo<int> regardless of ToType, so check
1588       // if the type matches (identity) or we are converting to bool
1589       if (!S.Context.hasSameUnqualifiedType(
1590                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1591         QualType resultTy;
1592         // if the function type matches except for [[noreturn]], it's ok
1593         if (!S.IsFunctionConversion(FromType,
1594               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1595           // otherwise, only a boolean conversion is standard
1596           if (!ToType->isBooleanType())
1597             return false;
1598       }
1599
1600       // Check if the "from" expression is taking the address of an overloaded
1601       // function and recompute the FromType accordingly. Take advantage of the
1602       // fact that non-static member functions *must* have such an address-of
1603       // expression.
1604       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1605       if (Method && !Method->isStatic()) {
1606         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1607                "Non-unary operator on non-static member address");
1608         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1609                == UO_AddrOf &&
1610                "Non-address-of operator on non-static member address");
1611         const Type *ClassType
1612           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1613         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1614       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1615         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1616                UO_AddrOf &&
1617                "Non-address-of operator for overloaded function expression");
1618         FromType = S.Context.getPointerType(FromType);
1619       }
1620
1621       // Check that we've computed the proper type after overload resolution.
1622       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1623       // be calling it from within an NDEBUG block.
1624       assert(S.Context.hasSameType(
1625         FromType,
1626         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1627     } else {
1628       return false;
1629     }
1630   }
1631   // Lvalue-to-rvalue conversion (C++11 4.1):
1632   //   A glvalue (3.10) of a non-function, non-array type T can
1633   //   be converted to a prvalue.
1634   bool argIsLValue = From->isGLValue();
1635   if (argIsLValue &&
1636       !FromType->isFunctionType() && !FromType->isArrayType() &&
1637       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1638     SCS.First = ICK_Lvalue_To_Rvalue;
1639
1640     // C11 6.3.2.1p2:
1641     //   ... if the lvalue has atomic type, the value has the non-atomic version
1642     //   of the type of the lvalue ...
1643     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1644       FromType = Atomic->getValueType();
1645
1646     // If T is a non-class type, the type of the rvalue is the
1647     // cv-unqualified version of T. Otherwise, the type of the rvalue
1648     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1649     // just strip the qualifiers because they don't matter.
1650     FromType = FromType.getUnqualifiedType();
1651   } else if (FromType->isArrayType()) {
1652     // Array-to-pointer conversion (C++ 4.2)
1653     SCS.First = ICK_Array_To_Pointer;
1654
1655     // An lvalue or rvalue of type "array of N T" or "array of unknown
1656     // bound of T" can be converted to an rvalue of type "pointer to
1657     // T" (C++ 4.2p1).
1658     FromType = S.Context.getArrayDecayedType(FromType);
1659
1660     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1661       // This conversion is deprecated in C++03 (D.4)
1662       SCS.DeprecatedStringLiteralToCharPtr = true;
1663
1664       // For the purpose of ranking in overload resolution
1665       // (13.3.3.1.1), this conversion is considered an
1666       // array-to-pointer conversion followed by a qualification
1667       // conversion (4.4). (C++ 4.2p2)
1668       SCS.Second = ICK_Identity;
1669       SCS.Third = ICK_Qualification;
1670       SCS.QualificationIncludesObjCLifetime = false;
1671       SCS.setAllToTypes(FromType);
1672       return true;
1673     }
1674   } else if (FromType->isFunctionType() && argIsLValue) {
1675     // Function-to-pointer conversion (C++ 4.3).
1676     SCS.First = ICK_Function_To_Pointer;
1677
1678     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1679       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1680         if (!S.checkAddressOfFunctionIsAvailable(FD))
1681           return false;
1682
1683     // An lvalue of function type T can be converted to an rvalue of
1684     // type "pointer to T." The result is a pointer to the
1685     // function. (C++ 4.3p1).
1686     FromType = S.Context.getPointerType(FromType);
1687   } else {
1688     // We don't require any conversions for the first step.
1689     SCS.First = ICK_Identity;
1690   }
1691   SCS.setToType(0, FromType);
1692
1693   // The second conversion can be an integral promotion, floating
1694   // point promotion, integral conversion, floating point conversion,
1695   // floating-integral conversion, pointer conversion,
1696   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1697   // For overloading in C, this can also be a "compatible-type"
1698   // conversion.
1699   bool IncompatibleObjC = false;
1700   ImplicitConversionKind SecondICK = ICK_Identity;
1701   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1702     // The unqualified versions of the types are the same: there's no
1703     // conversion to do.
1704     SCS.Second = ICK_Identity;
1705   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1706     // Integral promotion (C++ 4.5).
1707     SCS.Second = ICK_Integral_Promotion;
1708     FromType = ToType.getUnqualifiedType();
1709   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1710     // Floating point promotion (C++ 4.6).
1711     SCS.Second = ICK_Floating_Promotion;
1712     FromType = ToType.getUnqualifiedType();
1713   } else if (S.IsComplexPromotion(FromType, ToType)) {
1714     // Complex promotion (Clang extension)
1715     SCS.Second = ICK_Complex_Promotion;
1716     FromType = ToType.getUnqualifiedType();
1717   } else if (ToType->isBooleanType() &&
1718              (FromType->isArithmeticType() ||
1719               FromType->isAnyPointerType() ||
1720               FromType->isBlockPointerType() ||
1721               FromType->isMemberPointerType() ||
1722               FromType->isNullPtrType())) {
1723     // Boolean conversions (C++ 4.12).
1724     SCS.Second = ICK_Boolean_Conversion;
1725     FromType = S.Context.BoolTy;
1726   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1727              ToType->isIntegralType(S.Context)) {
1728     // Integral conversions (C++ 4.7).
1729     SCS.Second = ICK_Integral_Conversion;
1730     FromType = ToType.getUnqualifiedType();
1731   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1732     // Complex conversions (C99 6.3.1.6)
1733     SCS.Second = ICK_Complex_Conversion;
1734     FromType = ToType.getUnqualifiedType();
1735   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1736              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1737     // Complex-real conversions (C99 6.3.1.7)
1738     SCS.Second = ICK_Complex_Real;
1739     FromType = ToType.getUnqualifiedType();
1740   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1741     // FIXME: disable conversions between long double and __float128 if
1742     // their representation is different until there is back end support
1743     // We of course allow this conversion if long double is really double.
1744     if (&S.Context.getFloatTypeSemantics(FromType) !=
1745         &S.Context.getFloatTypeSemantics(ToType)) {
1746       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1747                                     ToType == S.Context.LongDoubleTy) ||
1748                                    (FromType == S.Context.LongDoubleTy &&
1749                                     ToType == S.Context.Float128Ty));
1750       if (Float128AndLongDouble &&
1751           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1752            &llvm::APFloat::IEEEdouble()))
1753         return false;
1754     }
1755     // Floating point conversions (C++ 4.8).
1756     SCS.Second = ICK_Floating_Conversion;
1757     FromType = ToType.getUnqualifiedType();
1758   } else if ((FromType->isRealFloatingType() &&
1759               ToType->isIntegralType(S.Context)) ||
1760              (FromType->isIntegralOrUnscopedEnumerationType() &&
1761               ToType->isRealFloatingType())) {
1762     // Floating-integral conversions (C++ 4.9).
1763     SCS.Second = ICK_Floating_Integral;
1764     FromType = ToType.getUnqualifiedType();
1765   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1766     SCS.Second = ICK_Block_Pointer_Conversion;
1767   } else if (AllowObjCWritebackConversion &&
1768              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1769     SCS.Second = ICK_Writeback_Conversion;
1770   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1771                                    FromType, IncompatibleObjC)) {
1772     // Pointer conversions (C++ 4.10).
1773     SCS.Second = ICK_Pointer_Conversion;
1774     SCS.IncompatibleObjC = IncompatibleObjC;
1775     FromType = FromType.getUnqualifiedType();
1776   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1777                                          InOverloadResolution, FromType)) {
1778     // Pointer to member conversions (4.11).
1779     SCS.Second = ICK_Pointer_Member;
1780   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1781     SCS.Second = SecondICK;
1782     FromType = ToType.getUnqualifiedType();
1783   } else if (!S.getLangOpts().CPlusPlus &&
1784              S.Context.typesAreCompatible(ToType, FromType)) {
1785     // Compatible conversions (Clang extension for C function overloading)
1786     SCS.Second = ICK_Compatible_Conversion;
1787     FromType = ToType.getUnqualifiedType();
1788   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1789                                              InOverloadResolution,
1790                                              SCS, CStyle)) {
1791     SCS.Second = ICK_TransparentUnionConversion;
1792     FromType = ToType;
1793   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1794                                  CStyle)) {
1795     // tryAtomicConversion has updated the standard conversion sequence
1796     // appropriately.
1797     return true;
1798   } else if (ToType->isEventT() &&
1799              From->isIntegerConstantExpr(S.getASTContext()) &&
1800              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1801     SCS.Second = ICK_Zero_Event_Conversion;
1802     FromType = ToType;
1803   } else if (ToType->isQueueT() &&
1804              From->isIntegerConstantExpr(S.getASTContext()) &&
1805              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1806     SCS.Second = ICK_Zero_Queue_Conversion;
1807     FromType = ToType;
1808   } else {
1809     // No second conversion required.
1810     SCS.Second = ICK_Identity;
1811   }
1812   SCS.setToType(1, FromType);
1813
1814   // The third conversion can be a function pointer conversion or a
1815   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1816   bool ObjCLifetimeConversion;
1817   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1818     // Function pointer conversions (removing 'noexcept') including removal of
1819     // 'noreturn' (Clang extension).
1820     SCS.Third = ICK_Function_Conversion;
1821   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1822                                          ObjCLifetimeConversion)) {
1823     SCS.Third = ICK_Qualification;
1824     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1825     FromType = ToType;
1826   } else {
1827     // No conversion required
1828     SCS.Third = ICK_Identity;
1829   }
1830
1831   // C++ [over.best.ics]p6:
1832   //   [...] Any difference in top-level cv-qualification is
1833   //   subsumed by the initialization itself and does not constitute
1834   //   a conversion. [...]
1835   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1836   QualType CanonTo = S.Context.getCanonicalType(ToType);
1837   if (CanonFrom.getLocalUnqualifiedType()
1838                                      == CanonTo.getLocalUnqualifiedType() &&
1839       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1840     FromType = ToType;
1841     CanonFrom = CanonTo;
1842   }
1843
1844   SCS.setToType(2, FromType);
1845
1846   if (CanonFrom == CanonTo)
1847     return true;
1848
1849   // If we have not converted the argument type to the parameter type,
1850   // this is a bad conversion sequence, unless we're resolving an overload in C.
1851   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1852     return false;
1853
1854   ExprResult ER = ExprResult{From};
1855   Sema::AssignConvertType Conv =
1856       S.CheckSingleAssignmentConstraints(ToType, ER,
1857                                          /*Diagnose=*/false,
1858                                          /*DiagnoseCFAudited=*/false,
1859                                          /*ConvertRHS=*/false);
1860   ImplicitConversionKind SecondConv;
1861   switch (Conv) {
1862   case Sema::Compatible:
1863     SecondConv = ICK_C_Only_Conversion;
1864     break;
1865   // For our purposes, discarding qualifiers is just as bad as using an
1866   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1867   // qualifiers, as well.
1868   case Sema::CompatiblePointerDiscardsQualifiers:
1869   case Sema::IncompatiblePointer:
1870   case Sema::IncompatiblePointerSign:
1871     SecondConv = ICK_Incompatible_Pointer_Conversion;
1872     break;
1873   default:
1874     return false;
1875   }
1876
1877   // First can only be an lvalue conversion, so we pretend that this was the
1878   // second conversion. First should already be valid from earlier in the
1879   // function.
1880   SCS.Second = SecondConv;
1881   SCS.setToType(1, ToType);
1882
1883   // Third is Identity, because Second should rank us worse than any other
1884   // conversion. This could also be ICK_Qualification, but it's simpler to just
1885   // lump everything in with the second conversion, and we don't gain anything
1886   // from making this ICK_Qualification.
1887   SCS.Third = ICK_Identity;
1888   SCS.setToType(2, ToType);
1889   return true;
1890 }
1891
1892 static bool
1893 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1894                                      QualType &ToType,
1895                                      bool InOverloadResolution,
1896                                      StandardConversionSequence &SCS,
1897                                      bool CStyle) {
1898
1899   const RecordType *UT = ToType->getAsUnionType();
1900   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1901     return false;
1902   // The field to initialize within the transparent union.
1903   RecordDecl *UD = UT->getDecl();
1904   // It's compatible if the expression matches any of the fields.
1905   for (const auto *it : UD->fields()) {
1906     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1907                              CStyle, /*ObjCWritebackConversion=*/false)) {
1908       ToType = it->getType();
1909       return true;
1910     }
1911   }
1912   return false;
1913 }
1914
1915 /// IsIntegralPromotion - Determines whether the conversion from the
1916 /// expression From (whose potentially-adjusted type is FromType) to
1917 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1918 /// sets PromotedType to the promoted type.
1919 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1920   const BuiltinType *To = ToType->getAs<BuiltinType>();
1921   // All integers are built-in.
1922   if (!To) {
1923     return false;
1924   }
1925
1926   // An rvalue of type char, signed char, unsigned char, short int, or
1927   // unsigned short int can be converted to an rvalue of type int if
1928   // int can represent all the values of the source type; otherwise,
1929   // the source rvalue can be converted to an rvalue of type unsigned
1930   // int (C++ 4.5p1).
1931   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1932       !FromType->isEnumeralType()) {
1933     if (// We can promote any signed, promotable integer type to an int
1934         (FromType->isSignedIntegerType() ||
1935          // We can promote any unsigned integer type whose size is
1936          // less than int to an int.
1937          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1938       return To->getKind() == BuiltinType::Int;
1939     }
1940
1941     return To->getKind() == BuiltinType::UInt;
1942   }
1943
1944   // C++11 [conv.prom]p3:
1945   //   A prvalue of an unscoped enumeration type whose underlying type is not
1946   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1947   //   following types that can represent all the values of the enumeration
1948   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1949   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1950   //   long long int. If none of the types in that list can represent all the
1951   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1952   //   type can be converted to an rvalue a prvalue of the extended integer type
1953   //   with lowest integer conversion rank (4.13) greater than the rank of long
1954   //   long in which all the values of the enumeration can be represented. If
1955   //   there are two such extended types, the signed one is chosen.
1956   // C++11 [conv.prom]p4:
1957   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1958   //   can be converted to a prvalue of its underlying type. Moreover, if
1959   //   integral promotion can be applied to its underlying type, a prvalue of an
1960   //   unscoped enumeration type whose underlying type is fixed can also be
1961   //   converted to a prvalue of the promoted underlying type.
1962   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1963     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1964     // provided for a scoped enumeration.
1965     if (FromEnumType->getDecl()->isScoped())
1966       return false;
1967
1968     // We can perform an integral promotion to the underlying type of the enum,
1969     // even if that's not the promoted type. Note that the check for promoting
1970     // the underlying type is based on the type alone, and does not consider
1971     // the bitfield-ness of the actual source expression.
1972     if (FromEnumType->getDecl()->isFixed()) {
1973       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1974       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1975              IsIntegralPromotion(nullptr, Underlying, ToType);
1976     }
1977
1978     // We have already pre-calculated the promotion type, so this is trivial.
1979     if (ToType->isIntegerType() &&
1980         isCompleteType(From->getLocStart(), FromType))
1981       return Context.hasSameUnqualifiedType(
1982           ToType, FromEnumType->getDecl()->getPromotionType());
1983   }
1984
1985   // C++0x [conv.prom]p2:
1986   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1987   //   to an rvalue a prvalue of the first of the following types that can
1988   //   represent all the values of its underlying type: int, unsigned int,
1989   //   long int, unsigned long int, long long int, or unsigned long long int.
1990   //   If none of the types in that list can represent all the values of its
1991   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1992   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1993   //   type.
1994   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1995       ToType->isIntegerType()) {
1996     // Determine whether the type we're converting from is signed or
1997     // unsigned.
1998     bool FromIsSigned = FromType->isSignedIntegerType();
1999     uint64_t FromSize = Context.getTypeSize(FromType);
2000
2001     // The types we'll try to promote to, in the appropriate
2002     // order. Try each of these types.
2003     QualType PromoteTypes[6] = {
2004       Context.IntTy, Context.UnsignedIntTy,
2005       Context.LongTy, Context.UnsignedLongTy ,
2006       Context.LongLongTy, Context.UnsignedLongLongTy
2007     };
2008     for (int Idx = 0; Idx < 6; ++Idx) {
2009       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2010       if (FromSize < ToSize ||
2011           (FromSize == ToSize &&
2012            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2013         // We found the type that we can promote to. If this is the
2014         // type we wanted, we have a promotion. Otherwise, no
2015         // promotion.
2016         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2017       }
2018     }
2019   }
2020
2021   // An rvalue for an integral bit-field (9.6) can be converted to an
2022   // rvalue of type int if int can represent all the values of the
2023   // bit-field; otherwise, it can be converted to unsigned int if
2024   // unsigned int can represent all the values of the bit-field. If
2025   // the bit-field is larger yet, no integral promotion applies to
2026   // it. If the bit-field has an enumerated type, it is treated as any
2027   // other value of that type for promotion purposes (C++ 4.5p3).
2028   // FIXME: We should delay checking of bit-fields until we actually perform the
2029   // conversion.
2030   if (From) {
2031     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2032       llvm::APSInt BitWidth;
2033       if (FromType->isIntegralType(Context) &&
2034           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2035         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2036         ToSize = Context.getTypeSize(ToType);
2037
2038         // Are we promoting to an int from a bitfield that fits in an int?
2039         if (BitWidth < ToSize ||
2040             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2041           return To->getKind() == BuiltinType::Int;
2042         }
2043
2044         // Are we promoting to an unsigned int from an unsigned bitfield
2045         // that fits into an unsigned int?
2046         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2047           return To->getKind() == BuiltinType::UInt;
2048         }
2049
2050         return false;
2051       }
2052     }
2053   }
2054
2055   // An rvalue of type bool can be converted to an rvalue of type int,
2056   // with false becoming zero and true becoming one (C++ 4.5p4).
2057   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2058     return true;
2059   }
2060
2061   return false;
2062 }
2063
2064 /// IsFloatingPointPromotion - Determines whether the conversion from
2065 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2066 /// returns true and sets PromotedType to the promoted type.
2067 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2068   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2069     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2070       /// An rvalue of type float can be converted to an rvalue of type
2071       /// double. (C++ 4.6p1).
2072       if (FromBuiltin->getKind() == BuiltinType::Float &&
2073           ToBuiltin->getKind() == BuiltinType::Double)
2074         return true;
2075
2076       // C99 6.3.1.5p1:
2077       //   When a float is promoted to double or long double, or a
2078       //   double is promoted to long double [...].
2079       if (!getLangOpts().CPlusPlus &&
2080           (FromBuiltin->getKind() == BuiltinType::Float ||
2081            FromBuiltin->getKind() == BuiltinType::Double) &&
2082           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2083            ToBuiltin->getKind() == BuiltinType::Float128))
2084         return true;
2085
2086       // Half can be promoted to float.
2087       if (!getLangOpts().NativeHalfType &&
2088            FromBuiltin->getKind() == BuiltinType::Half &&
2089           ToBuiltin->getKind() == BuiltinType::Float)
2090         return true;
2091     }
2092
2093   return false;
2094 }
2095
2096 /// \brief Determine if a conversion is a complex promotion.
2097 ///
2098 /// A complex promotion is defined as a complex -> complex conversion
2099 /// where the conversion between the underlying real types is a
2100 /// floating-point or integral promotion.
2101 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2102   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2103   if (!FromComplex)
2104     return false;
2105
2106   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2107   if (!ToComplex)
2108     return false;
2109
2110   return IsFloatingPointPromotion(FromComplex->getElementType(),
2111                                   ToComplex->getElementType()) ||
2112     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2113                         ToComplex->getElementType());
2114 }
2115
2116 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2117 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2118 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2119 /// if non-empty, will be a pointer to ToType that may or may not have
2120 /// the right set of qualifiers on its pointee.
2121 ///
2122 static QualType
2123 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2124                                    QualType ToPointee, QualType ToType,
2125                                    ASTContext &Context,
2126                                    bool StripObjCLifetime = false) {
2127   assert((FromPtr->getTypeClass() == Type::Pointer ||
2128           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2129          "Invalid similarly-qualified pointer type");
2130
2131   /// Conversions to 'id' subsume cv-qualifier conversions.
2132   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2133     return ToType.getUnqualifiedType();
2134
2135   QualType CanonFromPointee
2136     = Context.getCanonicalType(FromPtr->getPointeeType());
2137   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2138   Qualifiers Quals = CanonFromPointee.getQualifiers();
2139
2140   if (StripObjCLifetime)
2141     Quals.removeObjCLifetime();
2142
2143   // Exact qualifier match -> return the pointer type we're converting to.
2144   if (CanonToPointee.getLocalQualifiers() == Quals) {
2145     // ToType is exactly what we need. Return it.
2146     if (!ToType.isNull())
2147       return ToType.getUnqualifiedType();
2148
2149     // Build a pointer to ToPointee. It has the right qualifiers
2150     // already.
2151     if (isa<ObjCObjectPointerType>(ToType))
2152       return Context.getObjCObjectPointerType(ToPointee);
2153     return Context.getPointerType(ToPointee);
2154   }
2155
2156   // Just build a canonical type that has the right qualifiers.
2157   QualType QualifiedCanonToPointee
2158     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2159
2160   if (isa<ObjCObjectPointerType>(ToType))
2161     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2162   return Context.getPointerType(QualifiedCanonToPointee);
2163 }
2164
2165 static bool isNullPointerConstantForConversion(Expr *Expr,
2166                                                bool InOverloadResolution,
2167                                                ASTContext &Context) {
2168   // Handle value-dependent integral null pointer constants correctly.
2169   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2170   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2171       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2172     return !InOverloadResolution;
2173
2174   return Expr->isNullPointerConstant(Context,
2175                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2176                                         : Expr::NPC_ValueDependentIsNull);
2177 }
2178
2179 /// IsPointerConversion - Determines whether the conversion of the
2180 /// expression From, which has the (possibly adjusted) type FromType,
2181 /// can be converted to the type ToType via a pointer conversion (C++
2182 /// 4.10). If so, returns true and places the converted type (that
2183 /// might differ from ToType in its cv-qualifiers at some level) into
2184 /// ConvertedType.
2185 ///
2186 /// This routine also supports conversions to and from block pointers
2187 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2188 /// pointers to interfaces. FIXME: Once we've determined the
2189 /// appropriate overloading rules for Objective-C, we may want to
2190 /// split the Objective-C checks into a different routine; however,
2191 /// GCC seems to consider all of these conversions to be pointer
2192 /// conversions, so for now they live here. IncompatibleObjC will be
2193 /// set if the conversion is an allowed Objective-C conversion that
2194 /// should result in a warning.
2195 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2196                                bool InOverloadResolution,
2197                                QualType& ConvertedType,
2198                                bool &IncompatibleObjC) {
2199   IncompatibleObjC = false;
2200   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2201                               IncompatibleObjC))
2202     return true;
2203
2204   // Conversion from a null pointer constant to any Objective-C pointer type.
2205   if (ToType->isObjCObjectPointerType() &&
2206       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2207     ConvertedType = ToType;
2208     return true;
2209   }
2210
2211   // Blocks: Block pointers can be converted to void*.
2212   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2213       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2214     ConvertedType = ToType;
2215     return true;
2216   }
2217   // Blocks: A null pointer constant can be converted to a block
2218   // pointer type.
2219   if (ToType->isBlockPointerType() &&
2220       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2221     ConvertedType = ToType;
2222     return true;
2223   }
2224
2225   // If the left-hand-side is nullptr_t, the right side can be a null
2226   // pointer constant.
2227   if (ToType->isNullPtrType() &&
2228       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2229     ConvertedType = ToType;
2230     return true;
2231   }
2232
2233   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2234   if (!ToTypePtr)
2235     return false;
2236
2237   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2238   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2239     ConvertedType = ToType;
2240     return true;
2241   }
2242
2243   // Beyond this point, both types need to be pointers
2244   // , including objective-c pointers.
2245   QualType ToPointeeType = ToTypePtr->getPointeeType();
2246   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2247       !getLangOpts().ObjCAutoRefCount) {
2248     ConvertedType = BuildSimilarlyQualifiedPointerType(
2249                                       FromType->getAs<ObjCObjectPointerType>(),
2250                                                        ToPointeeType,
2251                                                        ToType, Context);
2252     return true;
2253   }
2254   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2255   if (!FromTypePtr)
2256     return false;
2257
2258   QualType FromPointeeType = FromTypePtr->getPointeeType();
2259
2260   // If the unqualified pointee types are the same, this can't be a
2261   // pointer conversion, so don't do all of the work below.
2262   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2263     return false;
2264
2265   // An rvalue of type "pointer to cv T," where T is an object type,
2266   // can be converted to an rvalue of type "pointer to cv void" (C++
2267   // 4.10p2).
2268   if (FromPointeeType->isIncompleteOrObjectType() &&
2269       ToPointeeType->isVoidType()) {
2270     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2271                                                        ToPointeeType,
2272                                                        ToType, Context,
2273                                                    /*StripObjCLifetime=*/true);
2274     return true;
2275   }
2276
2277   // MSVC allows implicit function to void* type conversion.
2278   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2279       ToPointeeType->isVoidType()) {
2280     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2281                                                        ToPointeeType,
2282                                                        ToType, Context);
2283     return true;
2284   }
2285
2286   // When we're overloading in C, we allow a special kind of pointer
2287   // conversion for compatible-but-not-identical pointee types.
2288   if (!getLangOpts().CPlusPlus &&
2289       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2290     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2291                                                        ToPointeeType,
2292                                                        ToType, Context);
2293     return true;
2294   }
2295
2296   // C++ [conv.ptr]p3:
2297   //
2298   //   An rvalue of type "pointer to cv D," where D is a class type,
2299   //   can be converted to an rvalue of type "pointer to cv B," where
2300   //   B is a base class (clause 10) of D. If B is an inaccessible
2301   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2302   //   necessitates this conversion is ill-formed. The result of the
2303   //   conversion is a pointer to the base class sub-object of the
2304   //   derived class object. The null pointer value is converted to
2305   //   the null pointer value of the destination type.
2306   //
2307   // Note that we do not check for ambiguity or inaccessibility
2308   // here. That is handled by CheckPointerConversion.
2309   if (getLangOpts().CPlusPlus &&
2310       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2311       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2312       IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2313     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2314                                                        ToPointeeType,
2315                                                        ToType, Context);
2316     return true;
2317   }
2318
2319   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2320       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2321     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2322                                                        ToPointeeType,
2323                                                        ToType, Context);
2324     return true;
2325   }
2326
2327   return false;
2328 }
2329
2330 /// \brief Adopt the given qualifiers for the given type.
2331 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2332   Qualifiers TQs = T.getQualifiers();
2333
2334   // Check whether qualifiers already match.
2335   if (TQs == Qs)
2336     return T;
2337
2338   if (Qs.compatiblyIncludes(TQs))
2339     return Context.getQualifiedType(T, Qs);
2340
2341   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2342 }
2343
2344 /// isObjCPointerConversion - Determines whether this is an
2345 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2346 /// with the same arguments and return values.
2347 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2348                                    QualType& ConvertedType,
2349                                    bool &IncompatibleObjC) {
2350   if (!getLangOpts().ObjC1)
2351     return false;
2352
2353   // The set of qualifiers on the type we're converting from.
2354   Qualifiers FromQualifiers = FromType.getQualifiers();
2355
2356   // First, we handle all conversions on ObjC object pointer types.
2357   const ObjCObjectPointerType* ToObjCPtr =
2358     ToType->getAs<ObjCObjectPointerType>();
2359   const ObjCObjectPointerType *FromObjCPtr =
2360     FromType->getAs<ObjCObjectPointerType>();
2361
2362   if (ToObjCPtr && FromObjCPtr) {
2363     // If the pointee types are the same (ignoring qualifications),
2364     // then this is not a pointer conversion.
2365     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2366                                        FromObjCPtr->getPointeeType()))
2367       return false;
2368
2369     // Conversion between Objective-C pointers.
2370     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2371       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2372       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2373       if (getLangOpts().CPlusPlus && LHS && RHS &&
2374           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2375                                                 FromObjCPtr->getPointeeType()))
2376         return false;
2377       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2378                                                    ToObjCPtr->getPointeeType(),
2379                                                          ToType, Context);
2380       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2381       return true;
2382     }
2383
2384     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2385       // Okay: this is some kind of implicit downcast of Objective-C
2386       // interfaces, which is permitted. However, we're going to
2387       // complain about it.
2388       IncompatibleObjC = true;
2389       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2390                                                    ToObjCPtr->getPointeeType(),
2391                                                          ToType, Context);
2392       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2393       return true;
2394     }
2395   }
2396   // Beyond this point, both types need to be C pointers or block pointers.
2397   QualType ToPointeeType;
2398   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2399     ToPointeeType = ToCPtr->getPointeeType();
2400   else if (const BlockPointerType *ToBlockPtr =
2401             ToType->getAs<BlockPointerType>()) {
2402     // Objective C++: We're able to convert from a pointer to any object
2403     // to a block pointer type.
2404     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2405       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2406       return true;
2407     }
2408     ToPointeeType = ToBlockPtr->getPointeeType();
2409   }
2410   else if (FromType->getAs<BlockPointerType>() &&
2411            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2412     // Objective C++: We're able to convert from a block pointer type to a
2413     // pointer to any object.
2414     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2415     return true;
2416   }
2417   else
2418     return false;
2419
2420   QualType FromPointeeType;
2421   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2422     FromPointeeType = FromCPtr->getPointeeType();
2423   else if (const BlockPointerType *FromBlockPtr =
2424            FromType->getAs<BlockPointerType>())
2425     FromPointeeType = FromBlockPtr->getPointeeType();
2426   else
2427     return false;
2428
2429   // If we have pointers to pointers, recursively check whether this
2430   // is an Objective-C conversion.
2431   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2432       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2433                               IncompatibleObjC)) {
2434     // We always complain about this conversion.
2435     IncompatibleObjC = true;
2436     ConvertedType = Context.getPointerType(ConvertedType);
2437     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2438     return true;
2439   }
2440   // Allow conversion of pointee being objective-c pointer to another one;
2441   // as in I* to id.
2442   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2443       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2444       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2445                               IncompatibleObjC)) {
2446
2447     ConvertedType = Context.getPointerType(ConvertedType);
2448     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2449     return true;
2450   }
2451
2452   // If we have pointers to functions or blocks, check whether the only
2453   // differences in the argument and result types are in Objective-C
2454   // pointer conversions. If so, we permit the conversion (but
2455   // complain about it).
2456   const FunctionProtoType *FromFunctionType
2457     = FromPointeeType->getAs<FunctionProtoType>();
2458   const FunctionProtoType *ToFunctionType
2459     = ToPointeeType->getAs<FunctionProtoType>();
2460   if (FromFunctionType && ToFunctionType) {
2461     // If the function types are exactly the same, this isn't an
2462     // Objective-C pointer conversion.
2463     if (Context.getCanonicalType(FromPointeeType)
2464           == Context.getCanonicalType(ToPointeeType))
2465       return false;
2466
2467     // Perform the quick checks that will tell us whether these
2468     // function types are obviously different.
2469     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2470         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2471         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2472       return false;
2473
2474     bool HasObjCConversion = false;
2475     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2476         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2477       // Okay, the types match exactly. Nothing to do.
2478     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2479                                        ToFunctionType->getReturnType(),
2480                                        ConvertedType, IncompatibleObjC)) {
2481       // Okay, we have an Objective-C pointer conversion.
2482       HasObjCConversion = true;
2483     } else {
2484       // Function types are too different. Abort.
2485       return false;
2486     }
2487
2488     // Check argument types.
2489     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2490          ArgIdx != NumArgs; ++ArgIdx) {
2491       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2492       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2493       if (Context.getCanonicalType(FromArgType)
2494             == Context.getCanonicalType(ToArgType)) {
2495         // Okay, the types match exactly. Nothing to do.
2496       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2497                                          ConvertedType, IncompatibleObjC)) {
2498         // Okay, we have an Objective-C pointer conversion.
2499         HasObjCConversion = true;
2500       } else {
2501         // Argument types are too different. Abort.
2502         return false;
2503       }
2504     }
2505
2506     if (HasObjCConversion) {
2507       // We had an Objective-C conversion. Allow this pointer
2508       // conversion, but complain about it.
2509       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2510       IncompatibleObjC = true;
2511       return true;
2512     }
2513   }
2514
2515   return false;
2516 }
2517
2518 /// \brief Determine whether this is an Objective-C writeback conversion,
2519 /// used for parameter passing when performing automatic reference counting.
2520 ///
2521 /// \param FromType The type we're converting form.
2522 ///
2523 /// \param ToType The type we're converting to.
2524 ///
2525 /// \param ConvertedType The type that will be produced after applying
2526 /// this conversion.
2527 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2528                                      QualType &ConvertedType) {
2529   if (!getLangOpts().ObjCAutoRefCount ||
2530       Context.hasSameUnqualifiedType(FromType, ToType))
2531     return false;
2532
2533   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2534   QualType ToPointee;
2535   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2536     ToPointee = ToPointer->getPointeeType();
2537   else
2538     return false;
2539
2540   Qualifiers ToQuals = ToPointee.getQualifiers();
2541   if (!ToPointee->isObjCLifetimeType() ||
2542       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2543       !ToQuals.withoutObjCLifetime().empty())
2544     return false;
2545
2546   // Argument must be a pointer to __strong to __weak.
2547   QualType FromPointee;
2548   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2549     FromPointee = FromPointer->getPointeeType();
2550   else
2551     return false;
2552
2553   Qualifiers FromQuals = FromPointee.getQualifiers();
2554   if (!FromPointee->isObjCLifetimeType() ||
2555       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2556        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2557     return false;
2558
2559   // Make sure that we have compatible qualifiers.
2560   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2561   if (!ToQuals.compatiblyIncludes(FromQuals))
2562     return false;
2563
2564   // Remove qualifiers from the pointee type we're converting from; they
2565   // aren't used in the compatibility check belong, and we'll be adding back
2566   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2567   FromPointee = FromPointee.getUnqualifiedType();
2568
2569   // The unqualified form of the pointee types must be compatible.
2570   ToPointee = ToPointee.getUnqualifiedType();
2571   bool IncompatibleObjC;
2572   if (Context.typesAreCompatible(FromPointee, ToPointee))
2573     FromPointee = ToPointee;
2574   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2575                                     IncompatibleObjC))
2576     return false;
2577
2578   /// \brief Construct the type we're converting to, which is a pointer to
2579   /// __autoreleasing pointee.
2580   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2581   ConvertedType = Context.getPointerType(FromPointee);
2582   return true;
2583 }
2584
2585 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2586                                     QualType& ConvertedType) {
2587   QualType ToPointeeType;
2588   if (const BlockPointerType *ToBlockPtr =
2589         ToType->getAs<BlockPointerType>())
2590     ToPointeeType = ToBlockPtr->getPointeeType();
2591   else
2592     return false;
2593
2594   QualType FromPointeeType;
2595   if (const BlockPointerType *FromBlockPtr =
2596       FromType->getAs<BlockPointerType>())
2597     FromPointeeType = FromBlockPtr->getPointeeType();
2598   else
2599     return false;
2600   // We have pointer to blocks, check whether the only
2601   // differences in the argument and result types are in Objective-C
2602   // pointer conversions. If so, we permit the conversion.
2603
2604   const FunctionProtoType *FromFunctionType
2605     = FromPointeeType->getAs<FunctionProtoType>();
2606   const FunctionProtoType *ToFunctionType
2607     = ToPointeeType->getAs<FunctionProtoType>();
2608
2609   if (!FromFunctionType || !ToFunctionType)
2610     return false;
2611
2612   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2613     return true;
2614
2615   // Perform the quick checks that will tell us whether these
2616   // function types are obviously different.
2617   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2618       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2619     return false;
2620
2621   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2622   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2623   if (FromEInfo != ToEInfo)
2624     return false;
2625
2626   bool IncompatibleObjC = false;
2627   if (Context.hasSameType(FromFunctionType->getReturnType(),
2628                           ToFunctionType->getReturnType())) {
2629     // Okay, the types match exactly. Nothing to do.
2630   } else {
2631     QualType RHS = FromFunctionType->getReturnType();
2632     QualType LHS = ToFunctionType->getReturnType();
2633     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2634         !RHS.hasQualifiers() && LHS.hasQualifiers())
2635        LHS = LHS.getUnqualifiedType();
2636
2637      if (Context.hasSameType(RHS,LHS)) {
2638        // OK exact match.
2639      } else if (isObjCPointerConversion(RHS, LHS,
2640                                         ConvertedType, IncompatibleObjC)) {
2641      if (IncompatibleObjC)
2642        return false;
2643      // Okay, we have an Objective-C pointer conversion.
2644      }
2645      else
2646        return false;
2647    }
2648
2649    // Check argument types.
2650    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2651         ArgIdx != NumArgs; ++ArgIdx) {
2652      IncompatibleObjC = false;
2653      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2654      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2655      if (Context.hasSameType(FromArgType, ToArgType)) {
2656        // Okay, the types match exactly. Nothing to do.
2657      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2658                                         ConvertedType, IncompatibleObjC)) {
2659        if (IncompatibleObjC)
2660          return false;
2661        // Okay, we have an Objective-C pointer conversion.
2662      } else
2663        // Argument types are too different. Abort.
2664        return false;
2665    }
2666    if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2667                                                         ToFunctionType))
2668      return false;
2669
2670    ConvertedType = ToType;
2671    return true;
2672 }
2673
2674 enum {
2675   ft_default,
2676   ft_different_class,
2677   ft_parameter_arity,
2678   ft_parameter_mismatch,
2679   ft_return_type,
2680   ft_qualifer_mismatch,
2681   ft_noexcept
2682 };
2683
2684 /// Attempts to get the FunctionProtoType from a Type. Handles
2685 /// MemberFunctionPointers properly.
2686 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2687   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2688     return FPT;
2689
2690   if (auto *MPT = FromType->getAs<MemberPointerType>())
2691     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2692
2693   return nullptr;
2694 }
2695
2696 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2697 /// function types.  Catches different number of parameter, mismatch in
2698 /// parameter types, and different return types.
2699 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2700                                       QualType FromType, QualType ToType) {
2701   // If either type is not valid, include no extra info.
2702   if (FromType.isNull() || ToType.isNull()) {
2703     PDiag << ft_default;
2704     return;
2705   }
2706
2707   // Get the function type from the pointers.
2708   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2709     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2710                             *ToMember = ToType->getAs<MemberPointerType>();
2711     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2712       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2713             << QualType(FromMember->getClass(), 0);
2714       return;
2715     }
2716     FromType = FromMember->getPointeeType();
2717     ToType = ToMember->getPointeeType();
2718   }
2719
2720   if (FromType->isPointerType())
2721     FromType = FromType->getPointeeType();
2722   if (ToType->isPointerType())
2723     ToType = ToType->getPointeeType();
2724
2725   // Remove references.
2726   FromType = FromType.getNonReferenceType();
2727   ToType = ToType.getNonReferenceType();
2728
2729   // Don't print extra info for non-specialized template functions.
2730   if (FromType->isInstantiationDependentType() &&
2731       !FromType->getAs<TemplateSpecializationType>()) {
2732     PDiag << ft_default;
2733     return;
2734   }
2735
2736   // No extra info for same types.
2737   if (Context.hasSameType(FromType, ToType)) {
2738     PDiag << ft_default;
2739     return;
2740   }
2741
2742   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2743                           *ToFunction = tryGetFunctionProtoType(ToType);
2744
2745   // Both types need to be function types.
2746   if (!FromFunction || !ToFunction) {
2747     PDiag << ft_default;
2748     return;
2749   }
2750
2751   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2752     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2753           << FromFunction->getNumParams();
2754     return;
2755   }
2756
2757   // Handle different parameter types.
2758   unsigned ArgPos;
2759   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2760     PDiag << ft_parameter_mismatch << ArgPos + 1
2761           << ToFunction->getParamType(ArgPos)
2762           << FromFunction->getParamType(ArgPos);
2763     return;
2764   }
2765
2766   // Handle different return type.
2767   if (!Context.hasSameType(FromFunction->getReturnType(),
2768                            ToFunction->getReturnType())) {
2769     PDiag << ft_return_type << ToFunction->getReturnType()
2770           << FromFunction->getReturnType();
2771     return;
2772   }
2773
2774   unsigned FromQuals = FromFunction->getTypeQuals(),
2775            ToQuals = ToFunction->getTypeQuals();
2776   if (FromQuals != ToQuals) {
2777     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2778     return;
2779   }
2780
2781   // Handle exception specification differences on canonical type (in C++17
2782   // onwards).
2783   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2784           ->isNothrow(Context) !=
2785       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2786           ->isNothrow(Context)) {
2787     PDiag << ft_noexcept;
2788     return;
2789   }
2790
2791   // Unable to find a difference, so add no extra info.
2792   PDiag << ft_default;
2793 }
2794
2795 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2796 /// for equality of their argument types. Caller has already checked that
2797 /// they have same number of arguments.  If the parameters are different,
2798 /// ArgPos will have the parameter index of the first different parameter.
2799 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2800                                       const FunctionProtoType *NewType,
2801                                       unsigned *ArgPos) {
2802   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2803                                               N = NewType->param_type_begin(),
2804                                               E = OldType->param_type_end();
2805        O && (O != E); ++O, ++N) {
2806     if (!Context.hasSameType(O->getUnqualifiedType(),
2807                              N->getUnqualifiedType())) {
2808       if (ArgPos)
2809         *ArgPos = O - OldType->param_type_begin();
2810       return false;
2811     }
2812   }
2813   return true;
2814 }
2815
2816 /// CheckPointerConversion - Check the pointer conversion from the
2817 /// expression From to the type ToType. This routine checks for
2818 /// ambiguous or inaccessible derived-to-base pointer
2819 /// conversions for which IsPointerConversion has already returned
2820 /// true. It returns true and produces a diagnostic if there was an
2821 /// error, or returns false otherwise.
2822 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2823                                   CastKind &Kind,
2824                                   CXXCastPath& BasePath,
2825                                   bool IgnoreBaseAccess,
2826                                   bool Diagnose) {
2827   QualType FromType = From->getType();
2828   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2829
2830   Kind = CK_BitCast;
2831
2832   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2833       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2834           Expr::NPCK_ZeroExpression) {
2835     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2836       DiagRuntimeBehavior(From->getExprLoc(), From,
2837                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2838                             << ToType << From->getSourceRange());
2839     else if (!isUnevaluatedContext())
2840       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2841         << ToType << From->getSourceRange();
2842   }
2843   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2844     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2845       QualType FromPointeeType = FromPtrType->getPointeeType(),
2846                ToPointeeType   = ToPtrType->getPointeeType();
2847
2848       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2849           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2850         // We must have a derived-to-base conversion. Check an
2851         // ambiguous or inaccessible conversion.
2852         unsigned InaccessibleID = 0;
2853         unsigned AmbigiousID = 0;
2854         if (Diagnose) {
2855           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2856           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2857         }
2858         if (CheckDerivedToBaseConversion(
2859                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2860                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2861                 &BasePath, IgnoreBaseAccess))
2862           return true;
2863
2864         // The conversion was successful.
2865         Kind = CK_DerivedToBase;
2866       }
2867
2868       if (Diagnose && !IsCStyleOrFunctionalCast &&
2869           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2870         assert(getLangOpts().MSVCCompat &&
2871                "this should only be possible with MSVCCompat!");
2872         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2873             << From->getSourceRange();
2874       }
2875     }
2876   } else if (const ObjCObjectPointerType *ToPtrType =
2877                ToType->getAs<ObjCObjectPointerType>()) {
2878     if (const ObjCObjectPointerType *FromPtrType =
2879           FromType->getAs<ObjCObjectPointerType>()) {
2880       // Objective-C++ conversions are always okay.
2881       // FIXME: We should have a different class of conversions for the
2882       // Objective-C++ implicit conversions.
2883       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2884         return false;
2885     } else if (FromType->isBlockPointerType()) {
2886       Kind = CK_BlockPointerToObjCPointerCast;
2887     } else {
2888       Kind = CK_CPointerToObjCPointerCast;
2889     }
2890   } else if (ToType->isBlockPointerType()) {
2891     if (!FromType->isBlockPointerType())
2892       Kind = CK_AnyPointerToBlockPointerCast;
2893   }
2894
2895   // We shouldn't fall into this case unless it's valid for other
2896   // reasons.
2897   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2898     Kind = CK_NullToPointer;
2899
2900   return false;
2901 }
2902
2903 /// IsMemberPointerConversion - Determines whether the conversion of the
2904 /// expression From, which has the (possibly adjusted) type FromType, can be
2905 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2906 /// If so, returns true and places the converted type (that might differ from
2907 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2908 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2909                                      QualType ToType,
2910                                      bool InOverloadResolution,
2911                                      QualType &ConvertedType) {
2912   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2913   if (!ToTypePtr)
2914     return false;
2915
2916   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2917   if (From->isNullPointerConstant(Context,
2918                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2919                                         : Expr::NPC_ValueDependentIsNull)) {
2920     ConvertedType = ToType;
2921     return true;
2922   }
2923
2924   // Otherwise, both types have to be member pointers.
2925   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2926   if (!FromTypePtr)
2927     return false;
2928
2929   // A pointer to member of B can be converted to a pointer to member of D,
2930   // where D is derived from B (C++ 4.11p2).
2931   QualType FromClass(FromTypePtr->getClass(), 0);
2932   QualType ToClass(ToTypePtr->getClass(), 0);
2933
2934   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2935       IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2936     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2937                                                  ToClass.getTypePtr());
2938     return true;
2939   }
2940
2941   return false;
2942 }
2943
2944 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2945 /// expression From to the type ToType. This routine checks for ambiguous or
2946 /// virtual or inaccessible base-to-derived member pointer conversions
2947 /// for which IsMemberPointerConversion has already returned true. It returns
2948 /// true and produces a diagnostic if there was an error, or returns false
2949 /// otherwise.
2950 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2951                                         CastKind &Kind,
2952                                         CXXCastPath &BasePath,
2953                                         bool IgnoreBaseAccess) {
2954   QualType FromType = From->getType();
2955   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2956   if (!FromPtrType) {
2957     // This must be a null pointer to member pointer conversion
2958     assert(From->isNullPointerConstant(Context,
2959                                        Expr::NPC_ValueDependentIsNull) &&
2960            "Expr must be null pointer constant!");
2961     Kind = CK_NullToMemberPointer;
2962     return false;
2963   }
2964
2965   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2966   assert(ToPtrType && "No member pointer cast has a target type "
2967                       "that is not a member pointer.");
2968
2969   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2970   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2971
2972   // FIXME: What about dependent types?
2973   assert(FromClass->isRecordType() && "Pointer into non-class.");
2974   assert(ToClass->isRecordType() && "Pointer into non-class.");
2975
2976   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2977                      /*DetectVirtual=*/true);
2978   bool DerivationOkay =
2979       IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2980   assert(DerivationOkay &&
2981          "Should not have been called if derivation isn't OK.");
2982   (void)DerivationOkay;
2983
2984   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2985                                   getUnqualifiedType())) {
2986     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2987     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2988       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2989     return true;
2990   }
2991
2992   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2993     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2994       << FromClass << ToClass << QualType(VBase, 0)
2995       << From->getSourceRange();
2996     return true;
2997   }
2998
2999   if (!IgnoreBaseAccess)
3000     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3001                          Paths.front(),
3002                          diag::err_downcast_from_inaccessible_base);
3003
3004   // Must be a base to derived member conversion.
3005   BuildBasePathArray(Paths, BasePath);
3006   Kind = CK_BaseToDerivedMemberPointer;
3007   return false;
3008 }
3009
3010 /// Determine whether the lifetime conversion between the two given
3011 /// qualifiers sets is nontrivial.
3012 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3013                                                Qualifiers ToQuals) {
3014   // Converting anything to const __unsafe_unretained is trivial.
3015   if (ToQuals.hasConst() &&
3016       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3017     return false;
3018
3019   return true;
3020 }
3021
3022 /// IsQualificationConversion - Determines whether the conversion from
3023 /// an rvalue of type FromType to ToType is a qualification conversion
3024 /// (C++ 4.4).
3025 ///
3026 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3027 /// when the qualification conversion involves a change in the Objective-C
3028 /// object lifetime.
3029 bool
3030 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3031                                 bool CStyle, bool &ObjCLifetimeConversion) {
3032   FromType = Context.getCanonicalType(FromType);
3033   ToType = Context.getCanonicalType(ToType);
3034   ObjCLifetimeConversion = false;
3035
3036   // If FromType and ToType are the same type, this is not a
3037   // qualification conversion.
3038   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3039     return false;
3040
3041   // (C++ 4.4p4):
3042   //   A conversion can add cv-qualifiers at levels other than the first
3043   //   in multi-level pointers, subject to the following rules: [...]
3044   bool PreviousToQualsIncludeConst = true;
3045   bool UnwrappedAnyPointer = false;
3046   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3047     // Within each iteration of the loop, we check the qualifiers to
3048     // determine if this still looks like a qualification
3049     // conversion. Then, if all is well, we unwrap one more level of
3050     // pointers or pointers-to-members and do it all again
3051     // until there are no more pointers or pointers-to-members left to
3052     // unwrap.
3053     UnwrappedAnyPointer = true;
3054
3055     Qualifiers FromQuals = FromType.getQualifiers();
3056     Qualifiers ToQuals = ToType.getQualifiers();
3057
3058     // Ignore __unaligned qualifier if this type is void.
3059     if (ToType.getUnqualifiedType()->isVoidType())
3060       FromQuals.removeUnaligned();
3061
3062     // Objective-C ARC:
3063     //   Check Objective-C lifetime conversions.
3064     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3065         UnwrappedAnyPointer) {
3066       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3067         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3068           ObjCLifetimeConversion = true;
3069         FromQuals.removeObjCLifetime();
3070         ToQuals.removeObjCLifetime();
3071       } else {
3072         // Qualification conversions cannot cast between different
3073         // Objective-C lifetime qualifiers.
3074         return false;
3075       }
3076     }
3077
3078     // Allow addition/removal of GC attributes but not changing GC attributes.
3079     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3080         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3081       FromQuals.removeObjCGCAttr();
3082       ToQuals.removeObjCGCAttr();
3083     }
3084
3085     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3086     //      2,j, and similarly for volatile.
3087     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3088       return false;
3089
3090     //   -- if the cv 1,j and cv 2,j are different, then const is in
3091     //      every cv for 0 < k < j.
3092     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3093         && !PreviousToQualsIncludeConst)
3094       return false;
3095
3096     // Keep track of whether all prior cv-qualifiers in the "to" type
3097     // include const.
3098     PreviousToQualsIncludeConst
3099       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3100   }
3101
3102   // We are left with FromType and ToType being the pointee types
3103   // after unwrapping the original FromType and ToType the same number
3104   // of types. If we unwrapped any pointers, and if FromType and
3105   // ToType have the same unqualified type (since we checked
3106   // qualifiers above), then this is a qualification conversion.
3107   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3108 }
3109
3110 /// \brief - Determine whether this is a conversion from a scalar type to an
3111 /// atomic type.
3112 ///
3113 /// If successful, updates \c SCS's second and third steps in the conversion
3114 /// sequence to finish the conversion.
3115 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3116                                 bool InOverloadResolution,
3117                                 StandardConversionSequence &SCS,
3118                                 bool CStyle) {
3119   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3120   if (!ToAtomic)
3121     return false;
3122
3123   StandardConversionSequence InnerSCS;
3124   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3125                             InOverloadResolution, InnerSCS,
3126                             CStyle, /*AllowObjCWritebackConversion=*/false))
3127     return false;
3128
3129   SCS.Second = InnerSCS.Second;
3130   SCS.setToType(1, InnerSCS.getToType(1));
3131   SCS.Third = InnerSCS.Third;
3132   SCS.QualificationIncludesObjCLifetime
3133     = InnerSCS.QualificationIncludesObjCLifetime;
3134   SCS.setToType(2, InnerSCS.getToType(2));
3135   return true;
3136 }
3137
3138 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3139                                               CXXConstructorDecl *Constructor,
3140                                               QualType Type) {
3141   const FunctionProtoType *CtorType =
3142       Constructor->getType()->getAs<FunctionProtoType>();
3143   if (CtorType->getNumParams() > 0) {
3144     QualType FirstArg = CtorType->getParamType(0);
3145     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3146       return true;
3147   }
3148   return false;
3149 }
3150
3151 static OverloadingResult
3152 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3153                                        CXXRecordDecl *To,
3154                                        UserDefinedConversionSequence &User,
3155                                        OverloadCandidateSet &CandidateSet,
3156                                        bool AllowExplicit) {
3157   for (auto *D : S.LookupConstructors(To)) {
3158     auto Info = getConstructorInfo(D);
3159     if (!Info)
3160       continue;
3161
3162     bool Usable = !Info.Constructor->isInvalidDecl() &&
3163                   S.isInitListConstructor(Info.Constructor) &&
3164                   (AllowExplicit || !Info.Constructor->isExplicit());
3165     if (Usable) {
3166       // If the first argument is (a reference to) the target type,
3167       // suppress conversions.
3168       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3169           S.Context, Info.Constructor, ToType);
3170       if (Info.ConstructorTmpl)
3171         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3172                                        /*ExplicitArgs*/ nullptr, From,
3173                                        CandidateSet, SuppressUserConversions);
3174       else
3175         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3176                                CandidateSet, SuppressUserConversions);
3177     }
3178   }
3179
3180   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3181
3182   OverloadCandidateSet::iterator Best;
3183   switch (auto Result =
3184             CandidateSet.BestViableFunction(S, From->getLocStart(),
3185                                             Best, true)) {
3186   case OR_Deleted:
3187   case OR_Success: {
3188     // Record the standard conversion we used and the conversion function.
3189     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3190     QualType ThisType = Constructor->getThisType(S.Context);
3191     // Initializer lists don't have conversions as such.
3192     User.Before.setAsIdentityConversion();
3193     User.HadMultipleCandidates = HadMultipleCandidates;
3194     User.ConversionFunction = Constructor;
3195     User.FoundConversionFunction = Best->FoundDecl;
3196     User.After.setAsIdentityConversion();
3197     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3198     User.After.setAllToTypes(ToType);
3199     return Result;
3200   }
3201
3202   case OR_No_Viable_Function:
3203     return OR_No_Viable_Function;
3204   case OR_Ambiguous:
3205     return OR_Ambiguous;
3206   }
3207
3208   llvm_unreachable("Invalid OverloadResult!");
3209 }
3210
3211 /// Determines whether there is a user-defined conversion sequence
3212 /// (C++ [over.ics.user]) that converts expression From to the type
3213 /// ToType. If such a conversion exists, User will contain the
3214 /// user-defined conversion sequence that performs such a conversion
3215 /// and this routine will return true. Otherwise, this routine returns
3216 /// false and User is unspecified.
3217 ///
3218 /// \param AllowExplicit  true if the conversion should consider C++0x
3219 /// "explicit" conversion functions as well as non-explicit conversion
3220 /// functions (C++0x [class.conv.fct]p2).
3221 ///
3222 /// \param AllowObjCConversionOnExplicit true if the conversion should
3223 /// allow an extra Objective-C pointer conversion on uses of explicit
3224 /// constructors. Requires \c AllowExplicit to also be set.
3225 static OverloadingResult
3226 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3227                         UserDefinedConversionSequence &User,
3228                         OverloadCandidateSet &CandidateSet,
3229                         bool AllowExplicit,
3230                         bool AllowObjCConversionOnExplicit) {
3231   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3232
3233   // Whether we will only visit constructors.
3234   bool ConstructorsOnly = false;
3235
3236   // If the type we are conversion to is a class type, enumerate its
3237   // constructors.
3238   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3239     // C++ [over.match.ctor]p1:
3240     //   When objects of class type are direct-initialized (8.5), or
3241     //   copy-initialized from an expression of the same or a
3242     //   derived class type (8.5), overload resolution selects the
3243     //   constructor. [...] For copy-initialization, the candidate
3244     //   functions are all the converting constructors (12.3.1) of
3245     //   that class. The argument list is the expression-list within
3246     //   the parentheses of the initializer.
3247     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3248         (From->getType()->getAs<RecordType>() &&
3249          S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3250       ConstructorsOnly = true;
3251
3252     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3253       // We're not going to find any constructors.
3254     } else if (CXXRecordDecl *ToRecordDecl
3255                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3256
3257       Expr **Args = &From;
3258       unsigned NumArgs = 1;
3259       bool ListInitializing = false;
3260       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3261         // But first, see if there is an init-list-constructor that will work.
3262         OverloadingResult Result = IsInitializerListConstructorConversion(
3263             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3264         if (Result != OR_No_Viable_Function)
3265           return Result;
3266         // Never mind.
3267         CandidateSet.clear();
3268
3269         // If we're list-initializing, we pass the individual elements as
3270         // arguments, not the entire list.
3271         Args = InitList->getInits();
3272         NumArgs = InitList->getNumInits();
3273         ListInitializing = true;
3274       }
3275
3276       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3277         auto Info = getConstructorInfo(D);
3278         if (!Info)
3279           continue;
3280
3281         bool Usable = !Info.Constructor->isInvalidDecl();
3282         if (ListInitializing)
3283           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3284         else
3285           Usable = Usable &&
3286                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3287         if (Usable) {
3288           bool SuppressUserConversions = !ConstructorsOnly;
3289           if (SuppressUserConversions && ListInitializing) {
3290             SuppressUserConversions = false;
3291             if (NumArgs == 1) {
3292               // If the first argument is (a reference to) the target type,
3293               // suppress conversions.
3294               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3295                   S.Context, Info.Constructor, ToType);
3296             }
3297           }
3298           if (Info.ConstructorTmpl)
3299             S.AddTemplateOverloadCandidate(
3300                 Info.ConstructorTmpl, Info.FoundDecl,
3301                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3302                 CandidateSet, SuppressUserConversions);
3303           else
3304             // Allow one user-defined conversion when user specifies a
3305             // From->ToType conversion via an static cast (c-style, etc).
3306             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3307                                    llvm::makeArrayRef(Args, NumArgs),
3308                                    CandidateSet, SuppressUserConversions);
3309         }
3310       }
3311     }
3312   }
3313
3314   // Enumerate conversion functions, if we're allowed to.
3315   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3316   } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3317     // No conversion functions from incomplete types.
3318   } else if (const RecordType *FromRecordType
3319                                    = From->getType()->getAs<RecordType>()) {
3320     if (CXXRecordDecl *FromRecordDecl
3321          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3322       // Add all of the conversion functions as candidates.
3323       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3324       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3325         DeclAccessPair FoundDecl = I.getPair();
3326         NamedDecl *D = FoundDecl.getDecl();
3327         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3328         if (isa<UsingShadowDecl>(D))
3329           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3330
3331         CXXConversionDecl *Conv;
3332         FunctionTemplateDecl *ConvTemplate;
3333         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3334           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3335         else
3336           Conv = cast<CXXConversionDecl>(D);
3337
3338         if (AllowExplicit || !Conv->isExplicit()) {
3339           if (ConvTemplate)
3340             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3341                                              ActingContext, From, ToType,
3342                                              CandidateSet,
3343                                              AllowObjCConversionOnExplicit);
3344           else
3345             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3346                                      From, ToType, CandidateSet,
3347                                      AllowObjCConversionOnExplicit);
3348         }
3349       }
3350     }
3351   }
3352
3353   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3354
3355   OverloadCandidateSet::iterator Best;
3356   switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3357                                                         Best, true)) {
3358   case OR_Success:
3359   case OR_Deleted:
3360     // Record the standard conversion we used and the conversion function.
3361     if (CXXConstructorDecl *Constructor
3362           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3363       // C++ [over.ics.user]p1:
3364       //   If the user-defined conversion is specified by a
3365       //   constructor (12.3.1), the initial standard conversion
3366       //   sequence converts the source type to the type required by
3367       //   the argument of the constructor.
3368       //
3369       QualType ThisType = Constructor->getThisType(S.Context);
3370       if (isa<InitListExpr>(From)) {
3371         // Initializer lists don't have conversions as such.
3372         User.Before.setAsIdentityConversion();
3373       } else {
3374         if (Best->Conversions[0].isEllipsis())
3375           User.EllipsisConversion = true;
3376         else {
3377           User.Before = Best->Conversions[0].Standard;
3378           User.EllipsisConversion = false;
3379         }
3380       }
3381       User.HadMultipleCandidates = HadMultipleCandidates;
3382       User.ConversionFunction = Constructor;
3383       User.FoundConversionFunction = Best->FoundDecl;
3384       User.After.setAsIdentityConversion();
3385       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3386       User.After.setAllToTypes(ToType);
3387       return Result;
3388     }
3389     if (CXXConversionDecl *Conversion
3390                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3391       // C++ [over.ics.user]p1:
3392       //
3393       //   [...] If the user-defined conversion is specified by a
3394       //   conversion function (12.3.2), the initial standard
3395       //   conversion sequence converts the source type to the
3396       //   implicit object parameter of the conversion function.
3397       User.Before = Best->Conversions[0].Standard;
3398       User.HadMultipleCandidates = HadMultipleCandidates;
3399       User.ConversionFunction = Conversion;
3400       User.FoundConversionFunction = Best->FoundDecl;
3401       User.EllipsisConversion = false;
3402
3403       // C++ [over.ics.user]p2:
3404       //   The second standard conversion sequence converts the
3405       //   result of the user-defined conversion to the target type
3406       //   for the sequence. Since an implicit conversion sequence
3407       //   is an initialization, the special rules for
3408       //   initialization by user-defined conversion apply when
3409       //   selecting the best user-defined conversion for a
3410       //   user-defined conversion sequence (see 13.3.3 and
3411       //   13.3.3.1).
3412       User.After = Best->FinalConversion;
3413       return Result;
3414     }
3415     llvm_unreachable("Not a constructor or conversion function?");
3416
3417   case OR_No_Viable_Function:
3418     return OR_No_Viable_Function;
3419
3420   case OR_Ambiguous:
3421     return OR_Ambiguous;
3422   }
3423
3424   llvm_unreachable("Invalid OverloadResult!");
3425 }
3426
3427 bool
3428 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3429   ImplicitConversionSequence ICS;
3430   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3431                                     OverloadCandidateSet::CSK_Normal);
3432   OverloadingResult OvResult =
3433     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3434                             CandidateSet, false, false);
3435   if (OvResult == OR_Ambiguous)
3436     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3437         << From->getType() << ToType << From->getSourceRange();
3438   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3439     if (!RequireCompleteType(From->getLocStart(), ToType,
3440                              diag::err_typecheck_nonviable_condition_incomplete,
3441                              From->getType(), From->getSourceRange()))
3442       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3443           << false << From->getType() << From->getSourceRange() << ToType;
3444   } else
3445     return false;
3446   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3447   return true;
3448 }
3449
3450 /// \brief Compare the user-defined conversion functions or constructors
3451 /// of two user-defined conversion sequences to determine whether any ordering
3452 /// is possible.
3453 static ImplicitConversionSequence::CompareKind
3454 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3455                            FunctionDecl *Function2) {
3456   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3457     return ImplicitConversionSequence::Indistinguishable;
3458
3459   // Objective-C++:
3460   //   If both conversion functions are implicitly-declared conversions from
3461   //   a lambda closure type to a function pointer and a block pointer,
3462   //   respectively, always prefer the conversion to a function pointer,
3463   //   because the function pointer is more lightweight and is more likely
3464   //   to keep code working.
3465   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3466   if (!Conv1)
3467     return ImplicitConversionSequence::Indistinguishable;
3468
3469   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3470   if (!Conv2)
3471     return ImplicitConversionSequence::Indistinguishable;
3472
3473   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3474     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3475     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3476     if (Block1 != Block2)
3477       return Block1 ? ImplicitConversionSequence::Worse
3478                     : ImplicitConversionSequence::Better;
3479   }
3480
3481   return ImplicitConversionSequence::Indistinguishable;
3482 }
3483
3484 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3485     const ImplicitConversionSequence &ICS) {
3486   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3487          (ICS.isUserDefined() &&
3488           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3489 }
3490
3491 /// CompareImplicitConversionSequences - Compare two implicit
3492 /// conversion sequences to determine whether one is better than the
3493 /// other or if they are indistinguishable (C++ 13.3.3.2).
3494 static ImplicitConversionSequence::CompareKind
3495 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3496                                    const ImplicitConversionSequence& ICS1,
3497                                    const ImplicitConversionSequence& ICS2)
3498 {
3499   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3500   // conversion sequences (as defined in 13.3.3.1)
3501   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3502   //      conversion sequence than a user-defined conversion sequence or
3503   //      an ellipsis conversion sequence, and
3504   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3505   //      conversion sequence than an ellipsis conversion sequence
3506   //      (13.3.3.1.3).
3507   //
3508   // C++0x [over.best.ics]p10:
3509   //   For the purpose of ranking implicit conversion sequences as
3510   //   described in 13.3.3.2, the ambiguous conversion sequence is
3511   //   treated as a user-defined sequence that is indistinguishable
3512   //   from any other user-defined conversion sequence.
3513
3514   // String literal to 'char *' conversion has been deprecated in C++03. It has
3515   // been removed from C++11. We still accept this conversion, if it happens at
3516   // the best viable function. Otherwise, this conversion is considered worse
3517   // than ellipsis conversion. Consider this as an extension; this is not in the
3518   // standard. For example:
3519   //
3520   // int &f(...);    // #1
3521   // void f(char*);  // #2
3522   // void g() { int &r = f("foo"); }
3523   //
3524   // In C++03, we pick #2 as the best viable function.
3525   // In C++11, we pick #1 as the best viable function, because ellipsis
3526   // conversion is better than string-literal to char* conversion (since there
3527   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3528   // convert arguments, #2 would be the best viable function in C++11.
3529   // If the best viable function has this conversion, a warning will be issued
3530   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3531
3532   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3533       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3534       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3535     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3536                ? ImplicitConversionSequence::Worse
3537                : ImplicitConversionSequence::Better;
3538
3539   if (ICS1.getKindRank() < ICS2.getKindRank())
3540     return ImplicitConversionSequence::Better;
3541   if (ICS2.getKindRank() < ICS1.getKindRank())
3542     return ImplicitConversionSequence::Worse;
3543
3544   // The following checks require both conversion sequences to be of
3545   // the same kind.
3546   if (ICS1.getKind() != ICS2.getKind())
3547     return ImplicitConversionSequence::Indistinguishable;
3548
3549   ImplicitConversionSequence::CompareKind Result =
3550       ImplicitConversionSequence::Indistinguishable;
3551
3552   // Two implicit conversion sequences of the same form are
3553   // indistinguishable conversion sequences unless one of the
3554   // following rules apply: (C++ 13.3.3.2p3):
3555
3556   // List-initialization sequence L1 is a better conversion sequence than
3557   // list-initialization sequence L2 if:
3558   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3559   //   if not that,
3560   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3561   //   and N1 is smaller than N2.,
3562   // even if one of the other rules in this paragraph would otherwise apply.
3563   if (!ICS1.isBad()) {
3564     if (ICS1.isStdInitializerListElement() &&
3565         !ICS2.isStdInitializerListElement())
3566       return ImplicitConversionSequence::Better;
3567     if (!ICS1.isStdInitializerListElement() &&
3568         ICS2.isStdInitializerListElement())
3569       return ImplicitConversionSequence::Worse;
3570   }
3571
3572   if (ICS1.isStandard())
3573     // Standard conversion sequence S1 is a better conversion sequence than
3574     // standard conversion sequence S2 if [...]
3575     Result = CompareStandardConversionSequences(S, Loc,
3576                                                 ICS1.Standard, ICS2.Standard);
3577   else if (ICS1.isUserDefined()) {
3578     // User-defined conversion sequence U1 is a better conversion
3579     // sequence than another user-defined conversion sequence U2 if
3580     // they contain the same user-defined conversion function or
3581     // constructor and if the second standard conversion sequence of
3582     // U1 is better than the second standard conversion sequence of
3583     // U2 (C++ 13.3.3.2p3).
3584     if (ICS1.UserDefined.ConversionFunction ==
3585           ICS2.UserDefined.ConversionFunction)
3586       Result = CompareStandardConversionSequences(S, Loc,
3587                                                   ICS1.UserDefined.After,
3588                                                   ICS2.UserDefined.After);
3589     else
3590       Result = compareConversionFunctions(S,
3591                                           ICS1.UserDefined.ConversionFunction,
3592                                           ICS2.UserDefined.ConversionFunction);
3593   }
3594
3595   return Result;
3596 }
3597
3598 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3599   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3600     Qualifiers Quals;
3601     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3602     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3603   }
3604
3605   return Context.hasSameUnqualifiedType(T1, T2);
3606 }
3607
3608 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3609 // determine if one is a proper subset of the other.
3610 static ImplicitConversionSequence::CompareKind
3611 compareStandardConversionSubsets(ASTContext &Context,
3612                                  const StandardConversionSequence& SCS1,
3613                                  const StandardConversionSequence& SCS2) {
3614   ImplicitConversionSequence::CompareKind Result
3615     = ImplicitConversionSequence::Indistinguishable;
3616
3617   // the identity conversion sequence is considered to be a subsequence of
3618   // any non-identity conversion sequence
3619   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3620     return ImplicitConversionSequence::Better;
3621   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3622     return ImplicitConversionSequence::Worse;
3623
3624   if (SCS1.Second != SCS2.Second) {
3625     if (SCS1.Second == ICK_Identity)
3626       Result = ImplicitConversionSequence::Better;
3627     else if (SCS2.Second == ICK_Identity)
3628       Result = ImplicitConversionSequence::Worse;
3629     else
3630       return ImplicitConversionSequence::Indistinguishable;
3631   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3632     return ImplicitConversionSequence::Indistinguishable;
3633
3634   if (SCS1.Third == SCS2.Third) {
3635     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3636                              : ImplicitConversionSequence::Indistinguishable;
3637   }
3638
3639   if (SCS1.Third == ICK_Identity)
3640     return Result == ImplicitConversionSequence::Worse
3641              ? ImplicitConversionSequence::Indistinguishable
3642              : ImplicitConversionSequence::Better;
3643
3644   if (SCS2.Third == ICK_Identity)
3645     return Result == ImplicitConversionSequence::Better
3646              ? ImplicitConversionSequence::Indistinguishable
3647              : ImplicitConversionSequence::Worse;
3648
3649   return ImplicitConversionSequence::Indistinguishable;
3650 }
3651
3652 /// \brief Determine whether one of the given reference bindings is better
3653 /// than the other based on what kind of bindings they are.
3654 static bool
3655 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3656                              const StandardConversionSequence &SCS2) {
3657   // C++0x [over.ics.rank]p3b4:
3658   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3659   //      implicit object parameter of a non-static member function declared
3660   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3661   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3662   //      lvalue reference to a function lvalue and S2 binds an rvalue
3663   //      reference*.
3664   //
3665   // FIXME: Rvalue references. We're going rogue with the above edits,
3666   // because the semantics in the current C++0x working paper (N3225 at the
3667   // time of this writing) break the standard definition of std::forward
3668   // and std::reference_wrapper when dealing with references to functions.
3669   // Proposed wording changes submitted to CWG for consideration.
3670   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3671       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3672     return false;
3673
3674   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3675           SCS2.IsLvalueReference) ||
3676          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3677           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3678 }
3679
3680 /// CompareStandardConversionSequences - Compare two standard
3681 /// conversion sequences to determine whether one is better than the
3682 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3683 static ImplicitConversionSequence::CompareKind
3684 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3685                                    const StandardConversionSequence& SCS1,
3686                                    const StandardConversionSequence& SCS2)
3687 {
3688   // Standard conversion sequence S1 is a better conversion sequence
3689   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3690
3691   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3692   //     sequences in the canonical form defined by 13.3.3.1.1,
3693   //     excluding any Lvalue Transformation; the identity conversion
3694   //     sequence is considered to be a subsequence of any
3695   //     non-identity conversion sequence) or, if not that,
3696   if (ImplicitConversionSequence::CompareKind CK
3697         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3698     return CK;
3699
3700   //  -- the rank of S1 is better than the rank of S2 (by the rules
3701   //     defined below), or, if not that,
3702   ImplicitConversionRank Rank1 = SCS1.getRank();
3703   ImplicitConversionRank Rank2 = SCS2.getRank();
3704   if (Rank1 < Rank2)
3705     return ImplicitConversionSequence::Better;
3706   else if (Rank2 < Rank1)
3707     return ImplicitConversionSequence::Worse;
3708
3709   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3710   // are indistinguishable unless one of the following rules
3711   // applies:
3712
3713   //   A conversion that is not a conversion of a pointer, or
3714   //   pointer to member, to bool is better than another conversion
3715   //   that is such a conversion.
3716   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3717     return SCS2.isPointerConversionToBool()
3718              ? ImplicitConversionSequence::Better
3719              : ImplicitConversionSequence::Worse;
3720
3721   // C++ [over.ics.rank]p4b2:
3722   //
3723   //   If class B is derived directly or indirectly from class A,
3724   //   conversion of B* to A* is better than conversion of B* to
3725   //   void*, and conversion of A* to void* is better than conversion
3726   //   of B* to void*.
3727   bool SCS1ConvertsToVoid
3728     = SCS1.isPointerConversionToVoidPointer(S.Context);
3729   bool SCS2ConvertsToVoid
3730     = SCS2.isPointerConversionToVoidPointer(S.Context);
3731   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3732     // Exactly one of the conversion sequences is a conversion to
3733     // a void pointer; it's the worse conversion.
3734     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3735                               : ImplicitConversionSequence::Worse;
3736   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3737     // Neither conversion sequence converts to a void pointer; compare
3738     // their derived-to-base conversions.
3739     if (ImplicitConversionSequence::CompareKind DerivedCK
3740           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3741       return DerivedCK;
3742   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3743              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3744     // Both conversion sequences are conversions to void
3745     // pointers. Compare the source types to determine if there's an
3746     // inheritance relationship in their sources.
3747     QualType FromType1 = SCS1.getFromType();
3748     QualType FromType2 = SCS2.getFromType();
3749
3750     // Adjust the types we're converting from via the array-to-pointer
3751     // conversion, if we need to.
3752     if (SCS1.First == ICK_Array_To_Pointer)
3753       FromType1 = S.Context.getArrayDecayedType(FromType1);
3754     if (SCS2.First == ICK_Array_To_Pointer)
3755       FromType2 = S.Context.getArrayDecayedType(FromType2);
3756
3757     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3758     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3759
3760     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3761       return ImplicitConversionSequence::Better;
3762     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3763       return ImplicitConversionSequence::Worse;
3764
3765     // Objective-C++: If one interface is more specific than the
3766     // other, it is the better one.
3767     const ObjCObjectPointerType* FromObjCPtr1
3768       = FromType1->getAs<ObjCObjectPointerType>();
3769     const ObjCObjectPointerType* FromObjCPtr2
3770       = FromType2->getAs<ObjCObjectPointerType>();
3771     if (FromObjCPtr1 && FromObjCPtr2) {
3772       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3773                                                           FromObjCPtr2);
3774       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3775                                                            FromObjCPtr1);
3776       if (AssignLeft != AssignRight) {
3777         return AssignLeft? ImplicitConversionSequence::Better
3778                          : ImplicitConversionSequence::Worse;
3779       }
3780     }
3781   }
3782
3783   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3784   // bullet 3).
3785   if (ImplicitConversionSequence::CompareKind QualCK
3786         = CompareQualificationConversions(S, SCS1, SCS2))
3787     return QualCK;
3788
3789   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3790     // Check for a better reference binding based on the kind of bindings.
3791     if (isBetterReferenceBindingKind(SCS1, SCS2))
3792       return ImplicitConversionSequence::Better;
3793     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3794       return ImplicitConversionSequence::Worse;
3795
3796     // C++ [over.ics.rank]p3b4:
3797     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3798     //      which the references refer are the same type except for
3799     //      top-level cv-qualifiers, and the type to which the reference
3800     //      initialized by S2 refers is more cv-qualified than the type
3801     //      to which the reference initialized by S1 refers.
3802     QualType T1 = SCS1.getToType(2);
3803     QualType T2 = SCS2.getToType(2);
3804     T1 = S.Context.getCanonicalType(T1);
3805     T2 = S.Context.getCanonicalType(T2);
3806     Qualifiers T1Quals, T2Quals;
3807     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3808     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3809     if (UnqualT1 == UnqualT2) {
3810       // Objective-C++ ARC: If the references refer to objects with different
3811       // lifetimes, prefer bindings that don't change lifetime.
3812       if (SCS1.ObjCLifetimeConversionBinding !=
3813                                           SCS2.ObjCLifetimeConversionBinding) {
3814         return SCS1.ObjCLifetimeConversionBinding
3815                                            ? ImplicitConversionSequence::Worse
3816                                            : ImplicitConversionSequence::Better;
3817       }
3818
3819       // If the type is an array type, promote the element qualifiers to the
3820       // type for comparison.
3821       if (isa<ArrayType>(T1) && T1Quals)
3822         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3823       if (isa<ArrayType>(T2) && T2Quals)
3824         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3825       if (T2.isMoreQualifiedThan(T1))
3826         return ImplicitConversionSequence::Better;
3827       else if (T1.isMoreQualifiedThan(T2))
3828         return ImplicitConversionSequence::Worse;
3829     }
3830   }
3831
3832   // In Microsoft mode, prefer an integral conversion to a
3833   // floating-to-integral conversion if the integral conversion
3834   // is between types of the same size.
3835   // For example:
3836   // void f(float);
3837   // void f(int);
3838   // int main {
3839   //    long a;
3840   //    f(a);
3841   // }
3842   // Here, MSVC will call f(int) instead of generating a compile error
3843   // as clang will do in standard mode.
3844   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3845       SCS2.Second == ICK_Floating_Integral &&
3846       S.Context.getTypeSize(SCS1.getFromType()) ==
3847           S.Context.getTypeSize(SCS1.getToType(2)))
3848     return ImplicitConversionSequence::Better;
3849
3850   return ImplicitConversionSequence::Indistinguishable;
3851 }
3852
3853 /// CompareQualificationConversions - Compares two standard conversion
3854 /// sequences to determine whether they can be ranked based on their
3855 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3856 static ImplicitConversionSequence::CompareKind
3857 CompareQualificationConversions(Sema &S,
3858                                 const StandardConversionSequence& SCS1,
3859                                 const StandardConversionSequence& SCS2) {
3860   // C++ 13.3.3.2p3:
3861   //  -- S1 and S2 differ only in their qualification conversion and
3862   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3863   //     cv-qualification signature of type T1 is a proper subset of
3864   //     the cv-qualification signature of type T2, and S1 is not the
3865   //     deprecated string literal array-to-pointer conversion (4.2).
3866   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3867       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3868     return ImplicitConversionSequence::Indistinguishable;
3869
3870   // FIXME: the example in the standard doesn't use a qualification
3871   // conversion (!)
3872   QualType T1 = SCS1.getToType(2);
3873   QualType T2 = SCS2.getToType(2);
3874   T1 = S.Context.getCanonicalType(T1);
3875   T2 = S.Context.getCanonicalType(T2);
3876   Qualifiers T1Quals, T2Quals;
3877   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3878   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3879
3880   // If the types are the same, we won't learn anything by unwrapped
3881   // them.
3882   if (UnqualT1 == UnqualT2)
3883     return ImplicitConversionSequence::Indistinguishable;
3884
3885   // If the type is an array type, promote the element qualifiers to the type
3886   // for comparison.
3887   if (isa<ArrayType>(T1) && T1Quals)
3888     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3889   if (isa<ArrayType>(T2) && T2Quals)
3890     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3891
3892   ImplicitConversionSequence::CompareKind Result
3893     = ImplicitConversionSequence::Indistinguishable;
3894
3895   // Objective-C++ ARC:
3896   //   Prefer qualification conversions not involving a change in lifetime
3897   //   to qualification conversions that do not change lifetime.
3898   if (SCS1.QualificationIncludesObjCLifetime !=
3899                                       SCS2.QualificationIncludesObjCLifetime) {
3900     Result = SCS1.QualificationIncludesObjCLifetime
3901                ? ImplicitConversionSequence::Worse
3902                : ImplicitConversionSequence::Better;
3903   }
3904
3905   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3906     // Within each iteration of the loop, we check the qualifiers to
3907     // determine if this still looks like a qualification
3908     // conversion. Then, if all is well, we unwrap one more level of
3909     // pointers or pointers-to-members and do it all again
3910     // until there are no more pointers or pointers-to-members left
3911     // to unwrap. This essentially mimics what
3912     // IsQualificationConversion does, but here we're checking for a
3913     // strict subset of qualifiers.
3914     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3915       // The qualifiers are the same, so this doesn't tell us anything
3916       // about how the sequences rank.
3917       ;
3918     else if (T2.isMoreQualifiedThan(T1)) {
3919       // T1 has fewer qualifiers, so it could be the better sequence.
3920       if (Result == ImplicitConversionSequence::Worse)
3921         // Neither has qualifiers that are a subset of the other's
3922         // qualifiers.
3923         return ImplicitConversionSequence::Indistinguishable;
3924
3925       Result = ImplicitConversionSequence::Better;
3926     } else if (T1.isMoreQualifiedThan(T2)) {
3927       // T2 has fewer qualifiers, so it could be the better sequence.
3928       if (Result == ImplicitConversionSequence::Better)
3929         // Neither has qualifiers that are a subset of the other's
3930         // qualifiers.
3931         return ImplicitConversionSequence::Indistinguishable;
3932
3933       Result = ImplicitConversionSequence::Worse;
3934     } else {
3935       // Qualifiers are disjoint.
3936       return ImplicitConversionSequence::Indistinguishable;
3937     }
3938
3939     // If the types after this point are equivalent, we're done.
3940     if (S.Context.hasSameUnqualifiedType(T1, T2))
3941       break;
3942   }
3943
3944   // Check that the winning standard conversion sequence isn't using
3945   // the deprecated string literal array to pointer conversion.
3946   switch (Result) {
3947   case ImplicitConversionSequence::Better:
3948     if (SCS1.DeprecatedStringLiteralToCharPtr)
3949       Result = ImplicitConversionSequence::Indistinguishable;
3950     break;
3951
3952   case ImplicitConversionSequence::Indistinguishable:
3953     break;
3954
3955   case ImplicitConversionSequence::Worse:
3956     if (SCS2.DeprecatedStringLiteralToCharPtr)
3957       Result = ImplicitConversionSequence::Indistinguishable;
3958     break;
3959   }
3960
3961   return Result;
3962 }
3963
3964 /// CompareDerivedToBaseConversions - Compares two standard conversion
3965 /// sequences to determine whether they can be ranked based on their
3966 /// various kinds of derived-to-base conversions (C++
3967 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3968 /// conversions between Objective-C interface types.
3969 static ImplicitConversionSequence::CompareKind
3970 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3971                                 const StandardConversionSequence& SCS1,
3972                                 const StandardConversionSequence& SCS2) {
3973   QualType FromType1 = SCS1.getFromType();
3974   QualType ToType1 = SCS1.getToType(1);
3975   QualType FromType2 = SCS2.getFromType();
3976   QualType ToType2 = SCS2.getToType(1);
3977
3978   // Adjust the types we're converting from via the array-to-pointer
3979   // conversion, if we need to.
3980   if (SCS1.First == ICK_Array_To_Pointer)
3981     FromType1 = S.Context.getArrayDecayedType(FromType1);
3982   if (SCS2.First == ICK_Array_To_Pointer)
3983     FromType2 = S.Context.getArrayDecayedType(FromType2);
3984
3985   // Canonicalize all of the types.
3986   FromType1 = S.Context.getCanonicalType(FromType1);
3987   ToType1 = S.Context.getCanonicalType(ToType1);
3988   FromType2 = S.Context.getCanonicalType(FromType2);
3989   ToType2 = S.Context.getCanonicalType(ToType2);
3990
3991   // C++ [over.ics.rank]p4b3:
3992   //
3993   //   If class B is derived directly or indirectly from class A and
3994   //   class C is derived directly or indirectly from B,
3995   //
3996   // Compare based on pointer conversions.
3997   if (SCS1.Second == ICK_Pointer_Conversion &&
3998       SCS2.Second == ICK_Pointer_Conversion &&
3999       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4000       FromType1->isPointerType() && FromType2->isPointerType() &&
4001       ToType1->isPointerType() && ToType2->isPointerType()) {
4002     QualType FromPointee1
4003       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4004     QualType ToPointee1
4005       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4006     QualType FromPointee2
4007       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4008     QualType ToPointee2
4009       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4010
4011     //   -- conversion of C* to B* is better than conversion of C* to A*,
4012     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4013       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4014         return ImplicitConversionSequence::Better;
4015       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4016         return ImplicitConversionSequence::Worse;
4017     }
4018
4019     //   -- conversion of B* to A* is better than conversion of C* to A*,
4020     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4021       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4022         return ImplicitConversionSequence::Better;
4023       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4024         return ImplicitConversionSequence::Worse;
4025     }
4026   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4027              SCS2.Second == ICK_Pointer_Conversion) {
4028     const ObjCObjectPointerType *FromPtr1
4029       = FromType1->getAs<ObjCObjectPointerType>();
4030     const ObjCObjectPointerType *FromPtr2
4031       = FromType2->getAs<ObjCObjectPointerType>();
4032     const ObjCObjectPointerType *ToPtr1
4033       = ToType1->getAs<ObjCObjectPointerType>();
4034     const ObjCObjectPointerType *ToPtr2
4035       = ToType2->getAs<ObjCObjectPointerType>();
4036
4037     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4038       // Apply the same conversion ranking rules for Objective-C pointer types
4039       // that we do for C++ pointers to class types. However, we employ the
4040       // Objective-C pseudo-subtyping relationship used for assignment of
4041       // Objective-C pointer types.
4042       bool FromAssignLeft
4043         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4044       bool FromAssignRight
4045         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4046       bool ToAssignLeft
4047         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4048       bool ToAssignRight
4049         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4050
4051       // A conversion to an a non-id object pointer type or qualified 'id'
4052       // type is better than a conversion to 'id'.
4053       if (ToPtr1->isObjCIdType() &&
4054           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4055         return ImplicitConversionSequence::Worse;
4056       if (ToPtr2->isObjCIdType() &&
4057           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4058         return ImplicitConversionSequence::Better;
4059
4060       // A conversion to a non-id object pointer type is better than a
4061       // conversion to a qualified 'id' type
4062       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4063         return ImplicitConversionSequence::Worse;
4064       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4065         return ImplicitConversionSequence::Better;
4066
4067       // A conversion to an a non-Class object pointer type or qualified 'Class'
4068       // type is better than a conversion to 'Class'.
4069       if (ToPtr1->isObjCClassType() &&
4070           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4071         return ImplicitConversionSequence::Worse;
4072       if (ToPtr2->isObjCClassType() &&
4073           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4074         return ImplicitConversionSequence::Better;
4075
4076       // A conversion to a non-Class object pointer type is better than a
4077       // conversion to a qualified 'Class' type.
4078       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4079         return ImplicitConversionSequence::Worse;
4080       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4081         return ImplicitConversionSequence::Better;
4082
4083       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4084       if (S.Context.hasSameType(FromType1, FromType2) &&
4085           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4086           (ToAssignLeft != ToAssignRight)) {
4087         if (FromPtr1->isSpecialized()) {
4088           // "conversion of B<A> * to B * is better than conversion of B * to
4089           // C *.
4090           bool IsFirstSame =
4091               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4092           bool IsSecondSame =
4093               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4094           if (IsFirstSame) {
4095             if (!IsSecondSame)
4096               return ImplicitConversionSequence::Better;
4097           } else if (IsSecondSame)
4098             return ImplicitConversionSequence::Worse;
4099         }
4100         return ToAssignLeft? ImplicitConversionSequence::Worse
4101                            : ImplicitConversionSequence::Better;
4102       }
4103
4104       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4105       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4106           (FromAssignLeft != FromAssignRight))
4107         return FromAssignLeft? ImplicitConversionSequence::Better
4108         : ImplicitConversionSequence::Worse;
4109     }
4110   }
4111
4112   // Ranking of member-pointer types.
4113   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4114       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4115       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4116     const MemberPointerType * FromMemPointer1 =
4117                                         FromType1->getAs<MemberPointerType>();
4118     const MemberPointerType * ToMemPointer1 =
4119                                           ToType1->getAs<MemberPointerType>();
4120     const MemberPointerType * FromMemPointer2 =
4121                                           FromType2->getAs<MemberPointerType>();
4122     const MemberPointerType * ToMemPointer2 =
4123                                           ToType2->getAs<MemberPointerType>();
4124     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4125     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4126     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4127     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4128     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4129     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4130     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4131     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4132     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4133     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4134       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4135         return ImplicitConversionSequence::Worse;
4136       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4137         return ImplicitConversionSequence::Better;
4138     }
4139     // conversion of B::* to C::* is better than conversion of A::* to C::*
4140     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4141       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4142         return ImplicitConversionSequence::Better;
4143       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4144         return ImplicitConversionSequence::Worse;
4145     }
4146   }
4147
4148   if (SCS1.Second == ICK_Derived_To_Base) {
4149     //   -- conversion of C to B is better than conversion of C to A,
4150     //   -- binding of an expression of type C to a reference of type
4151     //      B& is better than binding an expression of type C to a
4152     //      reference of type A&,
4153     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4154         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4155       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4156         return ImplicitConversionSequence::Better;
4157       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4158         return ImplicitConversionSequence::Worse;
4159     }
4160
4161     //   -- conversion of B to A is better than conversion of C to A.
4162     //   -- binding of an expression of type B to a reference of type
4163     //      A& is better than binding an expression of type C to a
4164     //      reference of type A&,
4165     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4166         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4167       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4168         return ImplicitConversionSequence::Better;
4169       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4170         return ImplicitConversionSequence::Worse;
4171     }
4172   }
4173
4174   return ImplicitConversionSequence::Indistinguishable;
4175 }
4176
4177 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4178 /// C++ class.
4179 static bool isTypeValid(QualType T) {
4180   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4181     return !Record->isInvalidDecl();
4182
4183   return true;
4184 }
4185
4186 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4187 /// determine whether they are reference-related,
4188 /// reference-compatible, reference-compatible with added
4189 /// qualification, or incompatible, for use in C++ initialization by
4190 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4191 /// type, and the first type (T1) is the pointee type of the reference
4192 /// type being initialized.
4193 Sema::ReferenceCompareResult
4194 Sema::CompareReferenceRelationship(SourceLocation Loc,
4195                                    QualType OrigT1, QualType OrigT2,
4196                                    bool &DerivedToBase,
4197                                    bool &ObjCConversion,
4198                                    bool &ObjCLifetimeConversion) {
4199   assert(!OrigT1->isReferenceType() &&
4200     "T1 must be the pointee type of the reference type");
4201   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4202
4203   QualType T1 = Context.getCanonicalType(OrigT1);
4204   QualType T2 = Context.getCanonicalType(OrigT2);
4205   Qualifiers T1Quals, T2Quals;
4206   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4207   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4208
4209   // C++ [dcl.init.ref]p4:
4210   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4211   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4212   //   T1 is a base class of T2.
4213   DerivedToBase = false;
4214   ObjCConversion = false;
4215   ObjCLifetimeConversion = false;
4216   QualType ConvertedT2;
4217   if (UnqualT1 == UnqualT2) {
4218     // Nothing to do.
4219   } else if (isCompleteType(Loc, OrigT2) &&
4220              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4221              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4222     DerivedToBase = true;
4223   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4224            UnqualT2->isObjCObjectOrInterfaceType() &&
4225            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4226     ObjCConversion = true;
4227   else if (UnqualT2->isFunctionType() &&
4228            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4229     // C++1z [dcl.init.ref]p4:
4230     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4231     //   function" and T1 is "function"
4232     //
4233     // We extend this to also apply to 'noreturn', so allow any function
4234     // conversion between function types.
4235     return Ref_Compatible;
4236   else
4237     return Ref_Incompatible;
4238
4239   // At this point, we know that T1 and T2 are reference-related (at
4240   // least).
4241
4242   // If the type is an array type, promote the element qualifiers to the type
4243   // for comparison.
4244   if (isa<ArrayType>(T1) && T1Quals)
4245     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4246   if (isa<ArrayType>(T2) && T2Quals)
4247     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4248
4249   // C++ [dcl.init.ref]p4:
4250   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4251   //   reference-related to T2 and cv1 is the same cv-qualification
4252   //   as, or greater cv-qualification than, cv2. For purposes of
4253   //   overload resolution, cases for which cv1 is greater
4254   //   cv-qualification than cv2 are identified as
4255   //   reference-compatible with added qualification (see 13.3.3.2).
4256   //
4257   // Note that we also require equivalence of Objective-C GC and address-space
4258   // qualifiers when performing these computations, so that e.g., an int in
4259   // address space 1 is not reference-compatible with an int in address
4260   // space 2.
4261   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4262       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4263     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4264       ObjCLifetimeConversion = true;
4265
4266     T1Quals.removeObjCLifetime();
4267     T2Quals.removeObjCLifetime();
4268   }
4269
4270   // MS compiler ignores __unaligned qualifier for references; do the same.
4271   T1Quals.removeUnaligned();
4272   T2Quals.removeUnaligned();
4273
4274   if (T1Quals.compatiblyIncludes(T2Quals))
4275     return Ref_Compatible;
4276   else
4277     return Ref_Related;
4278 }
4279
4280 /// \brief Look for a user-defined conversion to a value reference-compatible
4281 ///        with DeclType. Return true if something definite is found.
4282 static bool
4283 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4284                          QualType DeclType, SourceLocation DeclLoc,
4285                          Expr *Init, QualType T2, bool AllowRvalues,
4286                          bool AllowExplicit) {
4287   assert(T2->isRecordType() && "Can only find conversions of record types.");
4288   CXXRecordDecl *T2RecordDecl
4289     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4290
4291   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4292   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4293   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4294     NamedDecl *D = *I;
4295     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4296     if (isa<UsingShadowDecl>(D))
4297       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4298
4299     FunctionTemplateDecl *ConvTemplate
4300       = dyn_cast<FunctionTemplateDecl>(D);
4301     CXXConversionDecl *Conv;
4302     if (ConvTemplate)
4303       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4304     else
4305       Conv = cast<CXXConversionDecl>(D);
4306
4307     // If this is an explicit conversion, and we're not allowed to consider
4308     // explicit conversions, skip it.
4309     if (!AllowExplicit && Conv->isExplicit())
4310       continue;
4311
4312     if (AllowRvalues) {
4313       bool DerivedToBase = false;
4314       bool ObjCConversion = false;
4315       bool ObjCLifetimeConversion = false;
4316
4317       // If we are initializing an rvalue reference, don't permit conversion
4318       // functions that return lvalues.
4319       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4320         const ReferenceType *RefType
4321           = Conv->getConversionType()->getAs<LValueReferenceType>();
4322         if (RefType && !RefType->getPointeeType()->isFunctionType())
4323           continue;
4324       }
4325
4326       if (!ConvTemplate &&
4327           S.CompareReferenceRelationship(
4328             DeclLoc,
4329             Conv->getConversionType().getNonReferenceType()
4330               .getUnqualifiedType(),
4331             DeclType.getNonReferenceType().getUnqualifiedType(),
4332             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4333           Sema::Ref_Incompatible)
4334         continue;
4335     } else {
4336       // If the conversion function doesn't return a reference type,
4337       // it can't be considered for this conversion. An rvalue reference
4338       // is only acceptable if its referencee is a function type.
4339
4340       const ReferenceType *RefType =
4341         Conv->getConversionType()->getAs<ReferenceType>();
4342       if (!RefType ||
4343           (!RefType->isLValueReferenceType() &&
4344            !RefType->getPointeeType()->isFunctionType()))
4345         continue;
4346     }
4347
4348     if (ConvTemplate)
4349       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4350                                        Init, DeclType, CandidateSet,
4351                                        /*AllowObjCConversionOnExplicit=*/false);
4352     else
4353       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4354                                DeclType, CandidateSet,
4355                                /*AllowObjCConversionOnExplicit=*/false);
4356   }
4357
4358   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4359
4360   OverloadCandidateSet::iterator Best;
4361   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4362   case OR_Success:
4363     // C++ [over.ics.ref]p1:
4364     //
4365     //   [...] If the parameter binds directly to the result of
4366     //   applying a conversion function to the argument
4367     //   expression, the implicit conversion sequence is a
4368     //   user-defined conversion sequence (13.3.3.1.2), with the
4369     //   second standard conversion sequence either an identity
4370     //   conversion or, if the conversion function returns an
4371     //   entity of a type that is a derived class of the parameter
4372     //   type, a derived-to-base Conversion.
4373     if (!Best->FinalConversion.DirectBinding)
4374       return false;
4375
4376     ICS.setUserDefined();
4377     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4378     ICS.UserDefined.After = Best->FinalConversion;
4379     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4380     ICS.UserDefined.ConversionFunction = Best->Function;
4381     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4382     ICS.UserDefined.EllipsisConversion = false;
4383     assert(ICS.UserDefined.After.ReferenceBinding &&
4384            ICS.UserDefined.After.DirectBinding &&
4385            "Expected a direct reference binding!");
4386     return true;
4387
4388   case OR_Ambiguous:
4389     ICS.setAmbiguous();
4390     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4391          Cand != CandidateSet.end(); ++Cand)
4392       if (Cand->Viable)
4393         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4394     return true;
4395
4396   case OR_No_Viable_Function:
4397   case OR_Deleted:
4398     // There was no suitable conversion, or we found a deleted
4399     // conversion; continue with other checks.
4400     return false;
4401   }
4402
4403   llvm_unreachable("Invalid OverloadResult!");
4404 }
4405
4406 /// \brief Compute an implicit conversion sequence for reference
4407 /// initialization.
4408 static ImplicitConversionSequence
4409 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4410                  SourceLocation DeclLoc,
4411                  bool SuppressUserConversions,
4412                  bool AllowExplicit) {
4413   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4414
4415   // Most paths end in a failed conversion.
4416   ImplicitConversionSequence ICS;
4417   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4418
4419   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4420   QualType T2 = Init->getType();
4421
4422   // If the initializer is the address of an overloaded function, try
4423   // to resolve the overloaded function. If all goes well, T2 is the
4424   // type of the resulting function.
4425   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4426     DeclAccessPair Found;
4427     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4428                                                                 false, Found))
4429       T2 = Fn->getType();
4430   }
4431
4432   // Compute some basic properties of the types and the initializer.
4433   bool isRValRef = DeclType->isRValueReferenceType();
4434   bool DerivedToBase = false;
4435   bool ObjCConversion = false;
4436   bool ObjCLifetimeConversion = false;
4437   Expr::Classification InitCategory = Init->Classify(S.Context);
4438   Sema::ReferenceCompareResult RefRelationship
4439     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4440                                      ObjCConversion, ObjCLifetimeConversion);
4441
4442
4443   // C++0x [dcl.init.ref]p5:
4444   //   A reference to type "cv1 T1" is initialized by an expression
4445   //   of type "cv2 T2" as follows:
4446
4447   //     -- If reference is an lvalue reference and the initializer expression
4448   if (!isRValRef) {
4449     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4450     //        reference-compatible with "cv2 T2," or
4451     //
4452     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4453     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4454       // C++ [over.ics.ref]p1:
4455       //   When a parameter of reference type binds directly (8.5.3)
4456       //   to an argument expression, the implicit conversion sequence
4457       //   is the identity conversion, unless the argument expression
4458       //   has a type that is a derived class of the parameter type,
4459       //   in which case the implicit conversion sequence is a
4460       //   derived-to-base Conversion (13.3.3.1).
4461       ICS.setStandard();
4462       ICS.Standard.First = ICK_Identity;
4463       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4464                          : ObjCConversion? ICK_Compatible_Conversion
4465                          : ICK_Identity;
4466       ICS.Standard.Third = ICK_Identity;
4467       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4468       ICS.Standard.setToType(0, T2);
4469       ICS.Standard.setToType(1, T1);
4470       ICS.Standard.setToType(2, T1);
4471       ICS.Standard.ReferenceBinding = true;
4472       ICS.Standard.DirectBinding = true;
4473       ICS.Standard.IsLvalueReference = !isRValRef;
4474       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4475       ICS.Standard.BindsToRvalue = false;
4476       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4477       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4478       ICS.Standard.CopyConstructor = nullptr;
4479       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4480
4481       // Nothing more to do: the inaccessibility/ambiguity check for
4482       // derived-to-base conversions is suppressed when we're
4483       // computing the implicit conversion sequence (C++
4484       // [over.best.ics]p2).
4485       return ICS;
4486     }
4487
4488     //       -- has a class type (i.e., T2 is a class type), where T1 is
4489     //          not reference-related to T2, and can be implicitly
4490     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4491     //          is reference-compatible with "cv3 T3" 92) (this
4492     //          conversion is selected by enumerating the applicable
4493     //          conversion functions (13.3.1.6) and choosing the best
4494     //          one through overload resolution (13.3)),
4495     if (!SuppressUserConversions && T2->isRecordType() &&
4496         S.isCompleteType(DeclLoc, T2) &&
4497         RefRelationship == Sema::Ref_Incompatible) {
4498       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4499                                    Init, T2, /*AllowRvalues=*/false,
4500                                    AllowExplicit))
4501         return ICS;
4502     }
4503   }
4504
4505   //     -- Otherwise, the reference shall be an lvalue reference to a
4506   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4507   //        shall be an rvalue reference.
4508   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4509     return ICS;
4510
4511   //       -- If the initializer expression
4512   //
4513   //            -- is an xvalue, class prvalue, array prvalue or function
4514   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4515   if (RefRelationship == Sema::Ref_Compatible &&
4516       (InitCategory.isXValue() ||
4517        (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4518        (InitCategory.isLValue() && T2->isFunctionType()))) {
4519     ICS.setStandard();
4520     ICS.Standard.First = ICK_Identity;
4521     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4522                       : ObjCConversion? ICK_Compatible_Conversion
4523                       : ICK_Identity;
4524     ICS.Standard.Third = ICK_Identity;
4525     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4526     ICS.Standard.setToType(0, T2);
4527     ICS.Standard.setToType(1, T1);
4528     ICS.Standard.setToType(2, T1);
4529     ICS.Standard.ReferenceBinding = true;
4530     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4531     // binding unless we're binding to a class prvalue.
4532     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4533     // allow the use of rvalue references in C++98/03 for the benefit of
4534     // standard library implementors; therefore, we need the xvalue check here.
4535     ICS.Standard.DirectBinding =
4536       S.getLangOpts().CPlusPlus11 ||
4537       !(InitCategory.isPRValue() || T2->isRecordType());
4538     ICS.Standard.IsLvalueReference = !isRValRef;
4539     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4540     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4541     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4542     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4543     ICS.Standard.CopyConstructor = nullptr;
4544     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4545     return ICS;
4546   }
4547
4548   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4549   //               reference-related to T2, and can be implicitly converted to
4550   //               an xvalue, class prvalue, or function lvalue of type
4551   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4552   //               "cv3 T3",
4553   //
4554   //          then the reference is bound to the value of the initializer
4555   //          expression in the first case and to the result of the conversion
4556   //          in the second case (or, in either case, to an appropriate base
4557   //          class subobject).
4558   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4559       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4560       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4561                                Init, T2, /*AllowRvalues=*/true,
4562                                AllowExplicit)) {
4563     // In the second case, if the reference is an rvalue reference
4564     // and the second standard conversion sequence of the
4565     // user-defined conversion sequence includes an lvalue-to-rvalue
4566     // conversion, the program is ill-formed.
4567     if (ICS.isUserDefined() && isRValRef &&
4568         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4569       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4570
4571     return ICS;
4572   }
4573
4574   // A temporary of function type cannot be created; don't even try.
4575   if (T1->isFunctionType())
4576     return ICS;
4577
4578   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4579   //          initialized from the initializer expression using the
4580   //          rules for a non-reference copy initialization (8.5). The
4581   //          reference is then bound to the temporary. If T1 is
4582   //          reference-related to T2, cv1 must be the same
4583   //          cv-qualification as, or greater cv-qualification than,
4584   //          cv2; otherwise, the program is ill-formed.
4585   if (RefRelationship == Sema::Ref_Related) {
4586     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4587     // we would be reference-compatible or reference-compatible with
4588     // added qualification. But that wasn't the case, so the reference
4589     // initialization fails.
4590     //
4591     // Note that we only want to check address spaces and cvr-qualifiers here.
4592     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4593     Qualifiers T1Quals = T1.getQualifiers();
4594     Qualifiers T2Quals = T2.getQualifiers();
4595     T1Quals.removeObjCGCAttr();
4596     T1Quals.removeObjCLifetime();
4597     T2Quals.removeObjCGCAttr();
4598     T2Quals.removeObjCLifetime();
4599     // MS compiler ignores __unaligned qualifier for references; do the same.
4600     T1Quals.removeUnaligned();
4601     T2Quals.removeUnaligned();
4602     if (!T1Quals.compatiblyIncludes(T2Quals))
4603       return ICS;
4604   }
4605
4606   // If at least one of the types is a class type, the types are not
4607   // related, and we aren't allowed any user conversions, the
4608   // reference binding fails. This case is important for breaking
4609   // recursion, since TryImplicitConversion below will attempt to
4610   // create a temporary through the use of a copy constructor.
4611   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4612       (T1->isRecordType() || T2->isRecordType()))
4613     return ICS;
4614
4615   // If T1 is reference-related to T2 and the reference is an rvalue
4616   // reference, the initializer expression shall not be an lvalue.
4617   if (RefRelationship >= Sema::Ref_Related &&
4618       isRValRef && Init->Classify(S.Context).isLValue())
4619     return ICS;
4620
4621   // C++ [over.ics.ref]p2:
4622   //   When a parameter of reference type is not bound directly to
4623   //   an argument expression, the conversion sequence is the one
4624   //   required to convert the argument expression to the
4625   //   underlying type of the reference according to
4626   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4627   //   to copy-initializing a temporary of the underlying type with
4628   //   the argument expression. Any difference in top-level
4629   //   cv-qualification is subsumed by the initialization itself
4630   //   and does not constitute a conversion.
4631   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4632                               /*AllowExplicit=*/false,
4633                               /*InOverloadResolution=*/false,
4634                               /*CStyle=*/false,
4635                               /*AllowObjCWritebackConversion=*/false,
4636                               /*AllowObjCConversionOnExplicit=*/false);
4637
4638   // Of course, that's still a reference binding.
4639   if (ICS.isStandard()) {
4640     ICS.Standard.ReferenceBinding = true;
4641     ICS.Standard.IsLvalueReference = !isRValRef;
4642     ICS.Standard.BindsToFunctionLvalue = false;
4643     ICS.Standard.BindsToRvalue = true;
4644     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4645     ICS.Standard.ObjCLifetimeConversionBinding = false;
4646   } else if (ICS.isUserDefined()) {
4647     const ReferenceType *LValRefType =
4648         ICS.UserDefined.ConversionFunction->getReturnType()
4649             ->getAs<LValueReferenceType>();
4650
4651     // C++ [over.ics.ref]p3:
4652     //   Except for an implicit object parameter, for which see 13.3.1, a
4653     //   standard conversion sequence cannot be formed if it requires [...]
4654     //   binding an rvalue reference to an lvalue other than a function
4655     //   lvalue.
4656     // Note that the function case is not possible here.
4657     if (DeclType->isRValueReferenceType() && LValRefType) {
4658       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4659       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4660       // reference to an rvalue!
4661       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4662       return ICS;
4663     }
4664
4665     ICS.UserDefined.After.ReferenceBinding = true;
4666     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4667     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4668     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4669     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4670     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4671   }
4672
4673   return ICS;
4674 }
4675
4676 static ImplicitConversionSequence
4677 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4678                       bool SuppressUserConversions,
4679                       bool InOverloadResolution,
4680                       bool AllowObjCWritebackConversion,
4681                       bool AllowExplicit = false);
4682
4683 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4684 /// initializer list From.
4685 static ImplicitConversionSequence
4686 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4687                   bool SuppressUserConversions,
4688                   bool InOverloadResolution,
4689                   bool AllowObjCWritebackConversion) {
4690   // C++11 [over.ics.list]p1:
4691   //   When an argument is an initializer list, it is not an expression and
4692   //   special rules apply for converting it to a parameter type.
4693
4694   ImplicitConversionSequence Result;
4695   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4696
4697   // We need a complete type for what follows. Incomplete types can never be
4698   // initialized from init lists.
4699   if (!S.isCompleteType(From->getLocStart(), ToType))
4700     return Result;
4701
4702   // Per DR1467:
4703   //   If the parameter type is a class X and the initializer list has a single
4704   //   element of type cv U, where U is X or a class derived from X, the
4705   //   implicit conversion sequence is the one required to convert the element
4706   //   to the parameter type.
4707   //
4708   //   Otherwise, if the parameter type is a character array [... ]
4709   //   and the initializer list has a single element that is an
4710   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4711   //   implicit conversion sequence is the identity conversion.
4712   if (From->getNumInits() == 1) {
4713     if (ToType->isRecordType()) {
4714       QualType InitType = From->getInit(0)->getType();
4715       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4716           S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4717         return TryCopyInitialization(S, From->getInit(0), ToType,
4718                                      SuppressUserConversions,
4719                                      InOverloadResolution,
4720                                      AllowObjCWritebackConversion);
4721     }
4722     // FIXME: Check the other conditions here: array of character type,
4723     // initializer is a string literal.
4724     if (ToType->isArrayType()) {
4725       InitializedEntity Entity =
4726         InitializedEntity::InitializeParameter(S.Context, ToType,
4727                                                /*Consumed=*/false);
4728       if (S.CanPerformCopyInitialization(Entity, From)) {
4729         Result.setStandard();
4730         Result.Standard.setAsIdentityConversion();
4731         Result.Standard.setFromType(ToType);
4732         Result.Standard.setAllToTypes(ToType);
4733         return Result;
4734       }
4735     }
4736   }
4737
4738   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4739   // C++11 [over.ics.list]p2:
4740   //   If the parameter type is std::initializer_list<X> or "array of X" and
4741   //   all the elements can be implicitly converted to X, the implicit
4742   //   conversion sequence is the worst conversion necessary to convert an
4743   //   element of the list to X.
4744   //
4745   // C++14 [over.ics.list]p3:
4746   //   Otherwise, if the parameter type is "array of N X", if the initializer
4747   //   list has exactly N elements or if it has fewer than N elements and X is
4748   //   default-constructible, and if all the elements of the initializer list
4749   //   can be implicitly converted to X, the implicit conversion sequence is
4750   //   the worst conversion necessary to convert an element of the list to X.
4751   //
4752   // FIXME: We're missing a lot of these checks.
4753   bool toStdInitializerList = false;
4754   QualType X;
4755   if (ToType->isArrayType())
4756     X = S.Context.getAsArrayType(ToType)->getElementType();
4757   else
4758     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4759   if (!X.isNull()) {
4760     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4761       Expr *Init = From->getInit(i);
4762       ImplicitConversionSequence ICS =
4763           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4764                                 InOverloadResolution,
4765                                 AllowObjCWritebackConversion);
4766       // If a single element isn't convertible, fail.
4767       if (ICS.isBad()) {
4768         Result = ICS;
4769         break;
4770       }
4771       // Otherwise, look for the worst conversion.
4772       if (Result.isBad() ||
4773           CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4774                                              Result) ==
4775               ImplicitConversionSequence::Worse)
4776         Result = ICS;
4777     }
4778
4779     // For an empty list, we won't have computed any conversion sequence.
4780     // Introduce the identity conversion sequence.
4781     if (From->getNumInits() == 0) {
4782       Result.setStandard();
4783       Result.Standard.setAsIdentityConversion();
4784       Result.Standard.setFromType(ToType);
4785       Result.Standard.setAllToTypes(ToType);
4786     }
4787
4788     Result.setStdInitializerListElement(toStdInitializerList);
4789     return Result;
4790   }
4791
4792   // C++14 [over.ics.list]p4:
4793   // C++11 [over.ics.list]p3:
4794   //   Otherwise, if the parameter is a non-aggregate class X and overload
4795   //   resolution chooses a single best constructor [...] the implicit
4796   //   conversion sequence is a user-defined conversion sequence. If multiple
4797   //   constructors are viable but none is better than the others, the
4798   //   implicit conversion sequence is a user-defined conversion sequence.
4799   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4800     // This function can deal with initializer lists.
4801     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4802                                     /*AllowExplicit=*/false,
4803                                     InOverloadResolution, /*CStyle=*/false,
4804                                     AllowObjCWritebackConversion,
4805                                     /*AllowObjCConversionOnExplicit=*/false);
4806   }
4807
4808   // C++14 [over.ics.list]p5:
4809   // C++11 [over.ics.list]p4:
4810   //   Otherwise, if the parameter has an aggregate type which can be
4811   //   initialized from the initializer list [...] the implicit conversion
4812   //   sequence is a user-defined conversion sequence.
4813   if (ToType->isAggregateType()) {
4814     // Type is an aggregate, argument is an init list. At this point it comes
4815     // down to checking whether the initialization works.
4816     // FIXME: Find out whether this parameter is consumed or not.
4817     // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4818     // need to call into the initialization code here; overload resolution
4819     // should not be doing that.
4820     InitializedEntity Entity =
4821         InitializedEntity::InitializeParameter(S.Context, ToType,
4822                                                /*Consumed=*/false);
4823     if (S.CanPerformCopyInitialization(Entity, From)) {
4824       Result.setUserDefined();
4825       Result.UserDefined.Before.setAsIdentityConversion();
4826       // Initializer lists don't have a type.
4827       Result.UserDefined.Before.setFromType(QualType());
4828       Result.UserDefined.Before.setAllToTypes(QualType());
4829
4830       Result.UserDefined.After.setAsIdentityConversion();
4831       Result.UserDefined.After.setFromType(ToType);
4832       Result.UserDefined.After.setAllToTypes(ToType);
4833       Result.UserDefined.ConversionFunction = nullptr;
4834     }
4835     return Result;
4836   }
4837
4838   // C++14 [over.ics.list]p6:
4839   // C++11 [over.ics.list]p5:
4840   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4841   if (ToType->isReferenceType()) {
4842     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4843     // mention initializer lists in any way. So we go by what list-
4844     // initialization would do and try to extrapolate from that.
4845
4846     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4847
4848     // If the initializer list has a single element that is reference-related
4849     // to the parameter type, we initialize the reference from that.
4850     if (From->getNumInits() == 1) {
4851       Expr *Init = From->getInit(0);
4852
4853       QualType T2 = Init->getType();
4854
4855       // If the initializer is the address of an overloaded function, try
4856       // to resolve the overloaded function. If all goes well, T2 is the
4857       // type of the resulting function.
4858       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4859         DeclAccessPair Found;
4860         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4861                                    Init, ToType, false, Found))
4862           T2 = Fn->getType();
4863       }
4864
4865       // Compute some basic properties of the types and the initializer.
4866       bool dummy1 = false;
4867       bool dummy2 = false;
4868       bool dummy3 = false;
4869       Sema::ReferenceCompareResult RefRelationship
4870         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4871                                          dummy2, dummy3);
4872
4873       if (RefRelationship >= Sema::Ref_Related) {
4874         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4875                                 SuppressUserConversions,
4876                                 /*AllowExplicit=*/false);
4877       }
4878     }
4879
4880     // Otherwise, we bind the reference to a temporary created from the
4881     // initializer list.
4882     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4883                                InOverloadResolution,
4884                                AllowObjCWritebackConversion);
4885     if (Result.isFailure())
4886       return Result;
4887     assert(!Result.isEllipsis() &&
4888            "Sub-initialization cannot result in ellipsis conversion.");
4889
4890     // Can we even bind to a temporary?
4891     if (ToType->isRValueReferenceType() ||
4892         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4893       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4894                                             Result.UserDefined.After;
4895       SCS.ReferenceBinding = true;
4896       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4897       SCS.BindsToRvalue = true;
4898       SCS.BindsToFunctionLvalue = false;
4899       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4900       SCS.ObjCLifetimeConversionBinding = false;
4901     } else
4902       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4903                     From, ToType);
4904     return Result;
4905   }
4906
4907   // C++14 [over.ics.list]p7:
4908   // C++11 [over.ics.list]p6:
4909   //   Otherwise, if the parameter type is not a class:
4910   if (!ToType->isRecordType()) {
4911     //    - if the initializer list has one element that is not itself an
4912     //      initializer list, the implicit conversion sequence is the one
4913     //      required to convert the element to the parameter type.
4914     unsigned NumInits = From->getNumInits();
4915     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4916       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4917                                      SuppressUserConversions,
4918                                      InOverloadResolution,
4919                                      AllowObjCWritebackConversion);
4920     //    - if the initializer list has no elements, the implicit conversion
4921     //      sequence is the identity conversion.
4922     else if (NumInits == 0) {
4923       Result.setStandard();
4924       Result.Standard.setAsIdentityConversion();
4925       Result.Standard.setFromType(ToType);
4926       Result.Standard.setAllToTypes(ToType);
4927     }
4928     return Result;
4929   }
4930
4931   // C++14 [over.ics.list]p8:
4932   // C++11 [over.ics.list]p7:
4933   //   In all cases other than those enumerated above, no conversion is possible
4934   return Result;
4935 }
4936
4937 /// TryCopyInitialization - Try to copy-initialize a value of type
4938 /// ToType from the expression From. Return the implicit conversion
4939 /// sequence required to pass this argument, which may be a bad
4940 /// conversion sequence (meaning that the argument cannot be passed to
4941 /// a parameter of this type). If @p SuppressUserConversions, then we
4942 /// do not permit any user-defined conversion sequences.
4943 static ImplicitConversionSequence
4944 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4945                       bool SuppressUserConversions,
4946                       bool InOverloadResolution,
4947                       bool AllowObjCWritebackConversion,
4948                       bool AllowExplicit) {
4949   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4950     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4951                              InOverloadResolution,AllowObjCWritebackConversion);
4952
4953   if (ToType->isReferenceType())
4954     return TryReferenceInit(S, From, ToType,
4955                             /*FIXME:*/From->getLocStart(),
4956                             SuppressUserConversions,
4957                             AllowExplicit);
4958
4959   return TryImplicitConversion(S, From, ToType,
4960                                SuppressUserConversions,
4961                                /*AllowExplicit=*/false,
4962                                InOverloadResolution,
4963                                /*CStyle=*/false,
4964                                AllowObjCWritebackConversion,
4965                                /*AllowObjCConversionOnExplicit=*/false);
4966 }
4967
4968 static bool TryCopyInitialization(const CanQualType FromQTy,
4969                                   const CanQualType ToQTy,
4970                                   Sema &S,
4971                                   SourceLocation Loc,
4972                                   ExprValueKind FromVK) {
4973   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4974   ImplicitConversionSequence ICS =
4975     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4976
4977   return !ICS.isBad();
4978 }
4979
4980 /// TryObjectArgumentInitialization - Try to initialize the object
4981 /// parameter of the given member function (@c Method) from the
4982 /// expression @p From.
4983 static ImplicitConversionSequence
4984 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4985                                 Expr::Classification FromClassification,
4986                                 CXXMethodDecl *Method,
4987                                 CXXRecordDecl *ActingContext) {
4988   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4989   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4990   //                 const volatile object.
4991   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4992     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4993   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4994
4995   // Set up the conversion sequence as a "bad" conversion, to allow us
4996   // to exit early.
4997   ImplicitConversionSequence ICS;
4998
4999   // We need to have an object of class type.
5000   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5001     FromType = PT->getPointeeType();
5002
5003     // When we had a pointer, it's implicitly dereferenced, so we
5004     // better have an lvalue.
5005     assert(FromClassification.isLValue());
5006   }
5007
5008   assert(FromType->isRecordType());
5009
5010   // C++0x [over.match.funcs]p4:
5011   //   For non-static member functions, the type of the implicit object
5012   //   parameter is
5013   //
5014   //     - "lvalue reference to cv X" for functions declared without a
5015   //        ref-qualifier or with the & ref-qualifier
5016   //     - "rvalue reference to cv X" for functions declared with the &&
5017   //        ref-qualifier
5018   //
5019   // where X is the class of which the function is a member and cv is the
5020   // cv-qualification on the member function declaration.
5021   //
5022   // However, when finding an implicit conversion sequence for the argument, we
5023   // are not allowed to perform user-defined conversions
5024   // (C++ [over.match.funcs]p5). We perform a simplified version of
5025   // reference binding here, that allows class rvalues to bind to
5026   // non-constant references.
5027
5028   // First check the qualifiers.
5029   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5030   if (ImplicitParamType.getCVRQualifiers()
5031                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5032       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5033     ICS.setBad(BadConversionSequence::bad_qualifiers,
5034                FromType, ImplicitParamType);
5035     return ICS;
5036   }
5037
5038   // Check that we have either the same type or a derived type. It
5039   // affects the conversion rank.
5040   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5041   ImplicitConversionKind SecondKind;
5042   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5043     SecondKind = ICK_Identity;
5044   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5045     SecondKind = ICK_Derived_To_Base;
5046   else {
5047     ICS.setBad(BadConversionSequence::unrelated_class,
5048                FromType, ImplicitParamType);
5049     return ICS;
5050   }
5051
5052   // Check the ref-qualifier.
5053   switch (Method->getRefQualifier()) {
5054   case RQ_None:
5055     // Do nothing; we don't care about lvalueness or rvalueness.
5056     break;
5057
5058   case RQ_LValue:
5059     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5060       // non-const lvalue reference cannot bind to an rvalue
5061       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5062                  ImplicitParamType);
5063       return ICS;
5064     }
5065     break;
5066
5067   case RQ_RValue:
5068     if (!FromClassification.isRValue()) {
5069       // rvalue reference cannot bind to an lvalue
5070       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5071                  ImplicitParamType);
5072       return ICS;
5073     }
5074     break;
5075   }
5076
5077   // Success. Mark this as a reference binding.
5078   ICS.setStandard();
5079   ICS.Standard.setAsIdentityConversion();
5080   ICS.Standard.Second = SecondKind;
5081   ICS.Standard.setFromType(FromType);
5082   ICS.Standard.setAllToTypes(ImplicitParamType);
5083   ICS.Standard.ReferenceBinding = true;
5084   ICS.Standard.DirectBinding = true;
5085   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5086   ICS.Standard.BindsToFunctionLvalue = false;
5087   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5088   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5089     = (Method->getRefQualifier() == RQ_None);
5090   return ICS;
5091 }
5092
5093 /// PerformObjectArgumentInitialization - Perform initialization of
5094 /// the implicit object parameter for the given Method with the given
5095 /// expression.
5096 ExprResult
5097 Sema::PerformObjectArgumentInitialization(Expr *From,
5098                                           NestedNameSpecifier *Qualifier,
5099                                           NamedDecl *FoundDecl,
5100                                           CXXMethodDecl *Method) {
5101   QualType FromRecordType, DestType;
5102   QualType ImplicitParamRecordType  =
5103     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5104
5105   Expr::Classification FromClassification;
5106   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5107     FromRecordType = PT->getPointeeType();
5108     DestType = Method->getThisType(Context);
5109     FromClassification = Expr::Classification::makeSimpleLValue();
5110   } else {
5111     FromRecordType = From->getType();
5112     DestType = ImplicitParamRecordType;
5113     FromClassification = From->Classify(Context);
5114   }
5115
5116   // Note that we always use the true parent context when performing
5117   // the actual argument initialization.
5118   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5119       *this, From->getLocStart(), From->getType(), FromClassification, Method,
5120       Method->getParent());
5121   if (ICS.isBad()) {
5122     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5123       Qualifiers FromQs = FromRecordType.getQualifiers();
5124       Qualifiers ToQs = DestType.getQualifiers();
5125       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5126       if (CVR) {
5127         Diag(From->getLocStart(),
5128              diag::err_member_function_call_bad_cvr)
5129           << Method->getDeclName() << FromRecordType << (CVR - 1)
5130           << From->getSourceRange();
5131         Diag(Method->getLocation(), diag::note_previous_decl)
5132           << Method->getDeclName();
5133         return ExprError();
5134       }
5135     }
5136
5137     return Diag(From->getLocStart(),
5138                 diag::err_implicit_object_parameter_init)
5139        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5140   }
5141
5142   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5143     ExprResult FromRes =
5144       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5145     if (FromRes.isInvalid())
5146       return ExprError();
5147     From = FromRes.get();
5148   }
5149
5150   if (!Context.hasSameType(From->getType(), DestType))
5151     From = ImpCastExprToType(From, DestType, CK_NoOp,
5152                              From->getValueKind()).get();
5153   return From;
5154 }
5155
5156 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5157 /// expression From to bool (C++0x [conv]p3).
5158 static ImplicitConversionSequence
5159 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5160   return TryImplicitConversion(S, From, S.Context.BoolTy,
5161                                /*SuppressUserConversions=*/false,
5162                                /*AllowExplicit=*/true,
5163                                /*InOverloadResolution=*/false,
5164                                /*CStyle=*/false,
5165                                /*AllowObjCWritebackConversion=*/false,
5166                                /*AllowObjCConversionOnExplicit=*/false);
5167 }
5168
5169 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5170 /// of the expression From to bool (C++0x [conv]p3).
5171 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5172   if (checkPlaceholderForOverload(*this, From))
5173     return ExprError();
5174
5175   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5176   if (!ICS.isBad())
5177     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5178
5179   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5180     return Diag(From->getLocStart(),
5181                 diag::err_typecheck_bool_condition)
5182                   << From->getType() << From->getSourceRange();
5183   return ExprError();
5184 }
5185
5186 /// Check that the specified conversion is permitted in a converted constant
5187 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5188 /// is acceptable.
5189 static bool CheckConvertedConstantConversions(Sema &S,
5190                                               StandardConversionSequence &SCS) {
5191   // Since we know that the target type is an integral or unscoped enumeration
5192   // type, most conversion kinds are impossible. All possible First and Third
5193   // conversions are fine.
5194   switch (SCS.Second) {
5195   case ICK_Identity:
5196   case ICK_Function_Conversion:
5197   case ICK_Integral_Promotion:
5198   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5199   case ICK_Zero_Queue_Conversion:
5200     return true;
5201
5202   case ICK_Boolean_Conversion:
5203     // Conversion from an integral or unscoped enumeration type to bool is
5204     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5205     // conversion, so we allow it in a converted constant expression.
5206     //
5207     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5208     // a lot of popular code. We should at least add a warning for this
5209     // (non-conforming) extension.
5210     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5211            SCS.getToType(2)->isBooleanType();
5212
5213   case ICK_Pointer_Conversion:
5214   case ICK_Pointer_Member:
5215     // C++1z: null pointer conversions and null member pointer conversions are
5216     // only permitted if the source type is std::nullptr_t.
5217     return SCS.getFromType()->isNullPtrType();
5218
5219   case ICK_Floating_Promotion:
5220   case ICK_Complex_Promotion:
5221   case ICK_Floating_Conversion:
5222   case ICK_Complex_Conversion:
5223   case ICK_Floating_Integral:
5224   case ICK_Compatible_Conversion:
5225   case ICK_Derived_To_Base:
5226   case ICK_Vector_Conversion:
5227   case ICK_Vector_Splat:
5228   case ICK_Complex_Real:
5229   case ICK_Block_Pointer_Conversion:
5230   case ICK_TransparentUnionConversion:
5231   case ICK_Writeback_Conversion:
5232   case ICK_Zero_Event_Conversion:
5233   case ICK_C_Only_Conversion:
5234   case ICK_Incompatible_Pointer_Conversion:
5235     return false;
5236
5237   case ICK_Lvalue_To_Rvalue:
5238   case ICK_Array_To_Pointer:
5239   case ICK_Function_To_Pointer:
5240     llvm_unreachable("found a first conversion kind in Second");
5241
5242   case ICK_Qualification:
5243     llvm_unreachable("found a third conversion kind in Second");
5244
5245   case ICK_Num_Conversion_Kinds:
5246     break;
5247   }
5248
5249   llvm_unreachable("unknown conversion kind");
5250 }
5251
5252 /// CheckConvertedConstantExpression - Check that the expression From is a
5253 /// converted constant expression of type T, perform the conversion and produce
5254 /// the converted expression, per C++11 [expr.const]p3.
5255 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5256                                                    QualType T, APValue &Value,
5257                                                    Sema::CCEKind CCE,
5258                                                    bool RequireInt) {
5259   assert(S.getLangOpts().CPlusPlus11 &&
5260          "converted constant expression outside C++11");
5261
5262   if (checkPlaceholderForOverload(S, From))
5263     return ExprError();
5264
5265   // C++1z [expr.const]p3:
5266   //  A converted constant expression of type T is an expression,
5267   //  implicitly converted to type T, where the converted
5268   //  expression is a constant expression and the implicit conversion
5269   //  sequence contains only [... list of conversions ...].
5270   // C++1z [stmt.if]p2:
5271   //  If the if statement is of the form if constexpr, the value of the
5272   //  condition shall be a contextually converted constant expression of type
5273   //  bool.
5274   ImplicitConversionSequence ICS =
5275       CCE == Sema::CCEK_ConstexprIf
5276           ? TryContextuallyConvertToBool(S, From)
5277           : TryCopyInitialization(S, From, T,
5278                                   /*SuppressUserConversions=*/false,
5279                                   /*InOverloadResolution=*/false,
5280                                   /*AllowObjcWritebackConversion=*/false,
5281                                   /*AllowExplicit=*/false);
5282   StandardConversionSequence *SCS = nullptr;
5283   switch (ICS.getKind()) {
5284   case ImplicitConversionSequence::StandardConversion:
5285     SCS = &ICS.Standard;
5286     break;
5287   case ImplicitConversionSequence::UserDefinedConversion:
5288     // We are converting to a non-class type, so the Before sequence
5289     // must be trivial.
5290     SCS = &ICS.UserDefined.After;
5291     break;
5292   case ImplicitConversionSequence::AmbiguousConversion:
5293   case ImplicitConversionSequence::BadConversion:
5294     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5295       return S.Diag(From->getLocStart(),
5296                     diag::err_typecheck_converted_constant_expression)
5297                 << From->getType() << From->getSourceRange() << T;
5298     return ExprError();
5299
5300   case ImplicitConversionSequence::EllipsisConversion:
5301     llvm_unreachable("ellipsis conversion in converted constant expression");
5302   }
5303
5304   // Check that we would only use permitted conversions.
5305   if (!CheckConvertedConstantConversions(S, *SCS)) {
5306     return S.Diag(From->getLocStart(),
5307                   diag::err_typecheck_converted_constant_expression_disallowed)
5308              << From->getType() << From->getSourceRange() << T;
5309   }
5310   // [...] and where the reference binding (if any) binds directly.
5311   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5312     return S.Diag(From->getLocStart(),
5313                   diag::err_typecheck_converted_constant_expression_indirect)
5314              << From->getType() << From->getSourceRange() << T;
5315   }
5316
5317   ExprResult Result =
5318       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5319   if (Result.isInvalid())
5320     return Result;
5321
5322   // Check for a narrowing implicit conversion.
5323   APValue PreNarrowingValue;
5324   QualType PreNarrowingType;
5325   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5326                                 PreNarrowingType)) {
5327   case NK_Dependent_Narrowing:
5328     // Implicit conversion to a narrower type, but the expression is
5329     // value-dependent so we can't tell whether it's actually narrowing.
5330   case NK_Variable_Narrowing:
5331     // Implicit conversion to a narrower type, and the value is not a constant
5332     // expression. We'll diagnose this in a moment.
5333   case NK_Not_Narrowing:
5334     break;
5335
5336   case NK_Constant_Narrowing:
5337     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5338       << CCE << /*Constant*/1
5339       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5340     break;
5341
5342   case NK_Type_Narrowing:
5343     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5344       << CCE << /*Constant*/0 << From->getType() << T;
5345     break;
5346   }
5347
5348   if (Result.get()->isValueDependent()) {
5349     Value = APValue();
5350     return Result;
5351   }
5352
5353   // Check the expression is a constant expression.
5354   SmallVector<PartialDiagnosticAt, 8> Notes;
5355   Expr::EvalResult Eval;
5356   Eval.Diag = &Notes;
5357
5358   if ((T->isReferenceType()
5359            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5360            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5361       (RequireInt && !Eval.Val.isInt())) {
5362     // The expression can't be folded, so we can't keep it at this position in
5363     // the AST.
5364     Result = ExprError();
5365   } else {
5366     Value = Eval.Val;
5367
5368     if (Notes.empty()) {
5369       // It's a constant expression.
5370       return Result;
5371     }
5372   }
5373
5374   // It's not a constant expression. Produce an appropriate diagnostic.
5375   if (Notes.size() == 1 &&
5376       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5377     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5378   else {
5379     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5380       << CCE << From->getSourceRange();
5381     for (unsigned I = 0; I < Notes.size(); ++I)
5382       S.Diag(Notes[I].first, Notes[I].second);
5383   }
5384   return ExprError();
5385 }
5386
5387 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5388                                                   APValue &Value, CCEKind CCE) {
5389   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5390 }
5391
5392 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5393                                                   llvm::APSInt &Value,
5394                                                   CCEKind CCE) {
5395   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5396
5397   APValue V;
5398   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5399   if (!R.isInvalid() && !R.get()->isValueDependent())
5400     Value = V.getInt();
5401   return R;
5402 }
5403
5404
5405 /// dropPointerConversions - If the given standard conversion sequence
5406 /// involves any pointer conversions, remove them.  This may change
5407 /// the result type of the conversion sequence.
5408 static void dropPointerConversion(StandardConversionSequence &SCS) {
5409   if (SCS.Second == ICK_Pointer_Conversion) {
5410     SCS.Second = ICK_Identity;
5411     SCS.Third = ICK_Identity;
5412     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5413   }
5414 }
5415
5416 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5417 /// convert the expression From to an Objective-C pointer type.
5418 static ImplicitConversionSequence
5419 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5420   // Do an implicit conversion to 'id'.
5421   QualType Ty = S.Context.getObjCIdType();
5422   ImplicitConversionSequence ICS
5423     = TryImplicitConversion(S, From, Ty,
5424                             // FIXME: Are these flags correct?
5425                             /*SuppressUserConversions=*/false,
5426                             /*AllowExplicit=*/true,
5427                             /*InOverloadResolution=*/false,
5428                             /*CStyle=*/false,
5429                             /*AllowObjCWritebackConversion=*/false,
5430                             /*AllowObjCConversionOnExplicit=*/true);
5431
5432   // Strip off any final conversions to 'id'.
5433   switch (ICS.getKind()) {
5434   case ImplicitConversionSequence::BadConversion:
5435   case ImplicitConversionSequence::AmbiguousConversion:
5436   case ImplicitConversionSequence::EllipsisConversion:
5437     break;
5438
5439   case ImplicitConversionSequence::UserDefinedConversion:
5440     dropPointerConversion(ICS.UserDefined.After);
5441     break;
5442
5443   case ImplicitConversionSequence::StandardConversion:
5444     dropPointerConversion(ICS.Standard);
5445     break;
5446   }
5447
5448   return ICS;
5449 }
5450
5451 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5452 /// conversion of the expression From to an Objective-C pointer type.
5453 /// Returns a valid but null ExprResult if no conversion sequence exists.
5454 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5455   if (checkPlaceholderForOverload(*this, From))
5456     return ExprError();
5457
5458   QualType Ty = Context.getObjCIdType();
5459   ImplicitConversionSequence ICS =
5460     TryContextuallyConvertToObjCPointer(*this, From);
5461   if (!ICS.isBad())
5462     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5463   return ExprResult();
5464 }
5465
5466 /// Determine whether the provided type is an integral type, or an enumeration
5467 /// type of a permitted flavor.
5468 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5469   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5470                                  : T->isIntegralOrUnscopedEnumerationType();
5471 }
5472
5473 static ExprResult
5474 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5475                             Sema::ContextualImplicitConverter &Converter,
5476                             QualType T, UnresolvedSetImpl &ViableConversions) {
5477
5478   if (Converter.Suppress)
5479     return ExprError();
5480
5481   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5482   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5483     CXXConversionDecl *Conv =
5484         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5485     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5486     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5487   }
5488   return From;
5489 }
5490
5491 static bool
5492 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5493                            Sema::ContextualImplicitConverter &Converter,
5494                            QualType T, bool HadMultipleCandidates,
5495                            UnresolvedSetImpl &ExplicitConversions) {
5496   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5497     DeclAccessPair Found = ExplicitConversions[0];
5498     CXXConversionDecl *Conversion =
5499         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5500
5501     // The user probably meant to invoke the given explicit
5502     // conversion; use it.
5503     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5504     std::string TypeStr;
5505     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5506
5507     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5508         << FixItHint::CreateInsertion(From->getLocStart(),
5509                                       "static_cast<" + TypeStr + ">(")
5510         << FixItHint::CreateInsertion(
5511                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5512     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5513
5514     // If we aren't in a SFINAE context, build a call to the
5515     // explicit conversion function.
5516     if (SemaRef.isSFINAEContext())
5517       return true;
5518
5519     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5520     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5521                                                        HadMultipleCandidates);
5522     if (Result.isInvalid())
5523       return true;
5524     // Record usage of conversion in an implicit cast.
5525     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5526                                     CK_UserDefinedConversion, Result.get(),
5527                                     nullptr, Result.get()->getValueKind());
5528   }
5529   return false;
5530 }
5531
5532 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5533                              Sema::ContextualImplicitConverter &Converter,
5534                              QualType T, bool HadMultipleCandidates,
5535                              DeclAccessPair &Found) {
5536   CXXConversionDecl *Conversion =
5537       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5538   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5539
5540   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5541   if (!Converter.SuppressConversion) {
5542     if (SemaRef.isSFINAEContext())
5543       return true;
5544
5545     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5546         << From->getSourceRange();
5547   }
5548
5549   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5550                                                      HadMultipleCandidates);
5551   if (Result.isInvalid())
5552     return true;
5553   // Record usage of conversion in an implicit cast.
5554   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5555                                   CK_UserDefinedConversion, Result.get(),
5556                                   nullptr, Result.get()->getValueKind());
5557   return false;
5558 }
5559
5560 static ExprResult finishContextualImplicitConversion(
5561     Sema &SemaRef, SourceLocation Loc, Expr *From,
5562     Sema::ContextualImplicitConverter &Converter) {
5563   if (!Converter.match(From->getType()) && !Converter.Suppress)
5564     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5565         << From->getSourceRange();
5566
5567   return SemaRef.DefaultLvalueConversion(From);
5568 }
5569
5570 static void
5571 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5572                                   UnresolvedSetImpl &ViableConversions,
5573                                   OverloadCandidateSet &CandidateSet) {
5574   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5575     DeclAccessPair FoundDecl = ViableConversions[I];
5576     NamedDecl *D = FoundDecl.getDecl();
5577     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5578     if (isa<UsingShadowDecl>(D))
5579       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5580
5581     CXXConversionDecl *Conv;
5582     FunctionTemplateDecl *ConvTemplate;
5583     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5584       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5585     else
5586       Conv = cast<CXXConversionDecl>(D);
5587
5588     if (ConvTemplate)
5589       SemaRef.AddTemplateConversionCandidate(
5590         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5591         /*AllowObjCConversionOnExplicit=*/false);
5592     else
5593       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5594                                      ToType, CandidateSet,
5595                                      /*AllowObjCConversionOnExplicit=*/false);
5596   }
5597 }
5598
5599 /// \brief Attempt to convert the given expression to a type which is accepted
5600 /// by the given converter.
5601 ///
5602 /// This routine will attempt to convert an expression of class type to a
5603 /// type accepted by the specified converter. In C++11 and before, the class
5604 /// must have a single non-explicit conversion function converting to a matching
5605 /// type. In C++1y, there can be multiple such conversion functions, but only
5606 /// one target type.
5607 ///
5608 /// \param Loc The source location of the construct that requires the
5609 /// conversion.
5610 ///
5611 /// \param From The expression we're converting from.
5612 ///
5613 /// \param Converter Used to control and diagnose the conversion process.
5614 ///
5615 /// \returns The expression, converted to an integral or enumeration type if
5616 /// successful.
5617 ExprResult Sema::PerformContextualImplicitConversion(
5618     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5619   // We can't perform any more checking for type-dependent expressions.
5620   if (From->isTypeDependent())
5621     return From;
5622
5623   // Process placeholders immediately.
5624   if (From->hasPlaceholderType()) {
5625     ExprResult result = CheckPlaceholderExpr(From);
5626     if (result.isInvalid())
5627       return result;
5628     From = result.get();
5629   }
5630
5631   // If the expression already has a matching type, we're golden.
5632   QualType T = From->getType();
5633   if (Converter.match(T))
5634     return DefaultLvalueConversion(From);
5635
5636   // FIXME: Check for missing '()' if T is a function type?
5637
5638   // We can only perform contextual implicit conversions on objects of class
5639   // type.
5640   const RecordType *RecordTy = T->getAs<RecordType>();
5641   if (!RecordTy || !getLangOpts().CPlusPlus) {
5642     if (!Converter.Suppress)
5643       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5644     return From;
5645   }
5646
5647   // We must have a complete class type.
5648   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5649     ContextualImplicitConverter &Converter;
5650     Expr *From;
5651
5652     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5653         : Converter(Converter), From(From) {}
5654
5655     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5656       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5657     }
5658   } IncompleteDiagnoser(Converter, From);
5659
5660   if (Converter.Suppress ? !isCompleteType(Loc, T)
5661                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5662     return From;
5663
5664   // Look for a conversion to an integral or enumeration type.
5665   UnresolvedSet<4>
5666       ViableConversions; // These are *potentially* viable in C++1y.
5667   UnresolvedSet<4> ExplicitConversions;
5668   const auto &Conversions =
5669       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5670
5671   bool HadMultipleCandidates =
5672       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5673
5674   // To check that there is only one target type, in C++1y:
5675   QualType ToType;
5676   bool HasUniqueTargetType = true;
5677
5678   // Collect explicit or viable (potentially in C++1y) conversions.
5679   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5680     NamedDecl *D = (*I)->getUnderlyingDecl();
5681     CXXConversionDecl *Conversion;
5682     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5683     if (ConvTemplate) {
5684       if (getLangOpts().CPlusPlus14)
5685         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5686       else
5687         continue; // C++11 does not consider conversion operator templates(?).
5688     } else
5689       Conversion = cast<CXXConversionDecl>(D);
5690
5691     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5692            "Conversion operator templates are considered potentially "
5693            "viable in C++1y");
5694
5695     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5696     if (Converter.match(CurToType) || ConvTemplate) {
5697
5698       if (Conversion->isExplicit()) {
5699         // FIXME: For C++1y, do we need this restriction?
5700         // cf. diagnoseNoViableConversion()
5701         if (!ConvTemplate)
5702           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5703       } else {
5704         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5705           if (ToType.isNull())
5706             ToType = CurToType.getUnqualifiedType();
5707           else if (HasUniqueTargetType &&
5708                    (CurToType.getUnqualifiedType() != ToType))
5709             HasUniqueTargetType = false;
5710         }
5711         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5712       }
5713     }
5714   }
5715
5716   if (getLangOpts().CPlusPlus14) {
5717     // C++1y [conv]p6:
5718     // ... An expression e of class type E appearing in such a context
5719     // is said to be contextually implicitly converted to a specified
5720     // type T and is well-formed if and only if e can be implicitly
5721     // converted to a type T that is determined as follows: E is searched
5722     // for conversion functions whose return type is cv T or reference to
5723     // cv T such that T is allowed by the context. There shall be
5724     // exactly one such T.
5725
5726     // If no unique T is found:
5727     if (ToType.isNull()) {
5728       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5729                                      HadMultipleCandidates,
5730                                      ExplicitConversions))
5731         return ExprError();
5732       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5733     }
5734
5735     // If more than one unique Ts are found:
5736     if (!HasUniqueTargetType)
5737       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5738                                          ViableConversions);
5739
5740     // If one unique T is found:
5741     // First, build a candidate set from the previously recorded
5742     // potentially viable conversions.
5743     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5744     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5745                                       CandidateSet);
5746
5747     // Then, perform overload resolution over the candidate set.
5748     OverloadCandidateSet::iterator Best;
5749     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5750     case OR_Success: {
5751       // Apply this conversion.
5752       DeclAccessPair Found =
5753           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5754       if (recordConversion(*this, Loc, From, Converter, T,
5755                            HadMultipleCandidates, Found))
5756         return ExprError();
5757       break;
5758     }
5759     case OR_Ambiguous:
5760       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5761                                          ViableConversions);
5762     case OR_No_Viable_Function:
5763       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5764                                      HadMultipleCandidates,
5765                                      ExplicitConversions))
5766         return ExprError();
5767     // fall through 'OR_Deleted' case.
5768     case OR_Deleted:
5769       // We'll complain below about a non-integral condition type.
5770       break;
5771     }
5772   } else {
5773     switch (ViableConversions.size()) {
5774     case 0: {
5775       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5776                                      HadMultipleCandidates,
5777                                      ExplicitConversions))
5778         return ExprError();
5779
5780       // We'll complain below about a non-integral condition type.
5781       break;
5782     }
5783     case 1: {
5784       // Apply this conversion.
5785       DeclAccessPair Found = ViableConversions[0];
5786       if (recordConversion(*this, Loc, From, Converter, T,
5787                            HadMultipleCandidates, Found))
5788         return ExprError();
5789       break;
5790     }
5791     default:
5792       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5793                                          ViableConversions);
5794     }
5795   }
5796
5797   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5798 }
5799
5800 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5801 /// an acceptable non-member overloaded operator for a call whose
5802 /// arguments have types T1 (and, if non-empty, T2). This routine
5803 /// implements the check in C++ [over.match.oper]p3b2 concerning
5804 /// enumeration types.
5805 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5806                                                    FunctionDecl *Fn,
5807                                                    ArrayRef<Expr *> Args) {
5808   QualType T1 = Args[0]->getType();
5809   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5810
5811   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5812     return true;
5813
5814   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5815     return true;
5816
5817   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5818   if (Proto->getNumParams() < 1)
5819     return false;
5820
5821   if (T1->isEnumeralType()) {
5822     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5823     if (Context.hasSameUnqualifiedType(T1, ArgType))
5824       return true;
5825   }
5826
5827   if (Proto->getNumParams() < 2)
5828     return false;
5829
5830   if (!T2.isNull() && T2->isEnumeralType()) {
5831     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5832     if (Context.hasSameUnqualifiedType(T2, ArgType))
5833       return true;
5834   }
5835
5836   return false;
5837 }
5838
5839 /// AddOverloadCandidate - Adds the given function to the set of
5840 /// candidate functions, using the given function call arguments.  If
5841 /// @p SuppressUserConversions, then don't allow user-defined
5842 /// conversions via constructors or conversion operators.
5843 ///
5844 /// \param PartialOverloading true if we are performing "partial" overloading
5845 /// based on an incomplete set of function arguments. This feature is used by
5846 /// code completion.
5847 void
5848 Sema::AddOverloadCandidate(FunctionDecl *Function,
5849                            DeclAccessPair FoundDecl,
5850                            ArrayRef<Expr *> Args,
5851                            OverloadCandidateSet &CandidateSet,
5852                            bool SuppressUserConversions,
5853                            bool PartialOverloading,
5854                            bool AllowExplicit,
5855                            ConversionSequenceList EarlyConversions) {
5856   const FunctionProtoType *Proto
5857     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5858   assert(Proto && "Functions without a prototype cannot be overloaded");
5859   assert(!Function->getDescribedFunctionTemplate() &&
5860          "Use AddTemplateOverloadCandidate for function templates");
5861
5862   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5863     if (!isa<CXXConstructorDecl>(Method)) {
5864       // If we get here, it's because we're calling a member function
5865       // that is named without a member access expression (e.g.,
5866       // "this->f") that was either written explicitly or created
5867       // implicitly. This can happen with a qualified call to a member
5868       // function, e.g., X::f(). We use an empty type for the implied
5869       // object argument (C++ [over.call.func]p3), and the acting context
5870       // is irrelevant.
5871       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5872                          Expr::Classification::makeSimpleLValue(), Args,
5873                          CandidateSet, SuppressUserConversions,
5874                          PartialOverloading, EarlyConversions);
5875       return;
5876     }
5877     // We treat a constructor like a non-member function, since its object
5878     // argument doesn't participate in overload resolution.
5879   }
5880
5881   if (!CandidateSet.isNewCandidate(Function))
5882     return;
5883
5884   // C++ [over.match.oper]p3:
5885   //   if no operand has a class type, only those non-member functions in the
5886   //   lookup set that have a first parameter of type T1 or "reference to
5887   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5888   //   is a right operand) a second parameter of type T2 or "reference to
5889   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5890   //   candidate functions.
5891   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5892       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5893     return;
5894
5895   // C++11 [class.copy]p11: [DR1402]
5896   //   A defaulted move constructor that is defined as deleted is ignored by
5897   //   overload resolution.
5898   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5899   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5900       Constructor->isMoveConstructor())
5901     return;
5902
5903   // Overload resolution is always an unevaluated context.
5904   EnterExpressionEvaluationContext Unevaluated(
5905       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5906
5907   // Add this candidate
5908   OverloadCandidate &Candidate =
5909       CandidateSet.addCandidate(Args.size(), EarlyConversions);
5910   Candidate.FoundDecl = FoundDecl;
5911   Candidate.Function = Function;
5912   Candidate.Viable = true;
5913   Candidate.IsSurrogate = false;
5914   Candidate.IgnoreObjectArgument = false;
5915   Candidate.ExplicitCallArguments = Args.size();
5916
5917   if (Constructor) {
5918     // C++ [class.copy]p3:
5919     //   A member function template is never instantiated to perform the copy
5920     //   of a class object to an object of its class type.
5921     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5922     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5923         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5924          IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5925                        ClassType))) {
5926       Candidate.Viable = false;
5927       Candidate.FailureKind = ovl_fail_illegal_constructor;
5928       return;
5929     }
5930
5931     // C++ [over.match.funcs]p8: (proposed DR resolution)
5932     //   A constructor inherited from class type C that has a first parameter
5933     //   of type "reference to P" (including such a constructor instantiated
5934     //   from a template) is excluded from the set of candidate functions when
5935     //   constructing an object of type cv D if the argument list has exactly
5936     //   one argument and D is reference-related to P and P is reference-related
5937     //   to C.
5938     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5939     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5940         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5941       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5942       QualType C = Context.getRecordType(Constructor->getParent());
5943       QualType D = Context.getRecordType(Shadow->getParent());
5944       SourceLocation Loc = Args.front()->getExprLoc();
5945       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5946           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5947         Candidate.Viable = false;
5948         Candidate.FailureKind = ovl_fail_inhctor_slice;
5949         return;
5950       }
5951     }
5952   }
5953
5954   unsigned NumParams = Proto->getNumParams();
5955
5956   // (C++ 13.3.2p2): A candidate function having fewer than m
5957   // parameters is viable only if it has an ellipsis in its parameter
5958   // list (8.3.5).
5959   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5960       !Proto->isVariadic()) {
5961     Candidate.Viable = false;
5962     Candidate.FailureKind = ovl_fail_too_many_arguments;
5963     return;
5964   }
5965
5966   // (C++ 13.3.2p2): A candidate function having more than m parameters
5967   // is viable only if the (m+1)st parameter has a default argument
5968   // (8.3.6). For the purposes of overload resolution, the
5969   // parameter list is truncated on the right, so that there are
5970   // exactly m parameters.
5971   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5972   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5973     // Not enough arguments.
5974     Candidate.Viable = false;
5975     Candidate.FailureKind = ovl_fail_too_few_arguments;
5976     return;
5977   }
5978
5979   // (CUDA B.1): Check for invalid calls between targets.
5980   if (getLangOpts().CUDA)
5981     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5982       // Skip the check for callers that are implicit members, because in this
5983       // case we may not yet know what the member's target is; the target is
5984       // inferred for the member automatically, based on the bases and fields of
5985       // the class.
5986       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5987         Candidate.Viable = false;
5988         Candidate.FailureKind = ovl_fail_bad_target;
5989         return;
5990       }
5991
5992   // Determine the implicit conversion sequences for each of the
5993   // arguments.
5994   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5995     if (Candidate.Conversions[ArgIdx].isInitialized()) {
5996       // We already formed a conversion sequence for this parameter during
5997       // template argument deduction.
5998     } else if (ArgIdx < NumParams) {
5999       // (C++ 13.3.2p3): for F to be a viable function, there shall
6000       // exist for each argument an implicit conversion sequence
6001       // (13.3.3.1) that converts that argument to the corresponding
6002       // parameter of F.
6003       QualType ParamType = Proto->getParamType(ArgIdx);
6004       Candidate.Conversions[ArgIdx]
6005         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6006                                 SuppressUserConversions,
6007                                 /*InOverloadResolution=*/true,
6008                                 /*AllowObjCWritebackConversion=*/
6009                                   getLangOpts().ObjCAutoRefCount,
6010                                 AllowExplicit);
6011       if (Candidate.Conversions[ArgIdx].isBad()) {
6012         Candidate.Viable = false;
6013         Candidate.FailureKind = ovl_fail_bad_conversion;
6014         return;
6015       }
6016     } else {
6017       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6018       // argument for which there is no corresponding parameter is
6019       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6020       Candidate.Conversions[ArgIdx].setEllipsis();
6021     }
6022   }
6023
6024   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6025     Candidate.Viable = false;
6026     Candidate.FailureKind = ovl_fail_enable_if;
6027     Candidate.DeductionFailure.Data = FailedAttr;
6028     return;
6029   }
6030
6031   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6032     Candidate.Viable = false;
6033     Candidate.FailureKind = ovl_fail_ext_disabled;
6034     return;
6035   }
6036 }
6037
6038 ObjCMethodDecl *
6039 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6040                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6041   if (Methods.size() <= 1)
6042     return nullptr;
6043
6044   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6045     bool Match = true;
6046     ObjCMethodDecl *Method = Methods[b];
6047     unsigned NumNamedArgs = Sel.getNumArgs();
6048     // Method might have more arguments than selector indicates. This is due
6049     // to addition of c-style arguments in method.
6050     if (Method->param_size() > NumNamedArgs)
6051       NumNamedArgs = Method->param_size();
6052     if (Args.size() < NumNamedArgs)
6053       continue;
6054
6055     for (unsigned i = 0; i < NumNamedArgs; i++) {
6056       // We can't do any type-checking on a type-dependent argument.
6057       if (Args[i]->isTypeDependent()) {
6058         Match = false;
6059         break;
6060       }
6061
6062       ParmVarDecl *param = Method->parameters()[i];
6063       Expr *argExpr = Args[i];
6064       assert(argExpr && "SelectBestMethod(): missing expression");
6065
6066       // Strip the unbridged-cast placeholder expression off unless it's
6067       // a consumed argument.
6068       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6069           !param->hasAttr<CFConsumedAttr>())
6070         argExpr = stripARCUnbridgedCast(argExpr);
6071
6072       // If the parameter is __unknown_anytype, move on to the next method.
6073       if (param->getType() == Context.UnknownAnyTy) {
6074         Match = false;
6075         break;
6076       }
6077
6078       ImplicitConversionSequence ConversionState
6079         = TryCopyInitialization(*this, argExpr, param->getType(),
6080                                 /*SuppressUserConversions*/false,
6081                                 /*InOverloadResolution=*/true,
6082                                 /*AllowObjCWritebackConversion=*/
6083                                 getLangOpts().ObjCAutoRefCount,
6084                                 /*AllowExplicit*/false);
6085       // This function looks for a reasonably-exact match, so we consider
6086       // incompatible pointer conversions to be a failure here.
6087       if (ConversionState.isBad() ||
6088           (ConversionState.isStandard() &&
6089            ConversionState.Standard.Second ==
6090                ICK_Incompatible_Pointer_Conversion)) {
6091         Match = false;
6092         break;
6093       }
6094     }
6095     // Promote additional arguments to variadic methods.
6096     if (Match && Method->isVariadic()) {
6097       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6098         if (Args[i]->isTypeDependent()) {
6099           Match = false;
6100           break;
6101         }
6102         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6103                                                           nullptr);
6104         if (Arg.isInvalid()) {
6105           Match = false;
6106           break;
6107         }
6108       }
6109     } else {
6110       // Check for extra arguments to non-variadic methods.
6111       if (Args.size() != NumNamedArgs)
6112         Match = false;
6113       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6114         // Special case when selectors have no argument. In this case, select
6115         // one with the most general result type of 'id'.
6116         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6117           QualType ReturnT = Methods[b]->getReturnType();
6118           if (ReturnT->isObjCIdType())
6119             return Methods[b];
6120         }
6121       }
6122     }
6123
6124     if (Match)
6125       return Method;
6126   }
6127   return nullptr;
6128 }
6129
6130 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6131 // enable_if is order-sensitive. As a result, we need to reverse things
6132 // sometimes. Size of 4 elements is arbitrary.
6133 static SmallVector<EnableIfAttr *, 4>
6134 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6135   SmallVector<EnableIfAttr *, 4> Result;
6136   if (!Function->hasAttrs())
6137     return Result;
6138
6139   const auto &FuncAttrs = Function->getAttrs();
6140   for (Attr *Attr : FuncAttrs)
6141     if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6142       Result.push_back(EnableIf);
6143
6144   std::reverse(Result.begin(), Result.end());
6145   return Result;
6146 }
6147
6148 static bool
6149 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6150                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6151                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6152                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6153   if (ThisArg) {
6154     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6155     assert(!isa<CXXConstructorDecl>(Method) &&
6156            "Shouldn't have `this` for ctors!");
6157     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6158     ExprResult R = S.PerformObjectArgumentInitialization(
6159         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6160     if (R.isInvalid())
6161       return false;
6162     ConvertedThis = R.get();
6163   } else {
6164     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6165       (void)MD;
6166       assert((MissingImplicitThis || MD->isStatic() ||
6167               isa<CXXConstructorDecl>(MD)) &&
6168              "Expected `this` for non-ctor instance methods");
6169     }
6170     ConvertedThis = nullptr;
6171   }
6172
6173   // Ignore any variadic arguments. Converting them is pointless, since the
6174   // user can't refer to them in the function condition.
6175   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6176
6177   // Convert the arguments.
6178   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6179     ExprResult R;
6180     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6181                                         S.Context, Function->getParamDecl(I)),
6182                                     SourceLocation(), Args[I]);
6183
6184     if (R.isInvalid())
6185       return false;
6186
6187     ConvertedArgs.push_back(R.get());
6188   }
6189
6190   if (Trap.hasErrorOccurred())
6191     return false;
6192
6193   // Push default arguments if needed.
6194   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6195     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6196       ParmVarDecl *P = Function->getParamDecl(i);
6197       ExprResult R = S.PerformCopyInitialization(
6198           InitializedEntity::InitializeParameter(S.Context,
6199                                                  Function->getParamDecl(i)),
6200           SourceLocation(),
6201           P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6202                                            : P->getDefaultArg());
6203       if (R.isInvalid())
6204         return false;
6205       ConvertedArgs.push_back(R.get());
6206     }
6207
6208     if (Trap.hasErrorOccurred())
6209       return false;
6210   }
6211   return true;
6212 }
6213
6214 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6215                                   bool MissingImplicitThis) {
6216   SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6217       getOrderedEnableIfAttrs(Function);
6218   if (EnableIfAttrs.empty())
6219     return nullptr;
6220
6221   SFINAETrap Trap(*this);
6222   SmallVector<Expr *, 16> ConvertedArgs;
6223   // FIXME: We should look into making enable_if late-parsed.
6224   Expr *DiscardedThis;
6225   if (!convertArgsForAvailabilityChecks(
6226           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6227           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6228     return EnableIfAttrs[0];
6229
6230   for (auto *EIA : EnableIfAttrs) {
6231     APValue Result;
6232     // FIXME: This doesn't consider value-dependent cases, because doing so is
6233     // very difficult. Ideally, we should handle them more gracefully.
6234     if (!EIA->getCond()->EvaluateWithSubstitution(
6235             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6236       return EIA;
6237
6238     if (!Result.isInt() || !Result.getInt().getBoolValue())
6239       return EIA;
6240   }
6241   return nullptr;
6242 }
6243
6244 template <typename CheckFn>
6245 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6246                                         bool ArgDependent, SourceLocation Loc,
6247                                         CheckFn &&IsSuccessful) {
6248   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6249   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6250     if (ArgDependent == DIA->getArgDependent())
6251       Attrs.push_back(DIA);
6252   }
6253
6254   // Common case: No diagnose_if attributes, so we can quit early.
6255   if (Attrs.empty())
6256     return false;
6257
6258   auto WarningBegin = std::stable_partition(
6259       Attrs.begin(), Attrs.end(),
6260       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6261
6262   // Note that diagnose_if attributes are late-parsed, so they appear in the
6263   // correct order (unlike enable_if attributes).
6264   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6265                                IsSuccessful);
6266   if (ErrAttr != WarningBegin) {
6267     const DiagnoseIfAttr *DIA = *ErrAttr;
6268     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6269     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6270         << DIA->getParent() << DIA->getCond()->getSourceRange();
6271     return true;
6272   }
6273
6274   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6275     if (IsSuccessful(DIA)) {
6276       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6277       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6278           << DIA->getParent() << DIA->getCond()->getSourceRange();
6279     }
6280
6281   return false;
6282 }
6283
6284 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6285                                                const Expr *ThisArg,
6286                                                ArrayRef<const Expr *> Args,
6287                                                SourceLocation Loc) {
6288   return diagnoseDiagnoseIfAttrsWith(
6289       *this, Function, /*ArgDependent=*/true, Loc,
6290       [&](const DiagnoseIfAttr *DIA) {
6291         APValue Result;
6292         // It's sane to use the same Args for any redecl of this function, since
6293         // EvaluateWithSubstitution only cares about the position of each
6294         // argument in the arg list, not the ParmVarDecl* it maps to.
6295         if (!DIA->getCond()->EvaluateWithSubstitution(
6296                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6297           return false;
6298         return Result.isInt() && Result.getInt().getBoolValue();
6299       });
6300 }
6301
6302 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6303                                                  SourceLocation Loc) {
6304   return diagnoseDiagnoseIfAttrsWith(
6305       *this, ND, /*ArgDependent=*/false, Loc,
6306       [&](const DiagnoseIfAttr *DIA) {
6307         bool Result;
6308         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6309                Result;
6310       });
6311 }
6312
6313 /// \brief Add all of the function declarations in the given function set to
6314 /// the overload candidate set.
6315 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6316                                  ArrayRef<Expr *> Args,
6317                                  OverloadCandidateSet& CandidateSet,
6318                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6319                                  bool SuppressUserConversions,
6320                                  bool PartialOverloading) {
6321   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6322     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6323     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6324       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6325         QualType ObjectType;
6326         Expr::Classification ObjectClassification;
6327         if (Expr *E = Args[0]) {
6328           // Use the explit base to restrict the lookup:
6329           ObjectType = E->getType();
6330           ObjectClassification = E->Classify(Context);
6331         } // .. else there is an implit base.
6332         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6333                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6334                            ObjectClassification, Args.slice(1), CandidateSet,
6335                            SuppressUserConversions, PartialOverloading);
6336       } else {
6337         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6338                              SuppressUserConversions, PartialOverloading);
6339       }
6340     } else {
6341       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6342       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6343           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6344         QualType ObjectType;
6345         Expr::Classification ObjectClassification;
6346         if (Expr *E = Args[0]) {
6347           // Use the explit base to restrict the lookup:
6348           ObjectType = E->getType();
6349           ObjectClassification = E->Classify(Context);
6350         } // .. else there is an implit base.
6351         AddMethodTemplateCandidate(
6352             FunTmpl, F.getPair(),
6353             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6354             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6355             Args.slice(1), CandidateSet, SuppressUserConversions,
6356             PartialOverloading);
6357       } else {
6358         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6359                                      ExplicitTemplateArgs, Args,
6360                                      CandidateSet, SuppressUserConversions,
6361                                      PartialOverloading);
6362       }
6363     }
6364   }
6365 }
6366
6367 /// AddMethodCandidate - Adds a named decl (which is some kind of
6368 /// method) as a method candidate to the given overload set.
6369 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6370                               QualType ObjectType,
6371                               Expr::Classification ObjectClassification,
6372                               ArrayRef<Expr *> Args,
6373                               OverloadCandidateSet& CandidateSet,
6374                               bool SuppressUserConversions) {
6375   NamedDecl *Decl = FoundDecl.getDecl();
6376   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6377
6378   if (isa<UsingShadowDecl>(Decl))
6379     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6380
6381   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6382     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6383            "Expected a member function template");
6384     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6385                                /*ExplicitArgs*/ nullptr, ObjectType,
6386                                ObjectClassification, Args, CandidateSet,
6387                                SuppressUserConversions);
6388   } else {
6389     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6390                        ObjectType, ObjectClassification, Args, CandidateSet,
6391                        SuppressUserConversions);
6392   }
6393 }
6394
6395 /// AddMethodCandidate - Adds the given C++ member function to the set
6396 /// of candidate functions, using the given function call arguments
6397 /// and the object argument (@c Object). For example, in a call
6398 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6399 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6400 /// allow user-defined conversions via constructors or conversion
6401 /// operators.
6402 void
6403 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6404                          CXXRecordDecl *ActingContext, QualType ObjectType,
6405                          Expr::Classification ObjectClassification,
6406                          ArrayRef<Expr *> Args,
6407                          OverloadCandidateSet &CandidateSet,
6408                          bool SuppressUserConversions,
6409                          bool PartialOverloading,
6410                          ConversionSequenceList EarlyConversions) {
6411   const FunctionProtoType *Proto
6412     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6413   assert(Proto && "Methods without a prototype cannot be overloaded");
6414   assert(!isa<CXXConstructorDecl>(Method) &&
6415          "Use AddOverloadCandidate for constructors");
6416
6417   if (!CandidateSet.isNewCandidate(Method))
6418     return;
6419
6420   // C++11 [class.copy]p23: [DR1402]
6421   //   A defaulted move assignment operator that is defined as deleted is
6422   //   ignored by overload resolution.
6423   if (Method->isDefaulted() && Method->isDeleted() &&
6424       Method->isMoveAssignmentOperator())
6425     return;
6426
6427   // Overload resolution is always an unevaluated context.
6428   EnterExpressionEvaluationContext Unevaluated(
6429       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6430
6431   // Add this candidate
6432   OverloadCandidate &Candidate =
6433       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6434   Candidate.FoundDecl = FoundDecl;
6435   Candidate.Function = Method;
6436   Candidate.IsSurrogate = false;
6437   Candidate.IgnoreObjectArgument = false;
6438   Candidate.ExplicitCallArguments = Args.size();
6439
6440   unsigned NumParams = Proto->getNumParams();
6441
6442   // (C++ 13.3.2p2): A candidate function having fewer than m
6443   // parameters is viable only if it has an ellipsis in its parameter
6444   // list (8.3.5).
6445   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6446       !Proto->isVariadic()) {
6447     Candidate.Viable = false;
6448     Candidate.FailureKind = ovl_fail_too_many_arguments;
6449     return;
6450   }
6451
6452   // (C++ 13.3.2p2): A candidate function having more than m parameters
6453   // is viable only if the (m+1)st parameter has a default argument
6454   // (8.3.6). For the purposes of overload resolution, the
6455   // parameter list is truncated on the right, so that there are
6456   // exactly m parameters.
6457   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6458   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6459     // Not enough arguments.
6460     Candidate.Viable = false;
6461     Candidate.FailureKind = ovl_fail_too_few_arguments;
6462     return;
6463   }
6464
6465   Candidate.Viable = true;
6466
6467   if (Method->isStatic() || ObjectType.isNull())
6468     // The implicit object argument is ignored.
6469     Candidate.IgnoreObjectArgument = true;
6470   else {
6471     // Determine the implicit conversion sequence for the object
6472     // parameter.
6473     Candidate.Conversions[0] = TryObjectArgumentInitialization(
6474         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6475         Method, ActingContext);
6476     if (Candidate.Conversions[0].isBad()) {
6477       Candidate.Viable = false;
6478       Candidate.FailureKind = ovl_fail_bad_conversion;
6479       return;
6480     }
6481   }
6482
6483   // (CUDA B.1): Check for invalid calls between targets.
6484   if (getLangOpts().CUDA)
6485     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6486       if (!IsAllowedCUDACall(Caller, Method)) {
6487         Candidate.Viable = false;
6488         Candidate.FailureKind = ovl_fail_bad_target;
6489         return;
6490       }
6491
6492   // Determine the implicit conversion sequences for each of the
6493   // arguments.
6494   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6495     if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6496       // We already formed a conversion sequence for this parameter during
6497       // template argument deduction.
6498     } else if (ArgIdx < NumParams) {
6499       // (C++ 13.3.2p3): for F to be a viable function, there shall
6500       // exist for each argument an implicit conversion sequence
6501       // (13.3.3.1) that converts that argument to the corresponding
6502       // parameter of F.
6503       QualType ParamType = Proto->getParamType(ArgIdx);
6504       Candidate.Conversions[ArgIdx + 1]
6505         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6506                                 SuppressUserConversions,
6507                                 /*InOverloadResolution=*/true,
6508                                 /*AllowObjCWritebackConversion=*/
6509                                   getLangOpts().ObjCAutoRefCount);
6510       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6511         Candidate.Viable = false;
6512         Candidate.FailureKind = ovl_fail_bad_conversion;
6513         return;
6514       }
6515     } else {
6516       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6517       // argument for which there is no corresponding parameter is
6518       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6519       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6520     }
6521   }
6522
6523   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6524     Candidate.Viable = false;
6525     Candidate.FailureKind = ovl_fail_enable_if;
6526     Candidate.DeductionFailure.Data = FailedAttr;
6527     return;
6528   }
6529 }
6530
6531 /// \brief Add a C++ member function template as a candidate to the candidate
6532 /// set, using template argument deduction to produce an appropriate member
6533 /// function template specialization.
6534 void
6535 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6536                                  DeclAccessPair FoundDecl,
6537                                  CXXRecordDecl *ActingContext,
6538                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6539                                  QualType ObjectType,
6540                                  Expr::Classification ObjectClassification,
6541                                  ArrayRef<Expr *> Args,
6542                                  OverloadCandidateSet& CandidateSet,
6543                                  bool SuppressUserConversions,
6544                                  bool PartialOverloading) {
6545   if (!CandidateSet.isNewCandidate(MethodTmpl))
6546     return;
6547
6548   // C++ [over.match.funcs]p7:
6549   //   In each case where a candidate is a function template, candidate
6550   //   function template specializations are generated using template argument
6551   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6552   //   candidate functions in the usual way.113) A given name can refer to one
6553   //   or more function templates and also to a set of overloaded non-template
6554   //   functions. In such a case, the candidate functions generated from each
6555   //   function template are combined with the set of non-template candidate
6556   //   functions.
6557   TemplateDeductionInfo Info(CandidateSet.getLocation());
6558   FunctionDecl *Specialization = nullptr;
6559   ConversionSequenceList Conversions;
6560   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6561           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6562           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6563             return CheckNonDependentConversions(
6564                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6565                 SuppressUserConversions, ActingContext, ObjectType,
6566                 ObjectClassification);
6567           })) {
6568     OverloadCandidate &Candidate =
6569         CandidateSet.addCandidate(Conversions.size(), Conversions);
6570     Candidate.FoundDecl = FoundDecl;
6571     Candidate.Function = MethodTmpl->getTemplatedDecl();
6572     Candidate.Viable = false;
6573     Candidate.IsSurrogate = false;
6574     Candidate.IgnoreObjectArgument =
6575         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6576         ObjectType.isNull();
6577     Candidate.ExplicitCallArguments = Args.size();
6578     if (Result == TDK_NonDependentConversionFailure)
6579       Candidate.FailureKind = ovl_fail_bad_conversion;
6580     else {
6581       Candidate.FailureKind = ovl_fail_bad_deduction;
6582       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6583                                                             Info);
6584     }
6585     return;
6586   }
6587
6588   // Add the function template specialization produced by template argument
6589   // deduction as a candidate.
6590   assert(Specialization && "Missing member function template specialization?");
6591   assert(isa<CXXMethodDecl>(Specialization) &&
6592          "Specialization is not a member function?");
6593   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6594                      ActingContext, ObjectType, ObjectClassification, Args,
6595                      CandidateSet, SuppressUserConversions, PartialOverloading,
6596                      Conversions);
6597 }
6598
6599 /// \brief Add a C++ function template specialization as a candidate
6600 /// in the candidate set, using template argument deduction to produce
6601 /// an appropriate function template specialization.
6602 void
6603 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6604                                    DeclAccessPair FoundDecl,
6605                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6606                                    ArrayRef<Expr *> Args,
6607                                    OverloadCandidateSet& CandidateSet,
6608                                    bool SuppressUserConversions,
6609                                    bool PartialOverloading) {
6610   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6611     return;
6612
6613   // C++ [over.match.funcs]p7:
6614   //   In each case where a candidate is a function template, candidate
6615   //   function template specializations are generated using template argument
6616   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6617   //   candidate functions in the usual way.113) A given name can refer to one
6618   //   or more function templates and also to a set of overloaded non-template
6619   //   functions. In such a case, the candidate functions generated from each
6620   //   function template are combined with the set of non-template candidate
6621   //   functions.
6622   TemplateDeductionInfo Info(CandidateSet.getLocation());
6623   FunctionDecl *Specialization = nullptr;
6624   ConversionSequenceList Conversions;
6625   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6626           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6627           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6628             return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6629                                                 Args, CandidateSet, Conversions,
6630                                                 SuppressUserConversions);
6631           })) {
6632     OverloadCandidate &Candidate =
6633         CandidateSet.addCandidate(Conversions.size(), Conversions);
6634     Candidate.FoundDecl = FoundDecl;
6635     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6636     Candidate.Viable = false;
6637     Candidate.IsSurrogate = false;
6638     // Ignore the object argument if there is one, since we don't have an object
6639     // type.
6640     Candidate.IgnoreObjectArgument =
6641         isa<CXXMethodDecl>(Candidate.Function) &&
6642         !isa<CXXConstructorDecl>(Candidate.Function);
6643     Candidate.ExplicitCallArguments = Args.size();
6644     if (Result == TDK_NonDependentConversionFailure)
6645       Candidate.FailureKind = ovl_fail_bad_conversion;
6646     else {
6647       Candidate.FailureKind = ovl_fail_bad_deduction;
6648       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6649                                                             Info);
6650     }
6651     return;
6652   }
6653
6654   // Add the function template specialization produced by template argument
6655   // deduction as a candidate.
6656   assert(Specialization && "Missing function template specialization?");
6657   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6658                        SuppressUserConversions, PartialOverloading,
6659                        /*AllowExplicit*/false, Conversions);
6660 }
6661
6662 /// Check that implicit conversion sequences can be formed for each argument
6663 /// whose corresponding parameter has a non-dependent type, per DR1391's
6664 /// [temp.deduct.call]p10.
6665 bool Sema::CheckNonDependentConversions(
6666     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6667     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6668     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6669     CXXRecordDecl *ActingContext, QualType ObjectType,
6670     Expr::Classification ObjectClassification) {
6671   // FIXME: The cases in which we allow explicit conversions for constructor
6672   // arguments never consider calling a constructor template. It's not clear
6673   // that is correct.
6674   const bool AllowExplicit = false;
6675
6676   auto *FD = FunctionTemplate->getTemplatedDecl();
6677   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6678   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6679   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6680
6681   Conversions =
6682       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6683
6684   // Overload resolution is always an unevaluated context.
6685   EnterExpressionEvaluationContext Unevaluated(
6686       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6687
6688   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6689   // require that, but this check should never result in a hard error, and
6690   // overload resolution is permitted to sidestep instantiations.
6691   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6692       !ObjectType.isNull()) {
6693     Conversions[0] = TryObjectArgumentInitialization(
6694         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6695         Method, ActingContext);
6696     if (Conversions[0].isBad())
6697       return true;
6698   }
6699
6700   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6701        ++I) {
6702     QualType ParamType = ParamTypes[I];
6703     if (!ParamType->isDependentType()) {
6704       Conversions[ThisConversions + I]
6705         = TryCopyInitialization(*this, Args[I], ParamType,
6706                                 SuppressUserConversions,
6707                                 /*InOverloadResolution=*/true,
6708                                 /*AllowObjCWritebackConversion=*/
6709                                   getLangOpts().ObjCAutoRefCount,
6710                                 AllowExplicit);
6711       if (Conversions[ThisConversions + I].isBad())
6712         return true;
6713     }
6714   }
6715
6716   return false;
6717 }
6718
6719 /// Determine whether this is an allowable conversion from the result
6720 /// of an explicit conversion operator to the expected type, per C++
6721 /// [over.match.conv]p1 and [over.match.ref]p1.
6722 ///
6723 /// \param ConvType The return type of the conversion function.
6724 ///
6725 /// \param ToType The type we are converting to.
6726 ///
6727 /// \param AllowObjCPointerConversion Allow a conversion from one
6728 /// Objective-C pointer to another.
6729 ///
6730 /// \returns true if the conversion is allowable, false otherwise.
6731 static bool isAllowableExplicitConversion(Sema &S,
6732                                           QualType ConvType, QualType ToType,
6733                                           bool AllowObjCPointerConversion) {
6734   QualType ToNonRefType = ToType.getNonReferenceType();
6735
6736   // Easy case: the types are the same.
6737   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6738     return true;
6739
6740   // Allow qualification conversions.
6741   bool ObjCLifetimeConversion;
6742   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6743                                   ObjCLifetimeConversion))
6744     return true;
6745
6746   // If we're not allowed to consider Objective-C pointer conversions,
6747   // we're done.
6748   if (!AllowObjCPointerConversion)
6749     return false;
6750
6751   // Is this an Objective-C pointer conversion?
6752   bool IncompatibleObjC = false;
6753   QualType ConvertedType;
6754   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6755                                    IncompatibleObjC);
6756 }
6757
6758 /// AddConversionCandidate - Add a C++ conversion function as a
6759 /// candidate in the candidate set (C++ [over.match.conv],
6760 /// C++ [over.match.copy]). From is the expression we're converting from,
6761 /// and ToType is the type that we're eventually trying to convert to
6762 /// (which may or may not be the same type as the type that the
6763 /// conversion function produces).
6764 void
6765 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6766                              DeclAccessPair FoundDecl,
6767                              CXXRecordDecl *ActingContext,
6768                              Expr *From, QualType ToType,
6769                              OverloadCandidateSet& CandidateSet,
6770                              bool AllowObjCConversionOnExplicit) {
6771   assert(!Conversion->getDescribedFunctionTemplate() &&
6772          "Conversion function templates use AddTemplateConversionCandidate");
6773   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6774   if (!CandidateSet.isNewCandidate(Conversion))
6775     return;
6776
6777   // If the conversion function has an undeduced return type, trigger its
6778   // deduction now.
6779   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6780     if (DeduceReturnType(Conversion, From->getExprLoc()))
6781       return;
6782     ConvType = Conversion->getConversionType().getNonReferenceType();
6783   }
6784
6785   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6786   // operator is only a candidate if its return type is the target type or
6787   // can be converted to the target type with a qualification conversion.
6788   if (Conversion->isExplicit() &&
6789       !isAllowableExplicitConversion(*this, ConvType, ToType,
6790                                      AllowObjCConversionOnExplicit))
6791     return;
6792
6793   // Overload resolution is always an unevaluated context.
6794   EnterExpressionEvaluationContext Unevaluated(
6795       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6796
6797   // Add this candidate
6798   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6799   Candidate.FoundDecl = FoundDecl;
6800   Candidate.Function = Conversion;
6801   Candidate.IsSurrogate = false;
6802   Candidate.IgnoreObjectArgument = false;
6803   Candidate.FinalConversion.setAsIdentityConversion();
6804   Candidate.FinalConversion.setFromType(ConvType);
6805   Candidate.FinalConversion.setAllToTypes(ToType);
6806   Candidate.Viable = true;
6807   Candidate.ExplicitCallArguments = 1;
6808
6809   // C++ [over.match.funcs]p4:
6810   //   For conversion functions, the function is considered to be a member of
6811   //   the class of the implicit implied object argument for the purpose of
6812   //   defining the type of the implicit object parameter.
6813   //
6814   // Determine the implicit conversion sequence for the implicit
6815   // object parameter.
6816   QualType ImplicitParamType = From->getType();
6817   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6818     ImplicitParamType = FromPtrType->getPointeeType();
6819   CXXRecordDecl *ConversionContext
6820     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6821
6822   Candidate.Conversions[0] = TryObjectArgumentInitialization(
6823       *this, CandidateSet.getLocation(), From->getType(),
6824       From->Classify(Context), Conversion, ConversionContext);
6825
6826   if (Candidate.Conversions[0].isBad()) {
6827     Candidate.Viable = false;
6828     Candidate.FailureKind = ovl_fail_bad_conversion;
6829     return;
6830   }
6831
6832   // We won't go through a user-defined type conversion function to convert a
6833   // derived to base as such conversions are given Conversion Rank. They only
6834   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6835   QualType FromCanon
6836     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6837   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6838   if (FromCanon == ToCanon ||
6839       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6840     Candidate.Viable = false;
6841     Candidate.FailureKind = ovl_fail_trivial_conversion;
6842     return;
6843   }
6844
6845   // To determine what the conversion from the result of calling the
6846   // conversion function to the type we're eventually trying to
6847   // convert to (ToType), we need to synthesize a call to the
6848   // conversion function and attempt copy initialization from it. This
6849   // makes sure that we get the right semantics with respect to
6850   // lvalues/rvalues and the type. Fortunately, we can allocate this
6851   // call on the stack and we don't need its arguments to be
6852   // well-formed.
6853   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6854                             VK_LValue, From->getLocStart());
6855   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6856                                 Context.getPointerType(Conversion->getType()),
6857                                 CK_FunctionToPointerDecay,
6858                                 &ConversionRef, VK_RValue);
6859
6860   QualType ConversionType = Conversion->getConversionType();
6861   if (!isCompleteType(From->getLocStart(), ConversionType)) {
6862     Candidate.Viable = false;
6863     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6864     return;
6865   }
6866
6867   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6868
6869   // Note that it is safe to allocate CallExpr on the stack here because
6870   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6871   // allocator).
6872   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6873   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6874                 From->getLocStart());
6875   ImplicitConversionSequence ICS =
6876     TryCopyInitialization(*this, &Call, ToType,
6877                           /*SuppressUserConversions=*/true,
6878                           /*InOverloadResolution=*/false,
6879                           /*AllowObjCWritebackConversion=*/false);
6880
6881   switch (ICS.getKind()) {
6882   case ImplicitConversionSequence::StandardConversion:
6883     Candidate.FinalConversion = ICS.Standard;
6884
6885     // C++ [over.ics.user]p3:
6886     //   If the user-defined conversion is specified by a specialization of a
6887     //   conversion function template, the second standard conversion sequence
6888     //   shall have exact match rank.
6889     if (Conversion->getPrimaryTemplate() &&
6890         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6891       Candidate.Viable = false;
6892       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6893       return;
6894     }
6895
6896     // C++0x [dcl.init.ref]p5:
6897     //    In the second case, if the reference is an rvalue reference and
6898     //    the second standard conversion sequence of the user-defined
6899     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6900     //    program is ill-formed.
6901     if (ToType->isRValueReferenceType() &&
6902         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6903       Candidate.Viable = false;
6904       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6905       return;
6906     }
6907     break;
6908
6909   case ImplicitConversionSequence::BadConversion:
6910     Candidate.Viable = false;
6911     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6912     return;
6913
6914   default:
6915     llvm_unreachable(
6916            "Can only end up with a standard conversion sequence or failure");
6917   }
6918
6919   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6920     Candidate.Viable = false;
6921     Candidate.FailureKind = ovl_fail_enable_if;
6922     Candidate.DeductionFailure.Data = FailedAttr;
6923     return;
6924   }
6925 }
6926
6927 /// \brief Adds a conversion function template specialization
6928 /// candidate to the overload set, using template argument deduction
6929 /// to deduce the template arguments of the conversion function
6930 /// template from the type that we are converting to (C++
6931 /// [temp.deduct.conv]).
6932 void
6933 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6934                                      DeclAccessPair FoundDecl,
6935                                      CXXRecordDecl *ActingDC,
6936                                      Expr *From, QualType ToType,
6937                                      OverloadCandidateSet &CandidateSet,
6938                                      bool AllowObjCConversionOnExplicit) {
6939   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6940          "Only conversion function templates permitted here");
6941
6942   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6943     return;
6944
6945   TemplateDeductionInfo Info(CandidateSet.getLocation());
6946   CXXConversionDecl *Specialization = nullptr;
6947   if (TemplateDeductionResult Result
6948         = DeduceTemplateArguments(FunctionTemplate, ToType,
6949                                   Specialization, Info)) {
6950     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6951     Candidate.FoundDecl = FoundDecl;
6952     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6953     Candidate.Viable = false;
6954     Candidate.FailureKind = ovl_fail_bad_deduction;
6955     Candidate.IsSurrogate = false;
6956     Candidate.IgnoreObjectArgument = false;
6957     Candidate.ExplicitCallArguments = 1;
6958     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6959                                                           Info);
6960     return;
6961   }
6962
6963   // Add the conversion function template specialization produced by
6964   // template argument deduction as a candidate.
6965   assert(Specialization && "Missing function template specialization?");
6966   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6967                          CandidateSet, AllowObjCConversionOnExplicit);
6968 }
6969
6970 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6971 /// converts the given @c Object to a function pointer via the
6972 /// conversion function @c Conversion, and then attempts to call it
6973 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6974 /// the type of function that we'll eventually be calling.
6975 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6976                                  DeclAccessPair FoundDecl,
6977                                  CXXRecordDecl *ActingContext,
6978                                  const FunctionProtoType *Proto,
6979                                  Expr *Object,
6980                                  ArrayRef<Expr *> Args,
6981                                  OverloadCandidateSet& CandidateSet) {
6982   if (!CandidateSet.isNewCandidate(Conversion))
6983     return;
6984
6985   // Overload resolution is always an unevaluated context.
6986   EnterExpressionEvaluationContext Unevaluated(
6987       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6988
6989   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6990   Candidate.FoundDecl = FoundDecl;
6991   Candidate.Function = nullptr;
6992   Candidate.Surrogate = Conversion;
6993   Candidate.Viable = true;
6994   Candidate.IsSurrogate = true;
6995   Candidate.IgnoreObjectArgument = false;
6996   Candidate.ExplicitCallArguments = Args.size();
6997
6998   // Determine the implicit conversion sequence for the implicit
6999   // object parameter.
7000   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7001       *this, CandidateSet.getLocation(), Object->getType(),
7002       Object->Classify(Context), Conversion, ActingContext);
7003   if (ObjectInit.isBad()) {
7004     Candidate.Viable = false;
7005     Candidate.FailureKind = ovl_fail_bad_conversion;
7006     Candidate.Conversions[0] = ObjectInit;
7007     return;
7008   }
7009
7010   // The first conversion is actually a user-defined conversion whose
7011   // first conversion is ObjectInit's standard conversion (which is
7012   // effectively a reference binding). Record it as such.
7013   Candidate.Conversions[0].setUserDefined();
7014   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7015   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7016   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7017   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7018   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7019   Candidate.Conversions[0].UserDefined.After
7020     = Candidate.Conversions[0].UserDefined.Before;
7021   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7022
7023   // Find the
7024   unsigned NumParams = Proto->getNumParams();
7025
7026   // (C++ 13.3.2p2): A candidate function having fewer than m
7027   // parameters is viable only if it has an ellipsis in its parameter
7028   // list (8.3.5).
7029   if (Args.size() > NumParams && !Proto->isVariadic()) {
7030     Candidate.Viable = false;
7031     Candidate.FailureKind = ovl_fail_too_many_arguments;
7032     return;
7033   }
7034
7035   // Function types don't have any default arguments, so just check if
7036   // we have enough arguments.
7037   if (Args.size() < NumParams) {
7038     // Not enough arguments.
7039     Candidate.Viable = false;
7040     Candidate.FailureKind = ovl_fail_too_few_arguments;
7041     return;
7042   }
7043
7044   // Determine the implicit conversion sequences for each of the
7045   // arguments.
7046   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7047     if (ArgIdx < NumParams) {
7048       // (C++ 13.3.2p3): for F to be a viable function, there shall
7049       // exist for each argument an implicit conversion sequence
7050       // (13.3.3.1) that converts that argument to the corresponding
7051       // parameter of F.
7052       QualType ParamType = Proto->getParamType(ArgIdx);
7053       Candidate.Conversions[ArgIdx + 1]
7054         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7055                                 /*SuppressUserConversions=*/false,
7056                                 /*InOverloadResolution=*/false,
7057                                 /*AllowObjCWritebackConversion=*/
7058                                   getLangOpts().ObjCAutoRefCount);
7059       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7060         Candidate.Viable = false;
7061         Candidate.FailureKind = ovl_fail_bad_conversion;
7062         return;
7063       }
7064     } else {
7065       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7066       // argument for which there is no corresponding parameter is
7067       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7068       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7069     }
7070   }
7071
7072   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7073     Candidate.Viable = false;
7074     Candidate.FailureKind = ovl_fail_enable_if;
7075     Candidate.DeductionFailure.Data = FailedAttr;
7076     return;
7077   }
7078 }
7079
7080 /// \brief Add overload candidates for overloaded operators that are
7081 /// member functions.
7082 ///
7083 /// Add the overloaded operator candidates that are member functions
7084 /// for the operator Op that was used in an operator expression such
7085 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7086 /// CandidateSet will store the added overload candidates. (C++
7087 /// [over.match.oper]).
7088 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7089                                        SourceLocation OpLoc,
7090                                        ArrayRef<Expr *> Args,
7091                                        OverloadCandidateSet& CandidateSet,
7092                                        SourceRange OpRange) {
7093   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7094
7095   // C++ [over.match.oper]p3:
7096   //   For a unary operator @ with an operand of a type whose
7097   //   cv-unqualified version is T1, and for a binary operator @ with
7098   //   a left operand of a type whose cv-unqualified version is T1 and
7099   //   a right operand of a type whose cv-unqualified version is T2,
7100   //   three sets of candidate functions, designated member
7101   //   candidates, non-member candidates and built-in candidates, are
7102   //   constructed as follows:
7103   QualType T1 = Args[0]->getType();
7104
7105   //     -- If T1 is a complete class type or a class currently being
7106   //        defined, the set of member candidates is the result of the
7107   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7108   //        the set of member candidates is empty.
7109   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7110     // Complete the type if it can be completed.
7111     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7112       return;
7113     // If the type is neither complete nor being defined, bail out now.
7114     if (!T1Rec->getDecl()->getDefinition())
7115       return;
7116
7117     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7118     LookupQualifiedName(Operators, T1Rec->getDecl());
7119     Operators.suppressDiagnostics();
7120
7121     for (LookupResult::iterator Oper = Operators.begin(),
7122                              OperEnd = Operators.end();
7123          Oper != OperEnd;
7124          ++Oper)
7125       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7126                          Args[0]->Classify(Context), Args.slice(1),
7127                          CandidateSet, /*SuppressUserConversions=*/false);
7128   }
7129 }
7130
7131 /// AddBuiltinCandidate - Add a candidate for a built-in
7132 /// operator. ResultTy and ParamTys are the result and parameter types
7133 /// of the built-in candidate, respectively. Args and NumArgs are the
7134 /// arguments being passed to the candidate. IsAssignmentOperator
7135 /// should be true when this built-in candidate is an assignment
7136 /// operator. NumContextualBoolArguments is the number of arguments
7137 /// (at the beginning of the argument list) that will be contextually
7138 /// converted to bool.
7139 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
7140                                ArrayRef<Expr *> Args,
7141                                OverloadCandidateSet& CandidateSet,
7142                                bool IsAssignmentOperator,
7143                                unsigned NumContextualBoolArguments) {
7144   // Overload resolution is always an unevaluated context.
7145   EnterExpressionEvaluationContext Unevaluated(
7146       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7147
7148   // Add this candidate
7149   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7150   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7151   Candidate.Function = nullptr;
7152   Candidate.IsSurrogate = false;
7153   Candidate.IgnoreObjectArgument = false;
7154   Candidate.BuiltinTypes.ResultTy = ResultTy;
7155   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7156     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
7157
7158   // Determine the implicit conversion sequences for each of the
7159   // arguments.
7160   Candidate.Viable = true;
7161   Candidate.ExplicitCallArguments = Args.size();
7162   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7163     // C++ [over.match.oper]p4:
7164     //   For the built-in assignment operators, conversions of the
7165     //   left operand are restricted as follows:
7166     //     -- no temporaries are introduced to hold the left operand, and
7167     //     -- no user-defined conversions are applied to the left
7168     //        operand to achieve a type match with the left-most
7169     //        parameter of a built-in candidate.
7170     //
7171     // We block these conversions by turning off user-defined
7172     // conversions, since that is the only way that initialization of
7173     // a reference to a non-class type can occur from something that
7174     // is not of the same type.
7175     if (ArgIdx < NumContextualBoolArguments) {
7176       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7177              "Contextual conversion to bool requires bool type");
7178       Candidate.Conversions[ArgIdx]
7179         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7180     } else {
7181       Candidate.Conversions[ArgIdx]
7182         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7183                                 ArgIdx == 0 && IsAssignmentOperator,
7184                                 /*InOverloadResolution=*/false,
7185                                 /*AllowObjCWritebackConversion=*/
7186                                   getLangOpts().ObjCAutoRefCount);
7187     }
7188     if (Candidate.Conversions[ArgIdx].isBad()) {
7189       Candidate.Viable = false;
7190       Candidate.FailureKind = ovl_fail_bad_conversion;
7191       break;
7192     }
7193   }
7194 }
7195
7196 namespace {
7197
7198 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7199 /// candidate operator functions for built-in operators (C++
7200 /// [over.built]). The types are separated into pointer types and
7201 /// enumeration types.
7202 class BuiltinCandidateTypeSet  {
7203   /// TypeSet - A set of types.
7204   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7205                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7206
7207   /// PointerTypes - The set of pointer types that will be used in the
7208   /// built-in candidates.
7209   TypeSet PointerTypes;
7210
7211   /// MemberPointerTypes - The set of member pointer types that will be
7212   /// used in the built-in candidates.
7213   TypeSet MemberPointerTypes;
7214
7215   /// EnumerationTypes - The set of enumeration types that will be
7216   /// used in the built-in candidates.
7217   TypeSet EnumerationTypes;
7218
7219   /// \brief The set of vector types that will be used in the built-in
7220   /// candidates.
7221   TypeSet VectorTypes;
7222
7223   /// \brief A flag indicating non-record types are viable candidates
7224   bool HasNonRecordTypes;
7225
7226   /// \brief A flag indicating whether either arithmetic or enumeration types
7227   /// were present in the candidate set.
7228   bool HasArithmeticOrEnumeralTypes;
7229
7230   /// \brief A flag indicating whether the nullptr type was present in the
7231   /// candidate set.
7232   bool HasNullPtrType;
7233
7234   /// Sema - The semantic analysis instance where we are building the
7235   /// candidate type set.
7236   Sema &SemaRef;
7237
7238   /// Context - The AST context in which we will build the type sets.
7239   ASTContext &Context;
7240
7241   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7242                                                const Qualifiers &VisibleQuals);
7243   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7244
7245 public:
7246   /// iterator - Iterates through the types that are part of the set.
7247   typedef TypeSet::iterator iterator;
7248
7249   BuiltinCandidateTypeSet(Sema &SemaRef)
7250     : HasNonRecordTypes(false),
7251       HasArithmeticOrEnumeralTypes(false),
7252       HasNullPtrType(false),
7253       SemaRef(SemaRef),
7254       Context(SemaRef.Context) { }
7255
7256   void AddTypesConvertedFrom(QualType Ty,
7257                              SourceLocation Loc,
7258                              bool AllowUserConversions,
7259                              bool AllowExplicitConversions,
7260                              const Qualifiers &VisibleTypeConversionsQuals);
7261
7262   /// pointer_begin - First pointer type found;
7263   iterator pointer_begin() { return PointerTypes.begin(); }
7264
7265   /// pointer_end - Past the last pointer type found;
7266   iterator pointer_end() { return PointerTypes.end(); }
7267
7268   /// member_pointer_begin - First member pointer type found;
7269   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7270
7271   /// member_pointer_end - Past the last member pointer type found;
7272   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7273
7274   /// enumeration_begin - First enumeration type found;
7275   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7276
7277   /// enumeration_end - Past the last enumeration type found;
7278   iterator enumeration_end() { return EnumerationTypes.end(); }
7279
7280   iterator vector_begin() { return VectorTypes.begin(); }
7281   iterator vector_end() { return VectorTypes.end(); }
7282
7283   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7284   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7285   bool hasNullPtrType() const { return HasNullPtrType; }
7286 };
7287
7288 } // end anonymous namespace
7289
7290 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7291 /// the set of pointer types along with any more-qualified variants of
7292 /// that type. For example, if @p Ty is "int const *", this routine
7293 /// will add "int const *", "int const volatile *", "int const
7294 /// restrict *", and "int const volatile restrict *" to the set of
7295 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7296 /// false otherwise.
7297 ///
7298 /// FIXME: what to do about extended qualifiers?
7299 bool
7300 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7301                                              const Qualifiers &VisibleQuals) {
7302
7303   // Insert this type.
7304   if (!PointerTypes.insert(Ty))
7305     return false;
7306
7307   QualType PointeeTy;
7308   const PointerType *PointerTy = Ty->getAs<PointerType>();
7309   bool buildObjCPtr = false;
7310   if (!PointerTy) {
7311     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7312     PointeeTy = PTy->getPointeeType();
7313     buildObjCPtr = true;
7314   } else {
7315     PointeeTy = PointerTy->getPointeeType();
7316   }
7317
7318   // Don't add qualified variants of arrays. For one, they're not allowed
7319   // (the qualifier would sink to the element type), and for another, the
7320   // only overload situation where it matters is subscript or pointer +- int,
7321   // and those shouldn't have qualifier variants anyway.
7322   if (PointeeTy->isArrayType())
7323     return true;
7324
7325   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7326   bool hasVolatile = VisibleQuals.hasVolatile();
7327   bool hasRestrict = VisibleQuals.hasRestrict();
7328
7329   // Iterate through all strict supersets of BaseCVR.
7330   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7331     if ((CVR | BaseCVR) != CVR) continue;
7332     // Skip over volatile if no volatile found anywhere in the types.
7333     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7334
7335     // Skip over restrict if no restrict found anywhere in the types, or if
7336     // the type cannot be restrict-qualified.
7337     if ((CVR & Qualifiers::Restrict) &&
7338         (!hasRestrict ||
7339          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7340       continue;
7341
7342     // Build qualified pointee type.
7343     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7344
7345     // Build qualified pointer type.
7346     QualType QPointerTy;
7347     if (!buildObjCPtr)
7348       QPointerTy = Context.getPointerType(QPointeeTy);
7349     else
7350       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7351
7352     // Insert qualified pointer type.
7353     PointerTypes.insert(QPointerTy);
7354   }
7355
7356   return true;
7357 }
7358
7359 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7360 /// to the set of pointer types along with any more-qualified variants of
7361 /// that type. For example, if @p Ty is "int const *", this routine
7362 /// will add "int const *", "int const volatile *", "int const
7363 /// restrict *", and "int const volatile restrict *" to the set of
7364 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7365 /// false otherwise.
7366 ///
7367 /// FIXME: what to do about extended qualifiers?
7368 bool
7369 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7370     QualType Ty) {
7371   // Insert this type.
7372   if (!MemberPointerTypes.insert(Ty))
7373     return false;
7374
7375   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7376   assert(PointerTy && "type was not a member pointer type!");
7377
7378   QualType PointeeTy = PointerTy->getPointeeType();
7379   // Don't add qualified variants of arrays. For one, they're not allowed
7380   // (the qualifier would sink to the element type), and for another, the
7381   // only overload situation where it matters is subscript or pointer +- int,
7382   // and those shouldn't have qualifier variants anyway.
7383   if (PointeeTy->isArrayType())
7384     return true;
7385   const Type *ClassTy = PointerTy->getClass();
7386
7387   // Iterate through all strict supersets of the pointee type's CVR
7388   // qualifiers.
7389   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7390   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7391     if ((CVR | BaseCVR) != CVR) continue;
7392
7393     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7394     MemberPointerTypes.insert(
7395       Context.getMemberPointerType(QPointeeTy, ClassTy));
7396   }
7397
7398   return true;
7399 }
7400
7401 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7402 /// Ty can be implicit converted to the given set of @p Types. We're
7403 /// primarily interested in pointer types and enumeration types. We also
7404 /// take member pointer types, for the conditional operator.
7405 /// AllowUserConversions is true if we should look at the conversion
7406 /// functions of a class type, and AllowExplicitConversions if we
7407 /// should also include the explicit conversion functions of a class
7408 /// type.
7409 void
7410 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7411                                                SourceLocation Loc,
7412                                                bool AllowUserConversions,
7413                                                bool AllowExplicitConversions,
7414                                                const Qualifiers &VisibleQuals) {
7415   // Only deal with canonical types.
7416   Ty = Context.getCanonicalType(Ty);
7417
7418   // Look through reference types; they aren't part of the type of an
7419   // expression for the purposes of conversions.
7420   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7421     Ty = RefTy->getPointeeType();
7422
7423   // If we're dealing with an array type, decay to the pointer.
7424   if (Ty->isArrayType())
7425     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7426
7427   // Otherwise, we don't care about qualifiers on the type.
7428   Ty = Ty.getLocalUnqualifiedType();
7429
7430   // Flag if we ever add a non-record type.
7431   const RecordType *TyRec = Ty->getAs<RecordType>();
7432   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7433
7434   // Flag if we encounter an arithmetic type.
7435   HasArithmeticOrEnumeralTypes =
7436     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7437
7438   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7439     PointerTypes.insert(Ty);
7440   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7441     // Insert our type, and its more-qualified variants, into the set
7442     // of types.
7443     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7444       return;
7445   } else if (Ty->isMemberPointerType()) {
7446     // Member pointers are far easier, since the pointee can't be converted.
7447     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7448       return;
7449   } else if (Ty->isEnumeralType()) {
7450     HasArithmeticOrEnumeralTypes = true;
7451     EnumerationTypes.insert(Ty);
7452   } else if (Ty->isVectorType()) {
7453     // We treat vector types as arithmetic types in many contexts as an
7454     // extension.
7455     HasArithmeticOrEnumeralTypes = true;
7456     VectorTypes.insert(Ty);
7457   } else if (Ty->isNullPtrType()) {
7458     HasNullPtrType = true;
7459   } else if (AllowUserConversions && TyRec) {
7460     // No conversion functions in incomplete types.
7461     if (!SemaRef.isCompleteType(Loc, Ty))
7462       return;
7463
7464     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7465     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7466       if (isa<UsingShadowDecl>(D))
7467         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7468
7469       // Skip conversion function templates; they don't tell us anything
7470       // about which builtin types we can convert to.
7471       if (isa<FunctionTemplateDecl>(D))
7472         continue;
7473
7474       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7475       if (AllowExplicitConversions || !Conv->isExplicit()) {
7476         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7477                               VisibleQuals);
7478       }
7479     }
7480   }
7481 }
7482
7483 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7484 /// the volatile- and non-volatile-qualified assignment operators for the
7485 /// given type to the candidate set.
7486 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7487                                                    QualType T,
7488                                                    ArrayRef<Expr *> Args,
7489                                     OverloadCandidateSet &CandidateSet) {
7490   QualType ParamTypes[2];
7491
7492   // T& operator=(T&, T)
7493   ParamTypes[0] = S.Context.getLValueReferenceType(T);
7494   ParamTypes[1] = T;
7495   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7496                         /*IsAssignmentOperator=*/true);
7497
7498   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7499     // volatile T& operator=(volatile T&, T)
7500     ParamTypes[0]
7501       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7502     ParamTypes[1] = T;
7503     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7504                           /*IsAssignmentOperator=*/true);
7505   }
7506 }
7507
7508 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7509 /// if any, found in visible type conversion functions found in ArgExpr's type.
7510 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7511     Qualifiers VRQuals;
7512     const RecordType *TyRec;
7513     if (const MemberPointerType *RHSMPType =
7514         ArgExpr->getType()->getAs<MemberPointerType>())
7515       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7516     else
7517       TyRec = ArgExpr->getType()->getAs<RecordType>();
7518     if (!TyRec) {
7519       // Just to be safe, assume the worst case.
7520       VRQuals.addVolatile();
7521       VRQuals.addRestrict();
7522       return VRQuals;
7523     }
7524
7525     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7526     if (!ClassDecl->hasDefinition())
7527       return VRQuals;
7528
7529     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7530       if (isa<UsingShadowDecl>(D))
7531         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7532       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7533         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7534         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7535           CanTy = ResTypeRef->getPointeeType();
7536         // Need to go down the pointer/mempointer chain and add qualifiers
7537         // as see them.
7538         bool done = false;
7539         while (!done) {
7540           if (CanTy.isRestrictQualified())
7541             VRQuals.addRestrict();
7542           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7543             CanTy = ResTypePtr->getPointeeType();
7544           else if (const MemberPointerType *ResTypeMPtr =
7545                 CanTy->getAs<MemberPointerType>())
7546             CanTy = ResTypeMPtr->getPointeeType();
7547           else
7548             done = true;
7549           if (CanTy.isVolatileQualified())
7550             VRQuals.addVolatile();
7551           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7552             return VRQuals;
7553         }
7554       }
7555     }
7556     return VRQuals;
7557 }
7558
7559 namespace {
7560
7561 /// \brief Helper class to manage the addition of builtin operator overload
7562 /// candidates. It provides shared state and utility methods used throughout
7563 /// the process, as well as a helper method to add each group of builtin
7564 /// operator overloads from the standard to a candidate set.
7565 class BuiltinOperatorOverloadBuilder {
7566   // Common instance state available to all overload candidate addition methods.
7567   Sema &S;
7568   ArrayRef<Expr *> Args;
7569   Qualifiers VisibleTypeConversionsQuals;
7570   bool HasArithmeticOrEnumeralCandidateType;
7571   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7572   OverloadCandidateSet &CandidateSet;
7573
7574   // Define some constants used to index and iterate over the arithemetic types
7575   // provided via the getArithmeticType() method below.
7576   // The "promoted arithmetic types" are the arithmetic
7577   // types are that preserved by promotion (C++ [over.built]p2).
7578   static const unsigned FirstIntegralType = 4;
7579   static const unsigned LastIntegralType = 21;
7580   static const unsigned FirstPromotedIntegralType = 4,
7581                         LastPromotedIntegralType = 12;
7582   static const unsigned FirstPromotedArithmeticType = 0,
7583                         LastPromotedArithmeticType = 12;
7584   static const unsigned NumArithmeticTypes = 21;
7585
7586   /// \brief Get the canonical type for a given arithmetic type index.
7587   CanQualType getArithmeticType(unsigned index) {
7588     assert(index < NumArithmeticTypes);
7589     static CanQualType ASTContext::* const
7590       ArithmeticTypes[NumArithmeticTypes] = {
7591       // Start of promoted types.
7592       &ASTContext::FloatTy,
7593       &ASTContext::DoubleTy,
7594       &ASTContext::LongDoubleTy,
7595       &ASTContext::Float128Ty,
7596
7597       // Start of integral types.
7598       &ASTContext::IntTy,
7599       &ASTContext::LongTy,
7600       &ASTContext::LongLongTy,
7601       &ASTContext::Int128Ty,
7602       &ASTContext::UnsignedIntTy,
7603       &ASTContext::UnsignedLongTy,
7604       &ASTContext::UnsignedLongLongTy,
7605       &ASTContext::UnsignedInt128Ty,
7606       // End of promoted types.
7607
7608       &ASTContext::BoolTy,
7609       &ASTContext::CharTy,
7610       &ASTContext::WCharTy,
7611       &ASTContext::Char16Ty,
7612       &ASTContext::Char32Ty,
7613       &ASTContext::SignedCharTy,
7614       &ASTContext::ShortTy,
7615       &ASTContext::UnsignedCharTy,
7616       &ASTContext::UnsignedShortTy,
7617       // End of integral types.
7618       // FIXME: What about complex? What about half?
7619     };
7620     return S.Context.*ArithmeticTypes[index];
7621   }
7622
7623   /// \brief Gets the canonical type resulting from the usual arithemetic
7624   /// converions for the given arithmetic types.
7625   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7626     // Accelerator table for performing the usual arithmetic conversions.
7627     // The rules are basically:
7628     //   - if either is floating-point, use the wider floating-point
7629     //   - if same signedness, use the higher rank
7630     //   - if same size, use unsigned of the higher rank
7631     //   - use the larger type
7632     // These rules, together with the axiom that higher ranks are
7633     // never smaller, are sufficient to precompute all of these results
7634     // *except* when dealing with signed types of higher rank.
7635     // (we could precompute SLL x UI for all known platforms, but it's
7636     // better not to make any assumptions).
7637     // We assume that int128 has a higher rank than long long on all platforms.
7638     enum PromotedType : int8_t {
7639             Dep=-1,
7640             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7641     };
7642     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7643                                         [LastPromotedArithmeticType] = {
7644 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7645 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7646 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7647 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7648 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7649 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7650 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7651 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7652 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7653 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7654 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7655     };
7656
7657     assert(L < LastPromotedArithmeticType);
7658     assert(R < LastPromotedArithmeticType);
7659     int Idx = ConversionsTable[L][R];
7660
7661     // Fast path: the table gives us a concrete answer.
7662     if (Idx != Dep) return getArithmeticType(Idx);
7663
7664     // Slow path: we need to compare widths.
7665     // An invariant is that the signed type has higher rank.
7666     CanQualType LT = getArithmeticType(L),
7667                 RT = getArithmeticType(R);
7668     unsigned LW = S.Context.getIntWidth(LT),
7669              RW = S.Context.getIntWidth(RT);
7670
7671     // If they're different widths, use the signed type.
7672     if (LW > RW) return LT;
7673     else if (LW < RW) return RT;
7674
7675     // Otherwise, use the unsigned type of the signed type's rank.
7676     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7677     assert(L == SLL || R == SLL);
7678     return S.Context.UnsignedLongLongTy;
7679   }
7680
7681   /// \brief Helper method to factor out the common pattern of adding overloads
7682   /// for '++' and '--' builtin operators.
7683   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7684                                            bool HasVolatile,
7685                                            bool HasRestrict) {
7686     QualType ParamTypes[2] = {
7687       S.Context.getLValueReferenceType(CandidateTy),
7688       S.Context.IntTy
7689     };
7690
7691     // Non-volatile version.
7692     if (Args.size() == 1)
7693       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7694     else
7695       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7696
7697     // Use a heuristic to reduce number of builtin candidates in the set:
7698     // add volatile version only if there are conversions to a volatile type.
7699     if (HasVolatile) {
7700       ParamTypes[0] =
7701         S.Context.getLValueReferenceType(
7702           S.Context.getVolatileType(CandidateTy));
7703       if (Args.size() == 1)
7704         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7705       else
7706         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7707     }
7708
7709     // Add restrict version only if there are conversions to a restrict type
7710     // and our candidate type is a non-restrict-qualified pointer.
7711     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7712         !CandidateTy.isRestrictQualified()) {
7713       ParamTypes[0]
7714         = S.Context.getLValueReferenceType(
7715             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7716       if (Args.size() == 1)
7717         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7718       else
7719         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7720
7721       if (HasVolatile) {
7722         ParamTypes[0]
7723           = S.Context.getLValueReferenceType(
7724               S.Context.getCVRQualifiedType(CandidateTy,
7725                                             (Qualifiers::Volatile |
7726                                              Qualifiers::Restrict)));
7727         if (Args.size() == 1)
7728           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7729         else
7730           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7731       }
7732     }
7733
7734   }
7735
7736 public:
7737   BuiltinOperatorOverloadBuilder(
7738     Sema &S, ArrayRef<Expr *> Args,
7739     Qualifiers VisibleTypeConversionsQuals,
7740     bool HasArithmeticOrEnumeralCandidateType,
7741     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7742     OverloadCandidateSet &CandidateSet)
7743     : S(S), Args(Args),
7744       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7745       HasArithmeticOrEnumeralCandidateType(
7746         HasArithmeticOrEnumeralCandidateType),
7747       CandidateTypes(CandidateTypes),
7748       CandidateSet(CandidateSet) {
7749     // Validate some of our static helper constants in debug builds.
7750     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7751            "Invalid first promoted integral type");
7752     assert(getArithmeticType(LastPromotedIntegralType - 1)
7753              == S.Context.UnsignedInt128Ty &&
7754            "Invalid last promoted integral type");
7755     assert(getArithmeticType(FirstPromotedArithmeticType)
7756              == S.Context.FloatTy &&
7757            "Invalid first promoted arithmetic type");
7758     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7759              == S.Context.UnsignedInt128Ty &&
7760            "Invalid last promoted arithmetic type");
7761   }
7762
7763   // C++ [over.built]p3:
7764   //
7765   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7766   //   is either volatile or empty, there exist candidate operator
7767   //   functions of the form
7768   //
7769   //       VQ T&      operator++(VQ T&);
7770   //       T          operator++(VQ T&, int);
7771   //
7772   // C++ [over.built]p4:
7773   //
7774   //   For every pair (T, VQ), where T is an arithmetic type other
7775   //   than bool, and VQ is either volatile or empty, there exist
7776   //   candidate operator functions of the form
7777   //
7778   //       VQ T&      operator--(VQ T&);
7779   //       T          operator--(VQ T&, int);
7780   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7781     if (!HasArithmeticOrEnumeralCandidateType)
7782       return;
7783
7784     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7785          Arith < NumArithmeticTypes; ++Arith) {
7786       addPlusPlusMinusMinusStyleOverloads(
7787         getArithmeticType(Arith),
7788         VisibleTypeConversionsQuals.hasVolatile(),
7789         VisibleTypeConversionsQuals.hasRestrict());
7790     }
7791   }
7792
7793   // C++ [over.built]p5:
7794   //
7795   //   For every pair (T, VQ), where T is a cv-qualified or
7796   //   cv-unqualified object type, and VQ is either volatile or
7797   //   empty, there exist candidate operator functions of the form
7798   //
7799   //       T*VQ&      operator++(T*VQ&);
7800   //       T*VQ&      operator--(T*VQ&);
7801   //       T*         operator++(T*VQ&, int);
7802   //       T*         operator--(T*VQ&, int);
7803   void addPlusPlusMinusMinusPointerOverloads() {
7804     for (BuiltinCandidateTypeSet::iterator
7805               Ptr = CandidateTypes[0].pointer_begin(),
7806            PtrEnd = CandidateTypes[0].pointer_end();
7807          Ptr != PtrEnd; ++Ptr) {
7808       // Skip pointer types that aren't pointers to object types.
7809       if (!(*Ptr)->getPointeeType()->isObjectType())
7810         continue;
7811
7812       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7813         (!(*Ptr).isVolatileQualified() &&
7814          VisibleTypeConversionsQuals.hasVolatile()),
7815         (!(*Ptr).isRestrictQualified() &&
7816          VisibleTypeConversionsQuals.hasRestrict()));
7817     }
7818   }
7819
7820   // C++ [over.built]p6:
7821   //   For every cv-qualified or cv-unqualified object type T, there
7822   //   exist candidate operator functions of the form
7823   //
7824   //       T&         operator*(T*);
7825   //
7826   // C++ [over.built]p7:
7827   //   For every function type T that does not have cv-qualifiers or a
7828   //   ref-qualifier, there exist candidate operator functions of the form
7829   //       T&         operator*(T*);
7830   void addUnaryStarPointerOverloads() {
7831     for (BuiltinCandidateTypeSet::iterator
7832               Ptr = CandidateTypes[0].pointer_begin(),
7833            PtrEnd = CandidateTypes[0].pointer_end();
7834          Ptr != PtrEnd; ++Ptr) {
7835       QualType ParamTy = *Ptr;
7836       QualType PointeeTy = ParamTy->getPointeeType();
7837       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7838         continue;
7839
7840       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7841         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7842           continue;
7843
7844       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7845                             &ParamTy, Args, CandidateSet);
7846     }
7847   }
7848
7849   // C++ [over.built]p9:
7850   //  For every promoted arithmetic type T, there exist candidate
7851   //  operator functions of the form
7852   //
7853   //       T         operator+(T);
7854   //       T         operator-(T);
7855   void addUnaryPlusOrMinusArithmeticOverloads() {
7856     if (!HasArithmeticOrEnumeralCandidateType)
7857       return;
7858
7859     for (unsigned Arith = FirstPromotedArithmeticType;
7860          Arith < LastPromotedArithmeticType; ++Arith) {
7861       QualType ArithTy = getArithmeticType(Arith);
7862       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7863     }
7864
7865     // Extension: We also add these operators for vector types.
7866     for (BuiltinCandidateTypeSet::iterator
7867               Vec = CandidateTypes[0].vector_begin(),
7868            VecEnd = CandidateTypes[0].vector_end();
7869          Vec != VecEnd; ++Vec) {
7870       QualType VecTy = *Vec;
7871       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7872     }
7873   }
7874
7875   // C++ [over.built]p8:
7876   //   For every type T, there exist candidate operator functions of
7877   //   the form
7878   //
7879   //       T*         operator+(T*);
7880   void addUnaryPlusPointerOverloads() {
7881     for (BuiltinCandidateTypeSet::iterator
7882               Ptr = CandidateTypes[0].pointer_begin(),
7883            PtrEnd = CandidateTypes[0].pointer_end();
7884          Ptr != PtrEnd; ++Ptr) {
7885       QualType ParamTy = *Ptr;
7886       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7887     }
7888   }
7889
7890   // C++ [over.built]p10:
7891   //   For every promoted integral type T, there exist candidate
7892   //   operator functions of the form
7893   //
7894   //        T         operator~(T);
7895   void addUnaryTildePromotedIntegralOverloads() {
7896     if (!HasArithmeticOrEnumeralCandidateType)
7897       return;
7898
7899     for (unsigned Int = FirstPromotedIntegralType;
7900          Int < LastPromotedIntegralType; ++Int) {
7901       QualType IntTy = getArithmeticType(Int);
7902       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7903     }
7904
7905     // Extension: We also add this operator for vector types.
7906     for (BuiltinCandidateTypeSet::iterator
7907               Vec = CandidateTypes[0].vector_begin(),
7908            VecEnd = CandidateTypes[0].vector_end();
7909          Vec != VecEnd; ++Vec) {
7910       QualType VecTy = *Vec;
7911       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7912     }
7913   }
7914
7915   // C++ [over.match.oper]p16:
7916   //   For every pointer to member type T or type std::nullptr_t, there
7917   //   exist candidate operator functions of the form
7918   //
7919   //        bool operator==(T,T);
7920   //        bool operator!=(T,T);
7921   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7922     /// Set of (canonical) types that we've already handled.
7923     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7924
7925     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7926       for (BuiltinCandidateTypeSet::iterator
7927                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7928              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7929            MemPtr != MemPtrEnd;
7930            ++MemPtr) {
7931         // Don't add the same builtin candidate twice.
7932         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7933           continue;
7934
7935         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7936         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7937       }
7938
7939       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7940         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7941         if (AddedTypes.insert(NullPtrTy).second) {
7942           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7943           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7944                                 CandidateSet);
7945         }
7946       }
7947     }
7948   }
7949
7950   // C++ [over.built]p15:
7951   //
7952   //   For every T, where T is an enumeration type or a pointer type,
7953   //   there exist candidate operator functions of the form
7954   //
7955   //        bool       operator<(T, T);
7956   //        bool       operator>(T, T);
7957   //        bool       operator<=(T, T);
7958   //        bool       operator>=(T, T);
7959   //        bool       operator==(T, T);
7960   //        bool       operator!=(T, T);
7961   void addRelationalPointerOrEnumeralOverloads() {
7962     // C++ [over.match.oper]p3:
7963     //   [...]the built-in candidates include all of the candidate operator
7964     //   functions defined in 13.6 that, compared to the given operator, [...]
7965     //   do not have the same parameter-type-list as any non-template non-member
7966     //   candidate.
7967     //
7968     // Note that in practice, this only affects enumeration types because there
7969     // aren't any built-in candidates of record type, and a user-defined operator
7970     // must have an operand of record or enumeration type. Also, the only other
7971     // overloaded operator with enumeration arguments, operator=,
7972     // cannot be overloaded for enumeration types, so this is the only place
7973     // where we must suppress candidates like this.
7974     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7975       UserDefinedBinaryOperators;
7976
7977     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7978       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7979           CandidateTypes[ArgIdx].enumeration_end()) {
7980         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7981                                          CEnd = CandidateSet.end();
7982              C != CEnd; ++C) {
7983           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7984             continue;
7985
7986           if (C->Function->isFunctionTemplateSpecialization())
7987             continue;
7988
7989           QualType FirstParamType =
7990             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7991           QualType SecondParamType =
7992             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7993
7994           // Skip if either parameter isn't of enumeral type.
7995           if (!FirstParamType->isEnumeralType() ||
7996               !SecondParamType->isEnumeralType())
7997             continue;
7998
7999           // Add this operator to the set of known user-defined operators.
8000           UserDefinedBinaryOperators.insert(
8001             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8002                            S.Context.getCanonicalType(SecondParamType)));
8003         }
8004       }
8005     }
8006
8007     /// Set of (canonical) types that we've already handled.
8008     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8009
8010     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8011       for (BuiltinCandidateTypeSet::iterator
8012                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8013              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8014            Ptr != PtrEnd; ++Ptr) {
8015         // Don't add the same builtin candidate twice.
8016         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8017           continue;
8018
8019         QualType ParamTypes[2] = { *Ptr, *Ptr };
8020         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
8021       }
8022       for (BuiltinCandidateTypeSet::iterator
8023                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8024              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8025            Enum != EnumEnd; ++Enum) {
8026         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8027
8028         // Don't add the same builtin candidate twice, or if a user defined
8029         // candidate exists.
8030         if (!AddedTypes.insert(CanonType).second ||
8031             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8032                                                             CanonType)))
8033           continue;
8034
8035         QualType ParamTypes[2] = { *Enum, *Enum };
8036         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
8037       }
8038     }
8039   }
8040
8041   // C++ [over.built]p13:
8042   //
8043   //   For every cv-qualified or cv-unqualified object type T
8044   //   there exist candidate operator functions of the form
8045   //
8046   //      T*         operator+(T*, ptrdiff_t);
8047   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8048   //      T*         operator-(T*, ptrdiff_t);
8049   //      T*         operator+(ptrdiff_t, T*);
8050   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8051   //
8052   // C++ [over.built]p14:
8053   //
8054   //   For every T, where T is a pointer to object type, there
8055   //   exist candidate operator functions of the form
8056   //
8057   //      ptrdiff_t  operator-(T, T);
8058   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8059     /// Set of (canonical) types that we've already handled.
8060     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8061
8062     for (int Arg = 0; Arg < 2; ++Arg) {
8063       QualType AsymmetricParamTypes[2] = {
8064         S.Context.getPointerDiffType(),
8065         S.Context.getPointerDiffType(),
8066       };
8067       for (BuiltinCandidateTypeSet::iterator
8068                 Ptr = CandidateTypes[Arg].pointer_begin(),
8069              PtrEnd = CandidateTypes[Arg].pointer_end();
8070            Ptr != PtrEnd; ++Ptr) {
8071         QualType PointeeTy = (*Ptr)->getPointeeType();
8072         if (!PointeeTy->isObjectType())
8073           continue;
8074
8075         AsymmetricParamTypes[Arg] = *Ptr;
8076         if (Arg == 0 || Op == OO_Plus) {
8077           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8078           // T* operator+(ptrdiff_t, T*);
8079           S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
8080         }
8081         if (Op == OO_Minus) {
8082           // ptrdiff_t operator-(T, T);
8083           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8084             continue;
8085
8086           QualType ParamTypes[2] = { *Ptr, *Ptr };
8087           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
8088                                 Args, CandidateSet);
8089         }
8090       }
8091     }
8092   }
8093
8094   // C++ [over.built]p12:
8095   //
8096   //   For every pair of promoted arithmetic types L and R, there
8097   //   exist candidate operator functions of the form
8098   //
8099   //        LR         operator*(L, R);
8100   //        LR         operator/(L, R);
8101   //        LR         operator+(L, R);
8102   //        LR         operator-(L, R);
8103   //        bool       operator<(L, R);
8104   //        bool       operator>(L, R);
8105   //        bool       operator<=(L, R);
8106   //        bool       operator>=(L, R);
8107   //        bool       operator==(L, R);
8108   //        bool       operator!=(L, R);
8109   //
8110   //   where LR is the result of the usual arithmetic conversions
8111   //   between types L and R.
8112   //
8113   // C++ [over.built]p24:
8114   //
8115   //   For every pair of promoted arithmetic types L and R, there exist
8116   //   candidate operator functions of the form
8117   //
8118   //        LR       operator?(bool, L, R);
8119   //
8120   //   where LR is the result of the usual arithmetic conversions
8121   //   between types L and R.
8122   // Our candidates ignore the first parameter.
8123   void addGenericBinaryArithmeticOverloads(bool isComparison) {
8124     if (!HasArithmeticOrEnumeralCandidateType)
8125       return;
8126
8127     for (unsigned Left = FirstPromotedArithmeticType;
8128          Left < LastPromotedArithmeticType; ++Left) {
8129       for (unsigned Right = FirstPromotedArithmeticType;
8130            Right < LastPromotedArithmeticType; ++Right) {
8131         QualType LandR[2] = { getArithmeticType(Left),
8132                               getArithmeticType(Right) };
8133         QualType Result =
8134           isComparison ? S.Context.BoolTy
8135                        : getUsualArithmeticConversions(Left, Right);
8136         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8137       }
8138     }
8139
8140     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8141     // conditional operator for vector types.
8142     for (BuiltinCandidateTypeSet::iterator
8143               Vec1 = CandidateTypes[0].vector_begin(),
8144            Vec1End = CandidateTypes[0].vector_end();
8145          Vec1 != Vec1End; ++Vec1) {
8146       for (BuiltinCandidateTypeSet::iterator
8147                 Vec2 = CandidateTypes[1].vector_begin(),
8148              Vec2End = CandidateTypes[1].vector_end();
8149            Vec2 != Vec2End; ++Vec2) {
8150         QualType LandR[2] = { *Vec1, *Vec2 };
8151         QualType Result = S.Context.BoolTy;
8152         if (!isComparison) {
8153           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
8154             Result = *Vec1;
8155           else
8156             Result = *Vec2;
8157         }
8158
8159         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8160       }
8161     }
8162   }
8163
8164   // C++ [over.built]p17:
8165   //
8166   //   For every pair of promoted integral types L and R, there
8167   //   exist candidate operator functions of the form
8168   //
8169   //      LR         operator%(L, R);
8170   //      LR         operator&(L, R);
8171   //      LR         operator^(L, R);
8172   //      LR         operator|(L, R);
8173   //      L          operator<<(L, R);
8174   //      L          operator>>(L, R);
8175   //
8176   //   where LR is the result of the usual arithmetic conversions
8177   //   between types L and R.
8178   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8179     if (!HasArithmeticOrEnumeralCandidateType)
8180       return;
8181
8182     for (unsigned Left = FirstPromotedIntegralType;
8183          Left < LastPromotedIntegralType; ++Left) {
8184       for (unsigned Right = FirstPromotedIntegralType;
8185            Right < LastPromotedIntegralType; ++Right) {
8186         QualType LandR[2] = { getArithmeticType(Left),
8187                               getArithmeticType(Right) };
8188         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
8189             ? LandR[0]
8190             : getUsualArithmeticConversions(Left, Right);
8191         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8192       }
8193     }
8194   }
8195
8196   // C++ [over.built]p20:
8197   //
8198   //   For every pair (T, VQ), where T is an enumeration or
8199   //   pointer to member type and VQ is either volatile or
8200   //   empty, there exist candidate operator functions of the form
8201   //
8202   //        VQ T&      operator=(VQ T&, T);
8203   void addAssignmentMemberPointerOrEnumeralOverloads() {
8204     /// Set of (canonical) types that we've already handled.
8205     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8206
8207     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8208       for (BuiltinCandidateTypeSet::iterator
8209                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8210              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8211            Enum != EnumEnd; ++Enum) {
8212         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8213           continue;
8214
8215         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8216       }
8217
8218       for (BuiltinCandidateTypeSet::iterator
8219                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8220              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8221            MemPtr != MemPtrEnd; ++MemPtr) {
8222         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8223           continue;
8224
8225         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8226       }
8227     }
8228   }
8229
8230   // C++ [over.built]p19:
8231   //
8232   //   For every pair (T, VQ), where T is any type and VQ is either
8233   //   volatile or empty, there exist candidate operator functions
8234   //   of the form
8235   //
8236   //        T*VQ&      operator=(T*VQ&, T*);
8237   //
8238   // C++ [over.built]p21:
8239   //
8240   //   For every pair (T, VQ), where T is a cv-qualified or
8241   //   cv-unqualified object type and VQ is either volatile or
8242   //   empty, there exist candidate operator functions of the form
8243   //
8244   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8245   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8246   void addAssignmentPointerOverloads(bool isEqualOp) {
8247     /// Set of (canonical) types that we've already handled.
8248     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8249
8250     for (BuiltinCandidateTypeSet::iterator
8251               Ptr = CandidateTypes[0].pointer_begin(),
8252            PtrEnd = CandidateTypes[0].pointer_end();
8253          Ptr != PtrEnd; ++Ptr) {
8254       // If this is operator=, keep track of the builtin candidates we added.
8255       if (isEqualOp)
8256         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8257       else if (!(*Ptr)->getPointeeType()->isObjectType())
8258         continue;
8259
8260       // non-volatile version
8261       QualType ParamTypes[2] = {
8262         S.Context.getLValueReferenceType(*Ptr),
8263         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8264       };
8265       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8266                             /*IsAssigmentOperator=*/ isEqualOp);
8267
8268       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8269                           VisibleTypeConversionsQuals.hasVolatile();
8270       if (NeedVolatile) {
8271         // volatile version
8272         ParamTypes[0] =
8273           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8274         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8275                               /*IsAssigmentOperator=*/isEqualOp);
8276       }
8277
8278       if (!(*Ptr).isRestrictQualified() &&
8279           VisibleTypeConversionsQuals.hasRestrict()) {
8280         // restrict version
8281         ParamTypes[0]
8282           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8283         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8284                               /*IsAssigmentOperator=*/isEqualOp);
8285
8286         if (NeedVolatile) {
8287           // volatile restrict version
8288           ParamTypes[0]
8289             = S.Context.getLValueReferenceType(
8290                 S.Context.getCVRQualifiedType(*Ptr,
8291                                               (Qualifiers::Volatile |
8292                                                Qualifiers::Restrict)));
8293           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8294                                 /*IsAssigmentOperator=*/isEqualOp);
8295         }
8296       }
8297     }
8298
8299     if (isEqualOp) {
8300       for (BuiltinCandidateTypeSet::iterator
8301                 Ptr = CandidateTypes[1].pointer_begin(),
8302              PtrEnd = CandidateTypes[1].pointer_end();
8303            Ptr != PtrEnd; ++Ptr) {
8304         // Make sure we don't add the same candidate twice.
8305         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8306           continue;
8307
8308         QualType ParamTypes[2] = {
8309           S.Context.getLValueReferenceType(*Ptr),
8310           *Ptr,
8311         };
8312
8313         // non-volatile version
8314         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8315                               /*IsAssigmentOperator=*/true);
8316
8317         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8318                            VisibleTypeConversionsQuals.hasVolatile();
8319         if (NeedVolatile) {
8320           // volatile version
8321           ParamTypes[0] =
8322             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8323           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8324                                 /*IsAssigmentOperator=*/true);
8325         }
8326
8327         if (!(*Ptr).isRestrictQualified() &&
8328             VisibleTypeConversionsQuals.hasRestrict()) {
8329           // restrict version
8330           ParamTypes[0]
8331             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8332           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8333                                 /*IsAssigmentOperator=*/true);
8334
8335           if (NeedVolatile) {
8336             // volatile restrict version
8337             ParamTypes[0]
8338               = S.Context.getLValueReferenceType(
8339                   S.Context.getCVRQualifiedType(*Ptr,
8340                                                 (Qualifiers::Volatile |
8341                                                  Qualifiers::Restrict)));
8342             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8343                                   /*IsAssigmentOperator=*/true);
8344           }
8345         }
8346       }
8347     }
8348   }
8349
8350   // C++ [over.built]p18:
8351   //
8352   //   For every triple (L, VQ, R), where L is an arithmetic type,
8353   //   VQ is either volatile or empty, and R is a promoted
8354   //   arithmetic type, there exist candidate operator functions of
8355   //   the form
8356   //
8357   //        VQ L&      operator=(VQ L&, R);
8358   //        VQ L&      operator*=(VQ L&, R);
8359   //        VQ L&      operator/=(VQ L&, R);
8360   //        VQ L&      operator+=(VQ L&, R);
8361   //        VQ L&      operator-=(VQ L&, R);
8362   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8363     if (!HasArithmeticOrEnumeralCandidateType)
8364       return;
8365
8366     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8367       for (unsigned Right = FirstPromotedArithmeticType;
8368            Right < LastPromotedArithmeticType; ++Right) {
8369         QualType ParamTypes[2];
8370         ParamTypes[1] = getArithmeticType(Right);
8371
8372         // Add this built-in operator as a candidate (VQ is empty).
8373         ParamTypes[0] =
8374           S.Context.getLValueReferenceType(getArithmeticType(Left));
8375         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8376                               /*IsAssigmentOperator=*/isEqualOp);
8377
8378         // Add this built-in operator as a candidate (VQ is 'volatile').
8379         if (VisibleTypeConversionsQuals.hasVolatile()) {
8380           ParamTypes[0] =
8381             S.Context.getVolatileType(getArithmeticType(Left));
8382           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8383           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8384                                 /*IsAssigmentOperator=*/isEqualOp);
8385         }
8386       }
8387     }
8388
8389     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8390     for (BuiltinCandidateTypeSet::iterator
8391               Vec1 = CandidateTypes[0].vector_begin(),
8392            Vec1End = CandidateTypes[0].vector_end();
8393          Vec1 != Vec1End; ++Vec1) {
8394       for (BuiltinCandidateTypeSet::iterator
8395                 Vec2 = CandidateTypes[1].vector_begin(),
8396              Vec2End = CandidateTypes[1].vector_end();
8397            Vec2 != Vec2End; ++Vec2) {
8398         QualType ParamTypes[2];
8399         ParamTypes[1] = *Vec2;
8400         // Add this built-in operator as a candidate (VQ is empty).
8401         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8402         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8403                               /*IsAssigmentOperator=*/isEqualOp);
8404
8405         // Add this built-in operator as a candidate (VQ is 'volatile').
8406         if (VisibleTypeConversionsQuals.hasVolatile()) {
8407           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8408           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8409           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8410                                 /*IsAssigmentOperator=*/isEqualOp);
8411         }
8412       }
8413     }
8414   }
8415
8416   // C++ [over.built]p22:
8417   //
8418   //   For every triple (L, VQ, R), where L is an integral type, VQ
8419   //   is either volatile or empty, and R is a promoted integral
8420   //   type, there exist candidate operator functions of the form
8421   //
8422   //        VQ L&       operator%=(VQ L&, R);
8423   //        VQ L&       operator<<=(VQ L&, R);
8424   //        VQ L&       operator>>=(VQ L&, R);
8425   //        VQ L&       operator&=(VQ L&, R);
8426   //        VQ L&       operator^=(VQ L&, R);
8427   //        VQ L&       operator|=(VQ L&, R);
8428   void addAssignmentIntegralOverloads() {
8429     if (!HasArithmeticOrEnumeralCandidateType)
8430       return;
8431
8432     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8433       for (unsigned Right = FirstPromotedIntegralType;
8434            Right < LastPromotedIntegralType; ++Right) {
8435         QualType ParamTypes[2];
8436         ParamTypes[1] = getArithmeticType(Right);
8437
8438         // Add this built-in operator as a candidate (VQ is empty).
8439         ParamTypes[0] =
8440           S.Context.getLValueReferenceType(getArithmeticType(Left));
8441         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8442         if (VisibleTypeConversionsQuals.hasVolatile()) {
8443           // Add this built-in operator as a candidate (VQ is 'volatile').
8444           ParamTypes[0] = getArithmeticType(Left);
8445           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8446           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8447           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8448         }
8449       }
8450     }
8451   }
8452
8453   // C++ [over.operator]p23:
8454   //
8455   //   There also exist candidate operator functions of the form
8456   //
8457   //        bool        operator!(bool);
8458   //        bool        operator&&(bool, bool);
8459   //        bool        operator||(bool, bool);
8460   void addExclaimOverload() {
8461     QualType ParamTy = S.Context.BoolTy;
8462     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8463                           /*IsAssignmentOperator=*/false,
8464                           /*NumContextualBoolArguments=*/1);
8465   }
8466   void addAmpAmpOrPipePipeOverload() {
8467     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8468     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8469                           /*IsAssignmentOperator=*/false,
8470                           /*NumContextualBoolArguments=*/2);
8471   }
8472
8473   // C++ [over.built]p13:
8474   //
8475   //   For every cv-qualified or cv-unqualified object type T there
8476   //   exist candidate operator functions of the form
8477   //
8478   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8479   //        T&         operator[](T*, ptrdiff_t);
8480   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8481   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8482   //        T&         operator[](ptrdiff_t, T*);
8483   void addSubscriptOverloads() {
8484     for (BuiltinCandidateTypeSet::iterator
8485               Ptr = CandidateTypes[0].pointer_begin(),
8486            PtrEnd = CandidateTypes[0].pointer_end();
8487          Ptr != PtrEnd; ++Ptr) {
8488       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8489       QualType PointeeType = (*Ptr)->getPointeeType();
8490       if (!PointeeType->isObjectType())
8491         continue;
8492
8493       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8494
8495       // T& operator[](T*, ptrdiff_t)
8496       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8497     }
8498
8499     for (BuiltinCandidateTypeSet::iterator
8500               Ptr = CandidateTypes[1].pointer_begin(),
8501            PtrEnd = CandidateTypes[1].pointer_end();
8502          Ptr != PtrEnd; ++Ptr) {
8503       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8504       QualType PointeeType = (*Ptr)->getPointeeType();
8505       if (!PointeeType->isObjectType())
8506         continue;
8507
8508       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8509
8510       // T& operator[](ptrdiff_t, T*)
8511       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8512     }
8513   }
8514
8515   // C++ [over.built]p11:
8516   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8517   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8518   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8519   //    there exist candidate operator functions of the form
8520   //
8521   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8522   //
8523   //    where CV12 is the union of CV1 and CV2.
8524   void addArrowStarOverloads() {
8525     for (BuiltinCandidateTypeSet::iterator
8526              Ptr = CandidateTypes[0].pointer_begin(),
8527            PtrEnd = CandidateTypes[0].pointer_end();
8528          Ptr != PtrEnd; ++Ptr) {
8529       QualType C1Ty = (*Ptr);
8530       QualType C1;
8531       QualifierCollector Q1;
8532       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8533       if (!isa<RecordType>(C1))
8534         continue;
8535       // heuristic to reduce number of builtin candidates in the set.
8536       // Add volatile/restrict version only if there are conversions to a
8537       // volatile/restrict type.
8538       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8539         continue;
8540       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8541         continue;
8542       for (BuiltinCandidateTypeSet::iterator
8543                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8544              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8545            MemPtr != MemPtrEnd; ++MemPtr) {
8546         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8547         QualType C2 = QualType(mptr->getClass(), 0);
8548         C2 = C2.getUnqualifiedType();
8549         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8550           break;
8551         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8552         // build CV12 T&
8553         QualType T = mptr->getPointeeType();
8554         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8555             T.isVolatileQualified())
8556           continue;
8557         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8558             T.isRestrictQualified())
8559           continue;
8560         T = Q1.apply(S.Context, T);
8561         QualType ResultTy = S.Context.getLValueReferenceType(T);
8562         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8563       }
8564     }
8565   }
8566
8567   // Note that we don't consider the first argument, since it has been
8568   // contextually converted to bool long ago. The candidates below are
8569   // therefore added as binary.
8570   //
8571   // C++ [over.built]p25:
8572   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8573   //   enumeration type, there exist candidate operator functions of the form
8574   //
8575   //        T        operator?(bool, T, T);
8576   //
8577   void addConditionalOperatorOverloads() {
8578     /// Set of (canonical) types that we've already handled.
8579     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8580
8581     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8582       for (BuiltinCandidateTypeSet::iterator
8583                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8584              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8585            Ptr != PtrEnd; ++Ptr) {
8586         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8587           continue;
8588
8589         QualType ParamTypes[2] = { *Ptr, *Ptr };
8590         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8591       }
8592
8593       for (BuiltinCandidateTypeSet::iterator
8594                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8595              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8596            MemPtr != MemPtrEnd; ++MemPtr) {
8597         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8598           continue;
8599
8600         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8601         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8602       }
8603
8604       if (S.getLangOpts().CPlusPlus11) {
8605         for (BuiltinCandidateTypeSet::iterator
8606                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8607                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8608              Enum != EnumEnd; ++Enum) {
8609           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8610             continue;
8611
8612           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8613             continue;
8614
8615           QualType ParamTypes[2] = { *Enum, *Enum };
8616           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8617         }
8618       }
8619     }
8620   }
8621 };
8622
8623 } // end anonymous namespace
8624
8625 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8626 /// operator overloads to the candidate set (C++ [over.built]), based
8627 /// on the operator @p Op and the arguments given. For example, if the
8628 /// operator is a binary '+', this routine might add "int
8629 /// operator+(int, int)" to cover integer addition.
8630 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8631                                         SourceLocation OpLoc,
8632                                         ArrayRef<Expr *> Args,
8633                                         OverloadCandidateSet &CandidateSet) {
8634   // Find all of the types that the arguments can convert to, but only
8635   // if the operator we're looking at has built-in operator candidates
8636   // that make use of these types. Also record whether we encounter non-record
8637   // candidate types or either arithmetic or enumeral candidate types.
8638   Qualifiers VisibleTypeConversionsQuals;
8639   VisibleTypeConversionsQuals.addConst();
8640   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8641     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8642
8643   bool HasNonRecordCandidateType = false;
8644   bool HasArithmeticOrEnumeralCandidateType = false;
8645   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8646   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8647     CandidateTypes.emplace_back(*this);
8648     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8649                                                  OpLoc,
8650                                                  true,
8651                                                  (Op == OO_Exclaim ||
8652                                                   Op == OO_AmpAmp ||
8653                                                   Op == OO_PipePipe),
8654                                                  VisibleTypeConversionsQuals);
8655     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8656         CandidateTypes[ArgIdx].hasNonRecordTypes();
8657     HasArithmeticOrEnumeralCandidateType =
8658         HasArithmeticOrEnumeralCandidateType ||
8659         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8660   }
8661
8662   // Exit early when no non-record types have been added to the candidate set
8663   // for any of the arguments to the operator.
8664   //
8665   // We can't exit early for !, ||, or &&, since there we have always have
8666   // 'bool' overloads.
8667   if (!HasNonRecordCandidateType &&
8668       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8669     return;
8670
8671   // Setup an object to manage the common state for building overloads.
8672   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8673                                            VisibleTypeConversionsQuals,
8674                                            HasArithmeticOrEnumeralCandidateType,
8675                                            CandidateTypes, CandidateSet);
8676
8677   // Dispatch over the operation to add in only those overloads which apply.
8678   switch (Op) {
8679   case OO_None:
8680   case NUM_OVERLOADED_OPERATORS:
8681     llvm_unreachable("Expected an overloaded operator");
8682
8683   case OO_New:
8684   case OO_Delete:
8685   case OO_Array_New:
8686   case OO_Array_Delete:
8687   case OO_Call:
8688     llvm_unreachable(
8689                     "Special operators don't use AddBuiltinOperatorCandidates");
8690
8691   case OO_Comma:
8692   case OO_Arrow:
8693   case OO_Coawait:
8694     // C++ [over.match.oper]p3:
8695     //   -- For the operator ',', the unary operator '&', the
8696     //      operator '->', or the operator 'co_await', the
8697     //      built-in candidates set is empty.
8698     break;
8699
8700   case OO_Plus: // '+' is either unary or binary
8701     if (Args.size() == 1)
8702       OpBuilder.addUnaryPlusPointerOverloads();
8703     // Fall through.
8704
8705   case OO_Minus: // '-' is either unary or binary
8706     if (Args.size() == 1) {
8707       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8708     } else {
8709       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8710       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8711     }
8712     break;
8713
8714   case OO_Star: // '*' is either unary or binary
8715     if (Args.size() == 1)
8716       OpBuilder.addUnaryStarPointerOverloads();
8717     else
8718       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8719     break;
8720
8721   case OO_Slash:
8722     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8723     break;
8724
8725   case OO_PlusPlus:
8726   case OO_MinusMinus:
8727     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8728     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8729     break;
8730
8731   case OO_EqualEqual:
8732   case OO_ExclaimEqual:
8733     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8734     // Fall through.
8735
8736   case OO_Less:
8737   case OO_Greater:
8738   case OO_LessEqual:
8739   case OO_GreaterEqual:
8740     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8741     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8742     break;
8743
8744   case OO_Percent:
8745   case OO_Caret:
8746   case OO_Pipe:
8747   case OO_LessLess:
8748   case OO_GreaterGreater:
8749     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8750     break;
8751
8752   case OO_Amp: // '&' is either unary or binary
8753     if (Args.size() == 1)
8754       // C++ [over.match.oper]p3:
8755       //   -- For the operator ',', the unary operator '&', or the
8756       //      operator '->', the built-in candidates set is empty.
8757       break;
8758
8759     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8760     break;
8761
8762   case OO_Tilde:
8763     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8764     break;
8765
8766   case OO_Equal:
8767     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8768     // Fall through.
8769
8770   case OO_PlusEqual:
8771   case OO_MinusEqual:
8772     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8773     // Fall through.
8774
8775   case OO_StarEqual:
8776   case OO_SlashEqual:
8777     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8778     break;
8779
8780   case OO_PercentEqual:
8781   case OO_LessLessEqual:
8782   case OO_GreaterGreaterEqual:
8783   case OO_AmpEqual:
8784   case OO_CaretEqual:
8785   case OO_PipeEqual:
8786     OpBuilder.addAssignmentIntegralOverloads();
8787     break;
8788
8789   case OO_Exclaim:
8790     OpBuilder.addExclaimOverload();
8791     break;
8792
8793   case OO_AmpAmp:
8794   case OO_PipePipe:
8795     OpBuilder.addAmpAmpOrPipePipeOverload();
8796     break;
8797
8798   case OO_Subscript:
8799     OpBuilder.addSubscriptOverloads();
8800     break;
8801
8802   case OO_ArrowStar:
8803     OpBuilder.addArrowStarOverloads();
8804     break;
8805
8806   case OO_Conditional:
8807     OpBuilder.addConditionalOperatorOverloads();
8808     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8809     break;
8810   }
8811 }
8812
8813 /// \brief Add function candidates found via argument-dependent lookup
8814 /// to the set of overloading candidates.
8815 ///
8816 /// This routine performs argument-dependent name lookup based on the
8817 /// given function name (which may also be an operator name) and adds
8818 /// all of the overload candidates found by ADL to the overload
8819 /// candidate set (C++ [basic.lookup.argdep]).
8820 void
8821 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8822                                            SourceLocation Loc,
8823                                            ArrayRef<Expr *> Args,
8824                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8825                                            OverloadCandidateSet& CandidateSet,
8826                                            bool PartialOverloading) {
8827   ADLResult Fns;
8828
8829   // FIXME: This approach for uniquing ADL results (and removing
8830   // redundant candidates from the set) relies on pointer-equality,
8831   // which means we need to key off the canonical decl.  However,
8832   // always going back to the canonical decl might not get us the
8833   // right set of default arguments.  What default arguments are
8834   // we supposed to consider on ADL candidates, anyway?
8835
8836   // FIXME: Pass in the explicit template arguments?
8837   ArgumentDependentLookup(Name, Loc, Args, Fns);
8838
8839   // Erase all of the candidates we already knew about.
8840   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8841                                    CandEnd = CandidateSet.end();
8842        Cand != CandEnd; ++Cand)
8843     if (Cand->Function) {
8844       Fns.erase(Cand->Function);
8845       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8846         Fns.erase(FunTmpl);
8847     }
8848
8849   // For each of the ADL candidates we found, add it to the overload
8850   // set.
8851   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8852     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8853     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8854       if (ExplicitTemplateArgs)
8855         continue;
8856
8857       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8858                            PartialOverloading);
8859     } else
8860       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8861                                    FoundDecl, ExplicitTemplateArgs,
8862                                    Args, CandidateSet, PartialOverloading);
8863   }
8864 }
8865
8866 namespace {
8867 enum class Comparison { Equal, Better, Worse };
8868 }
8869
8870 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8871 /// overload resolution.
8872 ///
8873 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8874 /// Cand1's first N enable_if attributes have precisely the same conditions as
8875 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8876 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8877 ///
8878 /// Note that you can have a pair of candidates such that Cand1's enable_if
8879 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8880 /// worse than Cand1's.
8881 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8882                                        const FunctionDecl *Cand2) {
8883   // Common case: One (or both) decls don't have enable_if attrs.
8884   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8885   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8886   if (!Cand1Attr || !Cand2Attr) {
8887     if (Cand1Attr == Cand2Attr)
8888       return Comparison::Equal;
8889     return Cand1Attr ? Comparison::Better : Comparison::Worse;
8890   }
8891
8892   // FIXME: The next several lines are just
8893   // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8894   // instead of reverse order which is how they're stored in the AST.
8895   auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8896   auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8897
8898   // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8899   // has fewer enable_if attributes than Cand2.
8900   if (Cand1Attrs.size() < Cand2Attrs.size())
8901     return Comparison::Worse;
8902
8903   auto Cand1I = Cand1Attrs.begin();
8904   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8905   for (auto &Cand2A : Cand2Attrs) {
8906     Cand1ID.clear();
8907     Cand2ID.clear();
8908
8909     auto &Cand1A = *Cand1I++;
8910     Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8911     Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8912     if (Cand1ID != Cand2ID)
8913       return Comparison::Worse;
8914   }
8915
8916   return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8917 }
8918
8919 /// isBetterOverloadCandidate - Determines whether the first overload
8920 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8921 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8922                                       const OverloadCandidate &Cand2,
8923                                       SourceLocation Loc,
8924                                       bool UserDefinedConversion) {
8925   // Define viable functions to be better candidates than non-viable
8926   // functions.
8927   if (!Cand2.Viable)
8928     return Cand1.Viable;
8929   else if (!Cand1.Viable)
8930     return false;
8931
8932   // C++ [over.match.best]p1:
8933   //
8934   //   -- if F is a static member function, ICS1(F) is defined such
8935   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8936   //      any function G, and, symmetrically, ICS1(G) is neither
8937   //      better nor worse than ICS1(F).
8938   unsigned StartArg = 0;
8939   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8940     StartArg = 1;
8941
8942   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8943     // We don't allow incompatible pointer conversions in C++.
8944     if (!S.getLangOpts().CPlusPlus)
8945       return ICS.isStandard() &&
8946              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8947
8948     // The only ill-formed conversion we allow in C++ is the string literal to
8949     // char* conversion, which is only considered ill-formed after C++11.
8950     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8951            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8952   };
8953
8954   // Define functions that don't require ill-formed conversions for a given
8955   // argument to be better candidates than functions that do.
8956   unsigned NumArgs = Cand1.Conversions.size();
8957   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8958   bool HasBetterConversion = false;
8959   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8960     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8961     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8962     if (Cand1Bad != Cand2Bad) {
8963       if (Cand1Bad)
8964         return false;
8965       HasBetterConversion = true;
8966     }
8967   }
8968
8969   if (HasBetterConversion)
8970     return true;
8971
8972   // C++ [over.match.best]p1:
8973   //   A viable function F1 is defined to be a better function than another
8974   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8975   //   conversion sequence than ICSi(F2), and then...
8976   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8977     switch (CompareImplicitConversionSequences(S, Loc,
8978                                                Cand1.Conversions[ArgIdx],
8979                                                Cand2.Conversions[ArgIdx])) {
8980     case ImplicitConversionSequence::Better:
8981       // Cand1 has a better conversion sequence.
8982       HasBetterConversion = true;
8983       break;
8984
8985     case ImplicitConversionSequence::Worse:
8986       // Cand1 can't be better than Cand2.
8987       return false;
8988
8989     case ImplicitConversionSequence::Indistinguishable:
8990       // Do nothing.
8991       break;
8992     }
8993   }
8994
8995   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8996   //       ICSj(F2), or, if not that,
8997   if (HasBetterConversion)
8998     return true;
8999
9000   //   -- the context is an initialization by user-defined conversion
9001   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9002   //      from the return type of F1 to the destination type (i.e.,
9003   //      the type of the entity being initialized) is a better
9004   //      conversion sequence than the standard conversion sequence
9005   //      from the return type of F2 to the destination type.
9006   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
9007       isa<CXXConversionDecl>(Cand1.Function) &&
9008       isa<CXXConversionDecl>(Cand2.Function)) {
9009     // First check whether we prefer one of the conversion functions over the
9010     // other. This only distinguishes the results in non-standard, extension
9011     // cases such as the conversion from a lambda closure type to a function
9012     // pointer or block.
9013     ImplicitConversionSequence::CompareKind Result =
9014         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9015     if (Result == ImplicitConversionSequence::Indistinguishable)
9016       Result = CompareStandardConversionSequences(S, Loc,
9017                                                   Cand1.FinalConversion,
9018                                                   Cand2.FinalConversion);
9019
9020     if (Result != ImplicitConversionSequence::Indistinguishable)
9021       return Result == ImplicitConversionSequence::Better;
9022
9023     // FIXME: Compare kind of reference binding if conversion functions
9024     // convert to a reference type used in direct reference binding, per
9025     // C++14 [over.match.best]p1 section 2 bullet 3.
9026   }
9027
9028   //    -- F1 is generated from a deduction-guide and F2 is not
9029   auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9030   auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9031   if (Guide1 && Guide2 && Guide1->isImplicit() != Guide2->isImplicit())
9032     return Guide2->isImplicit();
9033
9034   //    -- F1 is a non-template function and F2 is a function template
9035   //       specialization, or, if not that,
9036   bool Cand1IsSpecialization = Cand1.Function &&
9037                                Cand1.Function->getPrimaryTemplate();
9038   bool Cand2IsSpecialization = Cand2.Function &&
9039                                Cand2.Function->getPrimaryTemplate();
9040   if (Cand1IsSpecialization != Cand2IsSpecialization)
9041     return Cand2IsSpecialization;
9042
9043   //   -- F1 and F2 are function template specializations, and the function
9044   //      template for F1 is more specialized than the template for F2
9045   //      according to the partial ordering rules described in 14.5.5.2, or,
9046   //      if not that,
9047   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9048     if (FunctionTemplateDecl *BetterTemplate
9049           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9050                                          Cand2.Function->getPrimaryTemplate(),
9051                                          Loc,
9052                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9053                                                              : TPOC_Call,
9054                                          Cand1.ExplicitCallArguments,
9055                                          Cand2.ExplicitCallArguments))
9056       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9057   }
9058
9059   // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9060   // A derived-class constructor beats an (inherited) base class constructor.
9061   bool Cand1IsInherited =
9062       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9063   bool Cand2IsInherited =
9064       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9065   if (Cand1IsInherited != Cand2IsInherited)
9066     return Cand2IsInherited;
9067   else if (Cand1IsInherited) {
9068     assert(Cand2IsInherited);
9069     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9070     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9071     if (Cand1Class->isDerivedFrom(Cand2Class))
9072       return true;
9073     if (Cand2Class->isDerivedFrom(Cand1Class))
9074       return false;
9075     // Inherited from sibling base classes: still ambiguous.
9076   }
9077
9078   // Check for enable_if value-based overload resolution.
9079   if (Cand1.Function && Cand2.Function) {
9080     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9081     if (Cmp != Comparison::Equal)
9082       return Cmp == Comparison::Better;
9083   }
9084
9085   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9086     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9087     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9088            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9089   }
9090
9091   bool HasPS1 = Cand1.Function != nullptr &&
9092                 functionHasPassObjectSizeParams(Cand1.Function);
9093   bool HasPS2 = Cand2.Function != nullptr &&
9094                 functionHasPassObjectSizeParams(Cand2.Function);
9095   return HasPS1 != HasPS2 && HasPS1;
9096 }
9097
9098 /// Determine whether two declarations are "equivalent" for the purposes of
9099 /// name lookup and overload resolution. This applies when the same internal/no
9100 /// linkage entity is defined by two modules (probably by textually including
9101 /// the same header). In such a case, we don't consider the declarations to
9102 /// declare the same entity, but we also don't want lookups with both
9103 /// declarations visible to be ambiguous in some cases (this happens when using
9104 /// a modularized libstdc++).
9105 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9106                                                   const NamedDecl *B) {
9107   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9108   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9109   if (!VA || !VB)
9110     return false;
9111
9112   // The declarations must be declaring the same name as an internal linkage
9113   // entity in different modules.
9114   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9115           VB->getDeclContext()->getRedeclContext()) ||
9116       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9117           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9118       VA->isExternallyVisible() || VB->isExternallyVisible())
9119     return false;
9120
9121   // Check that the declarations appear to be equivalent.
9122   //
9123   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9124   // For constants and functions, we should check the initializer or body is
9125   // the same. For non-constant variables, we shouldn't allow it at all.
9126   if (Context.hasSameType(VA->getType(), VB->getType()))
9127     return true;
9128
9129   // Enum constants within unnamed enumerations will have different types, but
9130   // may still be similar enough to be interchangeable for our purposes.
9131   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9132     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9133       // Only handle anonymous enums. If the enumerations were named and
9134       // equivalent, they would have been merged to the same type.
9135       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9136       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9137       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9138           !Context.hasSameType(EnumA->getIntegerType(),
9139                                EnumB->getIntegerType()))
9140         return false;
9141       // Allow this only if the value is the same for both enumerators.
9142       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9143     }
9144   }
9145
9146   // Nothing else is sufficiently similar.
9147   return false;
9148 }
9149
9150 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9151     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9152   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9153
9154   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9155   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9156       << !M << (M ? M->getFullModuleName() : "");
9157
9158   for (auto *E : Equiv) {
9159     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9160     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9161         << !M << (M ? M->getFullModuleName() : "");
9162   }
9163 }
9164
9165 /// \brief Computes the best viable function (C++ 13.3.3)
9166 /// within an overload candidate set.
9167 ///
9168 /// \param Loc The location of the function name (or operator symbol) for
9169 /// which overload resolution occurs.
9170 ///
9171 /// \param Best If overload resolution was successful or found a deleted
9172 /// function, \p Best points to the candidate function found.
9173 ///
9174 /// \returns The result of overload resolution.
9175 OverloadingResult
9176 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9177                                          iterator &Best,
9178                                          bool UserDefinedConversion) {
9179   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9180   std::transform(begin(), end(), std::back_inserter(Candidates),
9181                  [](OverloadCandidate &Cand) { return &Cand; });
9182
9183   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9184   // are accepted by both clang and NVCC. However, during a particular
9185   // compilation mode only one call variant is viable. We need to
9186   // exclude non-viable overload candidates from consideration based
9187   // only on their host/device attributes. Specifically, if one
9188   // candidate call is WrongSide and the other is SameSide, we ignore
9189   // the WrongSide candidate.
9190   if (S.getLangOpts().CUDA) {
9191     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9192     bool ContainsSameSideCandidate =
9193         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9194           return Cand->Function &&
9195                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9196                      Sema::CFP_SameSide;
9197         });
9198     if (ContainsSameSideCandidate) {
9199       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9200         return Cand->Function &&
9201                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9202                    Sema::CFP_WrongSide;
9203       };
9204       llvm::erase_if(Candidates, IsWrongSideCandidate);
9205     }
9206   }
9207
9208   // Find the best viable function.
9209   Best = end();
9210   for (auto *Cand : Candidates)
9211     if (Cand->Viable)
9212       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
9213                                                      UserDefinedConversion))
9214         Best = Cand;
9215
9216   // If we didn't find any viable functions, abort.
9217   if (Best == end())
9218     return OR_No_Viable_Function;
9219
9220   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9221
9222   // Make sure that this function is better than every other viable
9223   // function. If not, we have an ambiguity.
9224   for (auto *Cand : Candidates) {
9225     if (Cand->Viable &&
9226         Cand != Best &&
9227         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
9228                                    UserDefinedConversion)) {
9229       if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9230                                                    Cand->Function)) {
9231         EquivalentCands.push_back(Cand->Function);
9232         continue;
9233       }
9234
9235       Best = end();
9236       return OR_Ambiguous;
9237     }
9238   }
9239
9240   // Best is the best viable function.
9241   if (Best->Function &&
9242       (Best->Function->isDeleted() ||
9243        S.isFunctionConsideredUnavailable(Best->Function)))
9244     return OR_Deleted;
9245
9246   if (!EquivalentCands.empty())
9247     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9248                                                     EquivalentCands);
9249
9250   return OR_Success;
9251 }
9252
9253 namespace {
9254
9255 enum OverloadCandidateKind {
9256   oc_function,
9257   oc_method,
9258   oc_constructor,
9259   oc_function_template,
9260   oc_method_template,
9261   oc_constructor_template,
9262   oc_implicit_default_constructor,
9263   oc_implicit_copy_constructor,
9264   oc_implicit_move_constructor,
9265   oc_implicit_copy_assignment,
9266   oc_implicit_move_assignment,
9267   oc_inherited_constructor,
9268   oc_inherited_constructor_template
9269 };
9270
9271 static OverloadCandidateKind
9272 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9273                           std::string &Description) {
9274   bool isTemplate = false;
9275
9276   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9277     isTemplate = true;
9278     Description = S.getTemplateArgumentBindingsText(
9279       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9280   }
9281
9282   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9283     if (!Ctor->isImplicit()) {
9284       if (isa<ConstructorUsingShadowDecl>(Found))
9285         return isTemplate ? oc_inherited_constructor_template
9286                           : oc_inherited_constructor;
9287       else
9288         return isTemplate ? oc_constructor_template : oc_constructor;
9289     }
9290
9291     if (Ctor->isDefaultConstructor())
9292       return oc_implicit_default_constructor;
9293
9294     if (Ctor->isMoveConstructor())
9295       return oc_implicit_move_constructor;
9296
9297     assert(Ctor->isCopyConstructor() &&
9298            "unexpected sort of implicit constructor");
9299     return oc_implicit_copy_constructor;
9300   }
9301
9302   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9303     // This actually gets spelled 'candidate function' for now, but
9304     // it doesn't hurt to split it out.
9305     if (!Meth->isImplicit())
9306       return isTemplate ? oc_method_template : oc_method;
9307
9308     if (Meth->isMoveAssignmentOperator())
9309       return oc_implicit_move_assignment;
9310
9311     if (Meth->isCopyAssignmentOperator())
9312       return oc_implicit_copy_assignment;
9313
9314     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9315     return oc_method;
9316   }
9317
9318   return isTemplate ? oc_function_template : oc_function;
9319 }
9320
9321 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9322   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9323   // set.
9324   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9325     S.Diag(FoundDecl->getLocation(),
9326            diag::note_ovl_candidate_inherited_constructor)
9327       << Shadow->getNominatedBaseClass();
9328 }
9329
9330 } // end anonymous namespace
9331
9332 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9333                                     const FunctionDecl *FD) {
9334   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9335     bool AlwaysTrue;
9336     if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9337       return false;
9338     if (!AlwaysTrue)
9339       return false;
9340   }
9341   return true;
9342 }
9343
9344 /// \brief Returns true if we can take the address of the function.
9345 ///
9346 /// \param Complain - If true, we'll emit a diagnostic
9347 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9348 ///   we in overload resolution?
9349 /// \param Loc - The location of the statement we're complaining about. Ignored
9350 ///   if we're not complaining, or if we're in overload resolution.
9351 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9352                                               bool Complain,
9353                                               bool InOverloadResolution,
9354                                               SourceLocation Loc) {
9355   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9356     if (Complain) {
9357       if (InOverloadResolution)
9358         S.Diag(FD->getLocStart(),
9359                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9360       else
9361         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9362     }
9363     return false;
9364   }
9365
9366   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9367     return P->hasAttr<PassObjectSizeAttr>();
9368   });
9369   if (I == FD->param_end())
9370     return true;
9371
9372   if (Complain) {
9373     // Add one to ParamNo because it's user-facing
9374     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9375     if (InOverloadResolution)
9376       S.Diag(FD->getLocation(),
9377              diag::note_ovl_candidate_has_pass_object_size_params)
9378           << ParamNo;
9379     else
9380       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9381           << FD << ParamNo;
9382   }
9383   return false;
9384 }
9385
9386 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9387                                                const FunctionDecl *FD) {
9388   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9389                                            /*InOverloadResolution=*/true,
9390                                            /*Loc=*/SourceLocation());
9391 }
9392
9393 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9394                                              bool Complain,
9395                                              SourceLocation Loc) {
9396   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9397                                              /*InOverloadResolution=*/false,
9398                                              Loc);
9399 }
9400
9401 // Notes the location of an overload candidate.
9402 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9403                                  QualType DestType, bool TakingAddress) {
9404   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9405     return;
9406
9407   std::string FnDesc;
9408   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9409   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9410                              << (unsigned) K << Fn << FnDesc;
9411
9412   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9413   Diag(Fn->getLocation(), PD);
9414   MaybeEmitInheritedConstructorNote(*this, Found);
9415 }
9416
9417 // Notes the location of all overload candidates designated through
9418 // OverloadedExpr
9419 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9420                                      bool TakingAddress) {
9421   assert(OverloadedExpr->getType() == Context.OverloadTy);
9422
9423   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9424   OverloadExpr *OvlExpr = Ovl.Expression;
9425
9426   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9427                             IEnd = OvlExpr->decls_end();
9428        I != IEnd; ++I) {
9429     if (FunctionTemplateDecl *FunTmpl =
9430                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9431       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9432                             TakingAddress);
9433     } else if (FunctionDecl *Fun
9434                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9435       NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9436     }
9437   }
9438 }
9439
9440 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9441 /// "lead" diagnostic; it will be given two arguments, the source and
9442 /// target types of the conversion.
9443 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9444                                  Sema &S,
9445                                  SourceLocation CaretLoc,
9446                                  const PartialDiagnostic &PDiag) const {
9447   S.Diag(CaretLoc, PDiag)
9448     << Ambiguous.getFromType() << Ambiguous.getToType();
9449   // FIXME: The note limiting machinery is borrowed from
9450   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9451   // refactoring here.
9452   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9453   unsigned CandsShown = 0;
9454   AmbiguousConversionSequence::const_iterator I, E;
9455   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9456     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9457       break;
9458     ++CandsShown;
9459     S.NoteOverloadCandidate(I->first, I->second);
9460   }
9461   if (I != E)
9462     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9463 }
9464
9465 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9466                                   unsigned I, bool TakingCandidateAddress) {
9467   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9468   assert(Conv.isBad());
9469   assert(Cand->Function && "for now, candidate must be a function");
9470   FunctionDecl *Fn = Cand->Function;
9471
9472   // There's a conversion slot for the object argument if this is a
9473   // non-constructor method.  Note that 'I' corresponds the
9474   // conversion-slot index.
9475   bool isObjectArgument = false;
9476   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9477     if (I == 0)
9478       isObjectArgument = true;
9479     else
9480       I--;
9481   }
9482
9483   std::string FnDesc;
9484   OverloadCandidateKind FnKind =
9485       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9486
9487   Expr *FromExpr = Conv.Bad.FromExpr;
9488   QualType FromTy = Conv.Bad.getFromType();
9489   QualType ToTy = Conv.Bad.getToType();
9490
9491   if (FromTy == S.Context.OverloadTy) {
9492     assert(FromExpr && "overload set argument came from implicit argument?");
9493     Expr *E = FromExpr->IgnoreParens();
9494     if (isa<UnaryOperator>(E))
9495       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9496     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9497
9498     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9499       << (unsigned) FnKind << FnDesc
9500       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9501       << ToTy << Name << I+1;
9502     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9503     return;
9504   }
9505
9506   // Do some hand-waving analysis to see if the non-viability is due
9507   // to a qualifier mismatch.
9508   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9509   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9510   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9511     CToTy = RT->getPointeeType();
9512   else {
9513     // TODO: detect and diagnose the full richness of const mismatches.
9514     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9515       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9516         CFromTy = FromPT->getPointeeType();
9517         CToTy = ToPT->getPointeeType();
9518       }
9519   }
9520
9521   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9522       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9523     Qualifiers FromQs = CFromTy.getQualifiers();
9524     Qualifiers ToQs = CToTy.getQualifiers();
9525
9526     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9527       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9528         << (unsigned) FnKind << FnDesc
9529         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9530         << FromTy
9531         << FromQs.getAddressSpaceAttributePrintValue()
9532         << ToQs.getAddressSpaceAttributePrintValue()
9533         << (unsigned) isObjectArgument << I+1;
9534       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9535       return;
9536     }
9537
9538     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9539       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9540         << (unsigned) FnKind << FnDesc
9541         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9542         << FromTy
9543         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9544         << (unsigned) isObjectArgument << I+1;
9545       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9546       return;
9547     }
9548
9549     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9550       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9551       << (unsigned) FnKind << FnDesc
9552       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9553       << FromTy
9554       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9555       << (unsigned) isObjectArgument << I+1;
9556       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9557       return;
9558     }
9559
9560     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9561       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9562         << (unsigned) FnKind << FnDesc
9563         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9564         << FromTy << FromQs.hasUnaligned() << I+1;
9565       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9566       return;
9567     }
9568
9569     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9570     assert(CVR && "unexpected qualifiers mismatch");
9571
9572     if (isObjectArgument) {
9573       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9574         << (unsigned) FnKind << FnDesc
9575         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9576         << FromTy << (CVR - 1);
9577     } else {
9578       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9579         << (unsigned) FnKind << FnDesc
9580         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9581         << FromTy << (CVR - 1) << I+1;
9582     }
9583     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9584     return;
9585   }
9586
9587   // Special diagnostic for failure to convert an initializer list, since
9588   // telling the user that it has type void is not useful.
9589   if (FromExpr && isa<InitListExpr>(FromExpr)) {
9590     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9591       << (unsigned) FnKind << FnDesc
9592       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9593       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9594     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9595     return;
9596   }
9597
9598   // Diagnose references or pointers to incomplete types differently,
9599   // since it's far from impossible that the incompleteness triggered
9600   // the failure.
9601   QualType TempFromTy = FromTy.getNonReferenceType();
9602   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9603     TempFromTy = PTy->getPointeeType();
9604   if (TempFromTy->isIncompleteType()) {
9605     // Emit the generic diagnostic and, optionally, add the hints to it.
9606     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9607       << (unsigned) FnKind << FnDesc
9608       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9609       << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9610       << (unsigned) (Cand->Fix.Kind);
9611
9612     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9613     return;
9614   }
9615
9616   // Diagnose base -> derived pointer conversions.
9617   unsigned BaseToDerivedConversion = 0;
9618   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9619     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9620       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9621                                                FromPtrTy->getPointeeType()) &&
9622           !FromPtrTy->getPointeeType()->isIncompleteType() &&
9623           !ToPtrTy->getPointeeType()->isIncompleteType() &&
9624           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9625                           FromPtrTy->getPointeeType()))
9626         BaseToDerivedConversion = 1;
9627     }
9628   } else if (const ObjCObjectPointerType *FromPtrTy
9629                                     = FromTy->getAs<ObjCObjectPointerType>()) {
9630     if (const ObjCObjectPointerType *ToPtrTy
9631                                         = ToTy->getAs<ObjCObjectPointerType>())
9632       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9633         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9634           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9635                                                 FromPtrTy->getPointeeType()) &&
9636               FromIface->isSuperClassOf(ToIface))
9637             BaseToDerivedConversion = 2;
9638   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9639     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9640         !FromTy->isIncompleteType() &&
9641         !ToRefTy->getPointeeType()->isIncompleteType() &&
9642         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9643       BaseToDerivedConversion = 3;
9644     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9645                ToTy.getNonReferenceType().getCanonicalType() ==
9646                FromTy.getNonReferenceType().getCanonicalType()) {
9647       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9648         << (unsigned) FnKind << FnDesc
9649         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9650         << (unsigned) isObjectArgument << I + 1;
9651       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9652       return;
9653     }
9654   }
9655
9656   if (BaseToDerivedConversion) {
9657     S.Diag(Fn->getLocation(),
9658            diag::note_ovl_candidate_bad_base_to_derived_conv)
9659       << (unsigned) FnKind << FnDesc
9660       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9661       << (BaseToDerivedConversion - 1)
9662       << FromTy << ToTy << I+1;
9663     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9664     return;
9665   }
9666
9667   if (isa<ObjCObjectPointerType>(CFromTy) &&
9668       isa<PointerType>(CToTy)) {
9669       Qualifiers FromQs = CFromTy.getQualifiers();
9670       Qualifiers ToQs = CToTy.getQualifiers();
9671       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9672         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9673         << (unsigned) FnKind << FnDesc
9674         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9675         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9676         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9677         return;
9678       }
9679   }
9680
9681   if (TakingCandidateAddress &&
9682       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9683     return;
9684
9685   // Emit the generic diagnostic and, optionally, add the hints to it.
9686   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9687   FDiag << (unsigned) FnKind << FnDesc
9688     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9689     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9690     << (unsigned) (Cand->Fix.Kind);
9691
9692   // If we can fix the conversion, suggest the FixIts.
9693   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9694        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9695     FDiag << *HI;
9696   S.Diag(Fn->getLocation(), FDiag);
9697
9698   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9699 }
9700
9701 /// Additional arity mismatch diagnosis specific to a function overload
9702 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9703 /// over a candidate in any candidate set.
9704 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9705                                unsigned NumArgs) {
9706   FunctionDecl *Fn = Cand->Function;
9707   unsigned MinParams = Fn->getMinRequiredArguments();
9708
9709   // With invalid overloaded operators, it's possible that we think we
9710   // have an arity mismatch when in fact it looks like we have the
9711   // right number of arguments, because only overloaded operators have
9712   // the weird behavior of overloading member and non-member functions.
9713   // Just don't report anything.
9714   if (Fn->isInvalidDecl() &&
9715       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9716     return true;
9717
9718   if (NumArgs < MinParams) {
9719     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9720            (Cand->FailureKind == ovl_fail_bad_deduction &&
9721             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9722   } else {
9723     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9724            (Cand->FailureKind == ovl_fail_bad_deduction &&
9725             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9726   }
9727
9728   return false;
9729 }
9730
9731 /// General arity mismatch diagnosis over a candidate in a candidate set.
9732 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9733                                   unsigned NumFormalArgs) {
9734   assert(isa<FunctionDecl>(D) &&
9735       "The templated declaration should at least be a function"
9736       " when diagnosing bad template argument deduction due to too many"
9737       " or too few arguments");
9738
9739   FunctionDecl *Fn = cast<FunctionDecl>(D);
9740
9741   // TODO: treat calls to a missing default constructor as a special case
9742   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9743   unsigned MinParams = Fn->getMinRequiredArguments();
9744
9745   // at least / at most / exactly
9746   unsigned mode, modeCount;
9747   if (NumFormalArgs < MinParams) {
9748     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9749         FnTy->isTemplateVariadic())
9750       mode = 0; // "at least"
9751     else
9752       mode = 2; // "exactly"
9753     modeCount = MinParams;
9754   } else {
9755     if (MinParams != FnTy->getNumParams())
9756       mode = 1; // "at most"
9757     else
9758       mode = 2; // "exactly"
9759     modeCount = FnTy->getNumParams();
9760   }
9761
9762   std::string Description;
9763   OverloadCandidateKind FnKind =
9764       ClassifyOverloadCandidate(S, Found, Fn, Description);
9765
9766   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9767     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9768       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9769       << mode << Fn->getParamDecl(0) << NumFormalArgs;
9770   else
9771     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9772       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9773       << mode << modeCount << NumFormalArgs;
9774   MaybeEmitInheritedConstructorNote(S, Found);
9775 }
9776
9777 /// Arity mismatch diagnosis specific to a function overload candidate.
9778 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9779                                   unsigned NumFormalArgs) {
9780   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9781     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9782 }
9783
9784 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9785   if (TemplateDecl *TD = Templated->getDescribedTemplate())
9786     return TD;
9787   llvm_unreachable("Unsupported: Getting the described template declaration"
9788                    " for bad deduction diagnosis");
9789 }
9790
9791 /// Diagnose a failed template-argument deduction.
9792 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9793                                  DeductionFailureInfo &DeductionFailure,
9794                                  unsigned NumArgs,
9795                                  bool TakingCandidateAddress) {
9796   TemplateParameter Param = DeductionFailure.getTemplateParameter();
9797   NamedDecl *ParamD;
9798   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9799   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9800   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9801   switch (DeductionFailure.Result) {
9802   case Sema::TDK_Success:
9803     llvm_unreachable("TDK_success while diagnosing bad deduction");
9804
9805   case Sema::TDK_Incomplete: {
9806     assert(ParamD && "no parameter found for incomplete deduction result");
9807     S.Diag(Templated->getLocation(),
9808            diag::note_ovl_candidate_incomplete_deduction)
9809         << ParamD->getDeclName();
9810     MaybeEmitInheritedConstructorNote(S, Found);
9811     return;
9812   }
9813
9814   case Sema::TDK_Underqualified: {
9815     assert(ParamD && "no parameter found for bad qualifiers deduction result");
9816     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9817
9818     QualType Param = DeductionFailure.getFirstArg()->getAsType();
9819
9820     // Param will have been canonicalized, but it should just be a
9821     // qualified version of ParamD, so move the qualifiers to that.
9822     QualifierCollector Qs;
9823     Qs.strip(Param);
9824     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9825     assert(S.Context.hasSameType(Param, NonCanonParam));
9826
9827     // Arg has also been canonicalized, but there's nothing we can do
9828     // about that.  It also doesn't matter as much, because it won't
9829     // have any template parameters in it (because deduction isn't
9830     // done on dependent types).
9831     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9832
9833     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9834         << ParamD->getDeclName() << Arg << NonCanonParam;
9835     MaybeEmitInheritedConstructorNote(S, Found);
9836     return;
9837   }
9838
9839   case Sema::TDK_Inconsistent: {
9840     assert(ParamD && "no parameter found for inconsistent deduction result");
9841     int which = 0;
9842     if (isa<TemplateTypeParmDecl>(ParamD))
9843       which = 0;
9844     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9845       // Deduction might have failed because we deduced arguments of two
9846       // different types for a non-type template parameter.
9847       // FIXME: Use a different TDK value for this.
9848       QualType T1 =
9849           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9850       QualType T2 =
9851           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9852       if (!S.Context.hasSameType(T1, T2)) {
9853         S.Diag(Templated->getLocation(),
9854                diag::note_ovl_candidate_inconsistent_deduction_types)
9855           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9856           << *DeductionFailure.getSecondArg() << T2;
9857         MaybeEmitInheritedConstructorNote(S, Found);
9858         return;
9859       }
9860
9861       which = 1;
9862     } else {
9863       which = 2;
9864     }
9865
9866     S.Diag(Templated->getLocation(),
9867            diag::note_ovl_candidate_inconsistent_deduction)
9868         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9869         << *DeductionFailure.getSecondArg();
9870     MaybeEmitInheritedConstructorNote(S, Found);
9871     return;
9872   }
9873
9874   case Sema::TDK_InvalidExplicitArguments:
9875     assert(ParamD && "no parameter found for invalid explicit arguments");
9876     if (ParamD->getDeclName())
9877       S.Diag(Templated->getLocation(),
9878              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9879           << ParamD->getDeclName();
9880     else {
9881       int index = 0;
9882       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9883         index = TTP->getIndex();
9884       else if (NonTypeTemplateParmDecl *NTTP
9885                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9886         index = NTTP->getIndex();
9887       else
9888         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9889       S.Diag(Templated->getLocation(),
9890              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9891           << (index + 1);
9892     }
9893     MaybeEmitInheritedConstructorNote(S, Found);
9894     return;
9895
9896   case Sema::TDK_TooManyArguments:
9897   case Sema::TDK_TooFewArguments:
9898     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9899     return;
9900
9901   case Sema::TDK_InstantiationDepth:
9902     S.Diag(Templated->getLocation(),
9903            diag::note_ovl_candidate_instantiation_depth);
9904     MaybeEmitInheritedConstructorNote(S, Found);
9905     return;
9906
9907   case Sema::TDK_SubstitutionFailure: {
9908     // Format the template argument list into the argument string.
9909     SmallString<128> TemplateArgString;
9910     if (TemplateArgumentList *Args =
9911             DeductionFailure.getTemplateArgumentList()) {
9912       TemplateArgString = " ";
9913       TemplateArgString += S.getTemplateArgumentBindingsText(
9914           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9915     }
9916
9917     // If this candidate was disabled by enable_if, say so.
9918     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9919     if (PDiag && PDiag->second.getDiagID() ==
9920           diag::err_typename_nested_not_found_enable_if) {
9921       // FIXME: Use the source range of the condition, and the fully-qualified
9922       //        name of the enable_if template. These are both present in PDiag.
9923       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9924         << "'enable_if'" << TemplateArgString;
9925       return;
9926     }
9927
9928     // Format the SFINAE diagnostic into the argument string.
9929     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9930     //        formatted message in another diagnostic.
9931     SmallString<128> SFINAEArgString;
9932     SourceRange R;
9933     if (PDiag) {
9934       SFINAEArgString = ": ";
9935       R = SourceRange(PDiag->first, PDiag->first);
9936       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9937     }
9938
9939     S.Diag(Templated->getLocation(),
9940            diag::note_ovl_candidate_substitution_failure)
9941         << TemplateArgString << SFINAEArgString << R;
9942     MaybeEmitInheritedConstructorNote(S, Found);
9943     return;
9944   }
9945
9946   case Sema::TDK_DeducedMismatch:
9947   case Sema::TDK_DeducedMismatchNested: {
9948     // Format the template argument list into the argument string.
9949     SmallString<128> TemplateArgString;
9950     if (TemplateArgumentList *Args =
9951             DeductionFailure.getTemplateArgumentList()) {
9952       TemplateArgString = " ";
9953       TemplateArgString += S.getTemplateArgumentBindingsText(
9954           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9955     }
9956
9957     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9958         << (*DeductionFailure.getCallArgIndex() + 1)
9959         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9960         << TemplateArgString
9961         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9962     break;
9963   }
9964
9965   case Sema::TDK_NonDeducedMismatch: {
9966     // FIXME: Provide a source location to indicate what we couldn't match.
9967     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9968     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9969     if (FirstTA.getKind() == TemplateArgument::Template &&
9970         SecondTA.getKind() == TemplateArgument::Template) {
9971       TemplateName FirstTN = FirstTA.getAsTemplate();
9972       TemplateName SecondTN = SecondTA.getAsTemplate();
9973       if (FirstTN.getKind() == TemplateName::Template &&
9974           SecondTN.getKind() == TemplateName::Template) {
9975         if (FirstTN.getAsTemplateDecl()->getName() ==
9976             SecondTN.getAsTemplateDecl()->getName()) {
9977           // FIXME: This fixes a bad diagnostic where both templates are named
9978           // the same.  This particular case is a bit difficult since:
9979           // 1) It is passed as a string to the diagnostic printer.
9980           // 2) The diagnostic printer only attempts to find a better
9981           //    name for types, not decls.
9982           // Ideally, this should folded into the diagnostic printer.
9983           S.Diag(Templated->getLocation(),
9984                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9985               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9986           return;
9987         }
9988       }
9989     }
9990
9991     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9992         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9993       return;
9994
9995     // FIXME: For generic lambda parameters, check if the function is a lambda
9996     // call operator, and if so, emit a prettier and more informative
9997     // diagnostic that mentions 'auto' and lambda in addition to
9998     // (or instead of?) the canonical template type parameters.
9999     S.Diag(Templated->getLocation(),
10000            diag::note_ovl_candidate_non_deduced_mismatch)
10001         << FirstTA << SecondTA;
10002     return;
10003   }
10004   // TODO: diagnose these individually, then kill off
10005   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10006   case Sema::TDK_MiscellaneousDeductionFailure:
10007     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10008     MaybeEmitInheritedConstructorNote(S, Found);
10009     return;
10010   case Sema::TDK_CUDATargetMismatch:
10011     S.Diag(Templated->getLocation(),
10012            diag::note_cuda_ovl_candidate_target_mismatch);
10013     return;
10014   }
10015 }
10016
10017 /// Diagnose a failed template-argument deduction, for function calls.
10018 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10019                                  unsigned NumArgs,
10020                                  bool TakingCandidateAddress) {
10021   unsigned TDK = Cand->DeductionFailure.Result;
10022   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10023     if (CheckArityMismatch(S, Cand, NumArgs))
10024       return;
10025   }
10026   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10027                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10028 }
10029
10030 /// CUDA: diagnose an invalid call across targets.
10031 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10032   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10033   FunctionDecl *Callee = Cand->Function;
10034
10035   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10036                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10037
10038   std::string FnDesc;
10039   OverloadCandidateKind FnKind =
10040       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10041
10042   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10043       << (unsigned)FnKind << CalleeTarget << CallerTarget;
10044
10045   // This could be an implicit constructor for which we could not infer the
10046   // target due to a collsion. Diagnose that case.
10047   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10048   if (Meth != nullptr && Meth->isImplicit()) {
10049     CXXRecordDecl *ParentClass = Meth->getParent();
10050     Sema::CXXSpecialMember CSM;
10051
10052     switch (FnKind) {
10053     default:
10054       return;
10055     case oc_implicit_default_constructor:
10056       CSM = Sema::CXXDefaultConstructor;
10057       break;
10058     case oc_implicit_copy_constructor:
10059       CSM = Sema::CXXCopyConstructor;
10060       break;
10061     case oc_implicit_move_constructor:
10062       CSM = Sema::CXXMoveConstructor;
10063       break;
10064     case oc_implicit_copy_assignment:
10065       CSM = Sema::CXXCopyAssignment;
10066       break;
10067     case oc_implicit_move_assignment:
10068       CSM = Sema::CXXMoveAssignment;
10069       break;
10070     };
10071
10072     bool ConstRHS = false;
10073     if (Meth->getNumParams()) {
10074       if (const ReferenceType *RT =
10075               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10076         ConstRHS = RT->getPointeeType().isConstQualified();
10077       }
10078     }
10079
10080     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10081                                               /* ConstRHS */ ConstRHS,
10082                                               /* Diagnose */ true);
10083   }
10084 }
10085
10086 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10087   FunctionDecl *Callee = Cand->Function;
10088   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10089
10090   S.Diag(Callee->getLocation(),
10091          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10092       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10093 }
10094
10095 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10096   FunctionDecl *Callee = Cand->Function;
10097
10098   S.Diag(Callee->getLocation(),
10099          diag::note_ovl_candidate_disabled_by_extension);
10100 }
10101
10102 /// Generates a 'note' diagnostic for an overload candidate.  We've
10103 /// already generated a primary error at the call site.
10104 ///
10105 /// It really does need to be a single diagnostic with its caret
10106 /// pointed at the candidate declaration.  Yes, this creates some
10107 /// major challenges of technical writing.  Yes, this makes pointing
10108 /// out problems with specific arguments quite awkward.  It's still
10109 /// better than generating twenty screens of text for every failed
10110 /// overload.
10111 ///
10112 /// It would be great to be able to express per-candidate problems
10113 /// more richly for those diagnostic clients that cared, but we'd
10114 /// still have to be just as careful with the default diagnostics.
10115 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10116                                   unsigned NumArgs,
10117                                   bool TakingCandidateAddress) {
10118   FunctionDecl *Fn = Cand->Function;
10119
10120   // Note deleted candidates, but only if they're viable.
10121   if (Cand->Viable) {
10122     if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10123       std::string FnDesc;
10124       OverloadCandidateKind FnKind =
10125         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10126
10127       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10128         << FnKind << FnDesc
10129         << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10130       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10131       return;
10132     }
10133
10134     // We don't really have anything else to say about viable candidates.
10135     S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10136     return;
10137   }
10138
10139   switch (Cand->FailureKind) {
10140   case ovl_fail_too_many_arguments:
10141   case ovl_fail_too_few_arguments:
10142     return DiagnoseArityMismatch(S, Cand, NumArgs);
10143
10144   case ovl_fail_bad_deduction:
10145     return DiagnoseBadDeduction(S, Cand, NumArgs,
10146                                 TakingCandidateAddress);
10147
10148   case ovl_fail_illegal_constructor: {
10149     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10150       << (Fn->getPrimaryTemplate() ? 1 : 0);
10151     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10152     return;
10153   }
10154
10155   case ovl_fail_trivial_conversion:
10156   case ovl_fail_bad_final_conversion:
10157   case ovl_fail_final_conversion_not_exact:
10158     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10159
10160   case ovl_fail_bad_conversion: {
10161     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10162     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10163       if (Cand->Conversions[I].isBad())
10164         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10165
10166     // FIXME: this currently happens when we're called from SemaInit
10167     // when user-conversion overload fails.  Figure out how to handle
10168     // those conditions and diagnose them well.
10169     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10170   }
10171
10172   case ovl_fail_bad_target:
10173     return DiagnoseBadTarget(S, Cand);
10174
10175   case ovl_fail_enable_if:
10176     return DiagnoseFailedEnableIfAttr(S, Cand);
10177
10178   case ovl_fail_ext_disabled:
10179     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10180
10181   case ovl_fail_inhctor_slice:
10182     // It's generally not interesting to note copy/move constructors here.
10183     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10184       return;
10185     S.Diag(Fn->getLocation(),
10186            diag::note_ovl_candidate_inherited_constructor_slice)
10187       << (Fn->getPrimaryTemplate() ? 1 : 0)
10188       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10189     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10190     return;
10191
10192   case ovl_fail_addr_not_available: {
10193     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10194     (void)Available;
10195     assert(!Available);
10196     break;
10197   }
10198   }
10199 }
10200
10201 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10202   // Desugar the type of the surrogate down to a function type,
10203   // retaining as many typedefs as possible while still showing
10204   // the function type (and, therefore, its parameter types).
10205   QualType FnType = Cand->Surrogate->getConversionType();
10206   bool isLValueReference = false;
10207   bool isRValueReference = false;
10208   bool isPointer = false;
10209   if (const LValueReferenceType *FnTypeRef =
10210         FnType->getAs<LValueReferenceType>()) {
10211     FnType = FnTypeRef->getPointeeType();
10212     isLValueReference = true;
10213   } else if (const RValueReferenceType *FnTypeRef =
10214                FnType->getAs<RValueReferenceType>()) {
10215     FnType = FnTypeRef->getPointeeType();
10216     isRValueReference = true;
10217   }
10218   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10219     FnType = FnTypePtr->getPointeeType();
10220     isPointer = true;
10221   }
10222   // Desugar down to a function type.
10223   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10224   // Reconstruct the pointer/reference as appropriate.
10225   if (isPointer) FnType = S.Context.getPointerType(FnType);
10226   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10227   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10228
10229   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10230     << FnType;
10231 }
10232
10233 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10234                                          SourceLocation OpLoc,
10235                                          OverloadCandidate *Cand) {
10236   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10237   std::string TypeStr("operator");
10238   TypeStr += Opc;
10239   TypeStr += "(";
10240   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
10241   if (Cand->Conversions.size() == 1) {
10242     TypeStr += ")";
10243     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10244   } else {
10245     TypeStr += ", ";
10246     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10247     TypeStr += ")";
10248     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10249   }
10250 }
10251
10252 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10253                                          OverloadCandidate *Cand) {
10254   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10255     if (ICS.isBad()) break; // all meaningless after first invalid
10256     if (!ICS.isAmbiguous()) continue;
10257
10258     ICS.DiagnoseAmbiguousConversion(
10259         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10260   }
10261 }
10262
10263 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10264   if (Cand->Function)
10265     return Cand->Function->getLocation();
10266   if (Cand->IsSurrogate)
10267     return Cand->Surrogate->getLocation();
10268   return SourceLocation();
10269 }
10270
10271 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10272   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10273   case Sema::TDK_Success:
10274   case Sema::TDK_NonDependentConversionFailure:
10275     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10276
10277   case Sema::TDK_Invalid:
10278   case Sema::TDK_Incomplete:
10279     return 1;
10280
10281   case Sema::TDK_Underqualified:
10282   case Sema::TDK_Inconsistent:
10283     return 2;
10284
10285   case Sema::TDK_SubstitutionFailure:
10286   case Sema::TDK_DeducedMismatch:
10287   case Sema::TDK_DeducedMismatchNested:
10288   case Sema::TDK_NonDeducedMismatch:
10289   case Sema::TDK_MiscellaneousDeductionFailure:
10290   case Sema::TDK_CUDATargetMismatch:
10291     return 3;
10292
10293   case Sema::TDK_InstantiationDepth:
10294     return 4;
10295
10296   case Sema::TDK_InvalidExplicitArguments:
10297     return 5;
10298
10299   case Sema::TDK_TooManyArguments:
10300   case Sema::TDK_TooFewArguments:
10301     return 6;
10302   }
10303   llvm_unreachable("Unhandled deduction result");
10304 }
10305
10306 namespace {
10307 struct CompareOverloadCandidatesForDisplay {
10308   Sema &S;
10309   SourceLocation Loc;
10310   size_t NumArgs;
10311
10312   CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
10313       : S(S), NumArgs(nArgs) {}
10314
10315   bool operator()(const OverloadCandidate *L,
10316                   const OverloadCandidate *R) {
10317     // Fast-path this check.
10318     if (L == R) return false;
10319
10320     // Order first by viability.
10321     if (L->Viable) {
10322       if (!R->Viable) return true;
10323
10324       // TODO: introduce a tri-valued comparison for overload
10325       // candidates.  Would be more worthwhile if we had a sort
10326       // that could exploit it.
10327       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10328       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10329     } else if (R->Viable)
10330       return false;
10331
10332     assert(L->Viable == R->Viable);
10333
10334     // Criteria by which we can sort non-viable candidates:
10335     if (!L->Viable) {
10336       // 1. Arity mismatches come after other candidates.
10337       if (L->FailureKind == ovl_fail_too_many_arguments ||
10338           L->FailureKind == ovl_fail_too_few_arguments) {
10339         if (R->FailureKind == ovl_fail_too_many_arguments ||
10340             R->FailureKind == ovl_fail_too_few_arguments) {
10341           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10342           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10343           if (LDist == RDist) {
10344             if (L->FailureKind == R->FailureKind)
10345               // Sort non-surrogates before surrogates.
10346               return !L->IsSurrogate && R->IsSurrogate;
10347             // Sort candidates requiring fewer parameters than there were
10348             // arguments given after candidates requiring more parameters
10349             // than there were arguments given.
10350             return L->FailureKind == ovl_fail_too_many_arguments;
10351           }
10352           return LDist < RDist;
10353         }
10354         return false;
10355       }
10356       if (R->FailureKind == ovl_fail_too_many_arguments ||
10357           R->FailureKind == ovl_fail_too_few_arguments)
10358         return true;
10359
10360       // 2. Bad conversions come first and are ordered by the number
10361       // of bad conversions and quality of good conversions.
10362       if (L->FailureKind == ovl_fail_bad_conversion) {
10363         if (R->FailureKind != ovl_fail_bad_conversion)
10364           return true;
10365
10366         // The conversion that can be fixed with a smaller number of changes,
10367         // comes first.
10368         unsigned numLFixes = L->Fix.NumConversionsFixed;
10369         unsigned numRFixes = R->Fix.NumConversionsFixed;
10370         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10371         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10372         if (numLFixes != numRFixes) {
10373           return numLFixes < numRFixes;
10374         }
10375
10376         // If there's any ordering between the defined conversions...
10377         // FIXME: this might not be transitive.
10378         assert(L->Conversions.size() == R->Conversions.size());
10379
10380         int leftBetter = 0;
10381         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10382         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10383           switch (CompareImplicitConversionSequences(S, Loc,
10384                                                      L->Conversions[I],
10385                                                      R->Conversions[I])) {
10386           case ImplicitConversionSequence::Better:
10387             leftBetter++;
10388             break;
10389
10390           case ImplicitConversionSequence::Worse:
10391             leftBetter--;
10392             break;
10393
10394           case ImplicitConversionSequence::Indistinguishable:
10395             break;
10396           }
10397         }
10398         if (leftBetter > 0) return true;
10399         if (leftBetter < 0) return false;
10400
10401       } else if (R->FailureKind == ovl_fail_bad_conversion)
10402         return false;
10403
10404       if (L->FailureKind == ovl_fail_bad_deduction) {
10405         if (R->FailureKind != ovl_fail_bad_deduction)
10406           return true;
10407
10408         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10409           return RankDeductionFailure(L->DeductionFailure)
10410                < RankDeductionFailure(R->DeductionFailure);
10411       } else if (R->FailureKind == ovl_fail_bad_deduction)
10412         return false;
10413
10414       // TODO: others?
10415     }
10416
10417     // Sort everything else by location.
10418     SourceLocation LLoc = GetLocationForCandidate(L);
10419     SourceLocation RLoc = GetLocationForCandidate(R);
10420
10421     // Put candidates without locations (e.g. builtins) at the end.
10422     if (LLoc.isInvalid()) return false;
10423     if (RLoc.isInvalid()) return true;
10424
10425     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10426   }
10427 };
10428 }
10429
10430 /// CompleteNonViableCandidate - Normally, overload resolution only
10431 /// computes up to the first bad conversion. Produces the FixIt set if
10432 /// possible.
10433 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10434                                        ArrayRef<Expr *> Args) {
10435   assert(!Cand->Viable);
10436
10437   // Don't do anything on failures other than bad conversion.
10438   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10439
10440   // We only want the FixIts if all the arguments can be corrected.
10441   bool Unfixable = false;
10442   // Use a implicit copy initialization to check conversion fixes.
10443   Cand->Fix.setConversionChecker(TryCopyInitialization);
10444
10445   // Attempt to fix the bad conversion.
10446   unsigned ConvCount = Cand->Conversions.size();
10447   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10448        ++ConvIdx) {
10449     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10450     if (Cand->Conversions[ConvIdx].isInitialized() &&
10451         Cand->Conversions[ConvIdx].isBad()) {
10452       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10453       break;
10454     }
10455   }
10456
10457   // FIXME: this should probably be preserved from the overload
10458   // operation somehow.
10459   bool SuppressUserConversions = false;
10460
10461   unsigned ConvIdx = 0;
10462   ArrayRef<QualType> ParamTypes;
10463
10464   if (Cand->IsSurrogate) {
10465     QualType ConvType
10466       = Cand->Surrogate->getConversionType().getNonReferenceType();
10467     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10468       ConvType = ConvPtrType->getPointeeType();
10469     ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10470     // Conversion 0 is 'this', which doesn't have a corresponding argument.
10471     ConvIdx = 1;
10472   } else if (Cand->Function) {
10473     ParamTypes =
10474         Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10475     if (isa<CXXMethodDecl>(Cand->Function) &&
10476         !isa<CXXConstructorDecl>(Cand->Function)) {
10477       // Conversion 0 is 'this', which doesn't have a corresponding argument.
10478       ConvIdx = 1;
10479     }
10480   } else {
10481     // Builtin operator.
10482     assert(ConvCount <= 3);
10483     ParamTypes = Cand->BuiltinTypes.ParamTypes;
10484   }
10485
10486   // Fill in the rest of the conversions.
10487   for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10488     if (Cand->Conversions[ConvIdx].isInitialized()) {
10489       // We've already checked this conversion.
10490     } else if (ArgIdx < ParamTypes.size()) {
10491       if (ParamTypes[ArgIdx]->isDependentType())
10492         Cand->Conversions[ConvIdx].setAsIdentityConversion(
10493             Args[ArgIdx]->getType());
10494       else {
10495         Cand->Conversions[ConvIdx] =
10496             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10497                                   SuppressUserConversions,
10498                                   /*InOverloadResolution=*/true,
10499                                   /*AllowObjCWritebackConversion=*/
10500                                   S.getLangOpts().ObjCAutoRefCount);
10501         // Store the FixIt in the candidate if it exists.
10502         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10503           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10504       }
10505     } else
10506       Cand->Conversions[ConvIdx].setEllipsis();
10507   }
10508 }
10509
10510 /// PrintOverloadCandidates - When overload resolution fails, prints
10511 /// diagnostic messages containing the candidates in the candidate
10512 /// set.
10513 void OverloadCandidateSet::NoteCandidates(
10514     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10515     StringRef Opc, SourceLocation OpLoc,
10516     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10517   // Sort the candidates by viability and position.  Sorting directly would
10518   // be prohibitive, so we make a set of pointers and sort those.
10519   SmallVector<OverloadCandidate*, 32> Cands;
10520   if (OCD == OCD_AllCandidates) Cands.reserve(size());
10521   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10522     if (!Filter(*Cand))
10523       continue;
10524     if (Cand->Viable)
10525       Cands.push_back(Cand);
10526     else if (OCD == OCD_AllCandidates) {
10527       CompleteNonViableCandidate(S, Cand, Args);
10528       if (Cand->Function || Cand->IsSurrogate)
10529         Cands.push_back(Cand);
10530       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
10531       // want to list every possible builtin candidate.
10532     }
10533   }
10534
10535   std::sort(Cands.begin(), Cands.end(),
10536             CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10537
10538   bool ReportedAmbiguousConversions = false;
10539
10540   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10541   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10542   unsigned CandsShown = 0;
10543   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10544     OverloadCandidate *Cand = *I;
10545
10546     // Set an arbitrary limit on the number of candidate functions we'll spam
10547     // the user with.  FIXME: This limit should depend on details of the
10548     // candidate list.
10549     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10550       break;
10551     }
10552     ++CandsShown;
10553
10554     if (Cand->Function)
10555       NoteFunctionCandidate(S, Cand, Args.size(),
10556                             /*TakingCandidateAddress=*/false);
10557     else if (Cand->IsSurrogate)
10558       NoteSurrogateCandidate(S, Cand);
10559     else {
10560       assert(Cand->Viable &&
10561              "Non-viable built-in candidates are not added to Cands.");
10562       // Generally we only see ambiguities including viable builtin
10563       // operators if overload resolution got screwed up by an
10564       // ambiguous user-defined conversion.
10565       //
10566       // FIXME: It's quite possible for different conversions to see
10567       // different ambiguities, though.
10568       if (!ReportedAmbiguousConversions) {
10569         NoteAmbiguousUserConversions(S, OpLoc, Cand);
10570         ReportedAmbiguousConversions = true;
10571       }
10572
10573       // If this is a viable builtin, print it.
10574       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10575     }
10576   }
10577
10578   if (I != E)
10579     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10580 }
10581
10582 static SourceLocation
10583 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10584   return Cand->Specialization ? Cand->Specialization->getLocation()
10585                               : SourceLocation();
10586 }
10587
10588 namespace {
10589 struct CompareTemplateSpecCandidatesForDisplay {
10590   Sema &S;
10591   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10592
10593   bool operator()(const TemplateSpecCandidate *L,
10594                   const TemplateSpecCandidate *R) {
10595     // Fast-path this check.
10596     if (L == R)
10597       return false;
10598
10599     // Assuming that both candidates are not matches...
10600
10601     // Sort by the ranking of deduction failures.
10602     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10603       return RankDeductionFailure(L->DeductionFailure) <
10604              RankDeductionFailure(R->DeductionFailure);
10605
10606     // Sort everything else by location.
10607     SourceLocation LLoc = GetLocationForCandidate(L);
10608     SourceLocation RLoc = GetLocationForCandidate(R);
10609
10610     // Put candidates without locations (e.g. builtins) at the end.
10611     if (LLoc.isInvalid())
10612       return false;
10613     if (RLoc.isInvalid())
10614       return true;
10615
10616     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10617   }
10618 };
10619 }
10620
10621 /// Diagnose a template argument deduction failure.
10622 /// We are treating these failures as overload failures due to bad
10623 /// deductions.
10624 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10625                                                  bool ForTakingAddress) {
10626   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10627                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10628 }
10629
10630 void TemplateSpecCandidateSet::destroyCandidates() {
10631   for (iterator i = begin(), e = end(); i != e; ++i) {
10632     i->DeductionFailure.Destroy();
10633   }
10634 }
10635
10636 void TemplateSpecCandidateSet::clear() {
10637   destroyCandidates();
10638   Candidates.clear();
10639 }
10640
10641 /// NoteCandidates - When no template specialization match is found, prints
10642 /// diagnostic messages containing the non-matching specializations that form
10643 /// the candidate set.
10644 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10645 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10646 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10647   // Sort the candidates by position (assuming no candidate is a match).
10648   // Sorting directly would be prohibitive, so we make a set of pointers
10649   // and sort those.
10650   SmallVector<TemplateSpecCandidate *, 32> Cands;
10651   Cands.reserve(size());
10652   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10653     if (Cand->Specialization)
10654       Cands.push_back(Cand);
10655     // Otherwise, this is a non-matching builtin candidate.  We do not,
10656     // in general, want to list every possible builtin candidate.
10657   }
10658
10659   std::sort(Cands.begin(), Cands.end(),
10660             CompareTemplateSpecCandidatesForDisplay(S));
10661
10662   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10663   // for generalization purposes (?).
10664   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10665
10666   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10667   unsigned CandsShown = 0;
10668   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10669     TemplateSpecCandidate *Cand = *I;
10670
10671     // Set an arbitrary limit on the number of candidates we'll spam
10672     // the user with.  FIXME: This limit should depend on details of the
10673     // candidate list.
10674     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10675       break;
10676     ++CandsShown;
10677
10678     assert(Cand->Specialization &&
10679            "Non-matching built-in candidates are not added to Cands.");
10680     Cand->NoteDeductionFailure(S, ForTakingAddress);
10681   }
10682
10683   if (I != E)
10684     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10685 }
10686
10687 // [PossiblyAFunctionType]  -->   [Return]
10688 // NonFunctionType --> NonFunctionType
10689 // R (A) --> R(A)
10690 // R (*)(A) --> R (A)
10691 // R (&)(A) --> R (A)
10692 // R (S::*)(A) --> R (A)
10693 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10694   QualType Ret = PossiblyAFunctionType;
10695   if (const PointerType *ToTypePtr =
10696     PossiblyAFunctionType->getAs<PointerType>())
10697     Ret = ToTypePtr->getPointeeType();
10698   else if (const ReferenceType *ToTypeRef =
10699     PossiblyAFunctionType->getAs<ReferenceType>())
10700     Ret = ToTypeRef->getPointeeType();
10701   else if (const MemberPointerType *MemTypePtr =
10702     PossiblyAFunctionType->getAs<MemberPointerType>())
10703     Ret = MemTypePtr->getPointeeType();
10704   Ret =
10705     Context.getCanonicalType(Ret).getUnqualifiedType();
10706   return Ret;
10707 }
10708
10709 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10710                                  bool Complain = true) {
10711   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10712       S.DeduceReturnType(FD, Loc, Complain))
10713     return true;
10714
10715   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10716   if (S.getLangOpts().CPlusPlus1z &&
10717       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10718       !S.ResolveExceptionSpec(Loc, FPT))
10719     return true;
10720
10721   return false;
10722 }
10723
10724 namespace {
10725 // A helper class to help with address of function resolution
10726 // - allows us to avoid passing around all those ugly parameters
10727 class AddressOfFunctionResolver {
10728   Sema& S;
10729   Expr* SourceExpr;
10730   const QualType& TargetType;
10731   QualType TargetFunctionType; // Extracted function type from target type
10732
10733   bool Complain;
10734   //DeclAccessPair& ResultFunctionAccessPair;
10735   ASTContext& Context;
10736
10737   bool TargetTypeIsNonStaticMemberFunction;
10738   bool FoundNonTemplateFunction;
10739   bool StaticMemberFunctionFromBoundPointer;
10740   bool HasComplained;
10741
10742   OverloadExpr::FindResult OvlExprInfo;
10743   OverloadExpr *OvlExpr;
10744   TemplateArgumentListInfo OvlExplicitTemplateArgs;
10745   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10746   TemplateSpecCandidateSet FailedCandidates;
10747
10748 public:
10749   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10750                             const QualType &TargetType, bool Complain)
10751       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10752         Complain(Complain), Context(S.getASTContext()),
10753         TargetTypeIsNonStaticMemberFunction(
10754             !!TargetType->getAs<MemberPointerType>()),
10755         FoundNonTemplateFunction(false),
10756         StaticMemberFunctionFromBoundPointer(false),
10757         HasComplained(false),
10758         OvlExprInfo(OverloadExpr::find(SourceExpr)),
10759         OvlExpr(OvlExprInfo.Expression),
10760         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10761     ExtractUnqualifiedFunctionTypeFromTargetType();
10762
10763     if (TargetFunctionType->isFunctionType()) {
10764       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10765         if (!UME->isImplicitAccess() &&
10766             !S.ResolveSingleFunctionTemplateSpecialization(UME))
10767           StaticMemberFunctionFromBoundPointer = true;
10768     } else if (OvlExpr->hasExplicitTemplateArgs()) {
10769       DeclAccessPair dap;
10770       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10771               OvlExpr, false, &dap)) {
10772         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10773           if (!Method->isStatic()) {
10774             // If the target type is a non-function type and the function found
10775             // is a non-static member function, pretend as if that was the
10776             // target, it's the only possible type to end up with.
10777             TargetTypeIsNonStaticMemberFunction = true;
10778
10779             // And skip adding the function if its not in the proper form.
10780             // We'll diagnose this due to an empty set of functions.
10781             if (!OvlExprInfo.HasFormOfMemberPointer)
10782               return;
10783           }
10784
10785         Matches.push_back(std::make_pair(dap, Fn));
10786       }
10787       return;
10788     }
10789
10790     if (OvlExpr->hasExplicitTemplateArgs())
10791       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10792
10793     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10794       // C++ [over.over]p4:
10795       //   If more than one function is selected, [...]
10796       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10797         if (FoundNonTemplateFunction)
10798           EliminateAllTemplateMatches();
10799         else
10800           EliminateAllExceptMostSpecializedTemplate();
10801       }
10802     }
10803
10804     if (S.getLangOpts().CUDA && Matches.size() > 1)
10805       EliminateSuboptimalCudaMatches();
10806   }
10807
10808   bool hasComplained() const { return HasComplained; }
10809
10810 private:
10811   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10812     QualType Discard;
10813     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10814            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10815   }
10816
10817   /// \return true if A is considered a better overload candidate for the
10818   /// desired type than B.
10819   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10820     // If A doesn't have exactly the correct type, we don't want to classify it
10821     // as "better" than anything else. This way, the user is required to
10822     // disambiguate for us if there are multiple candidates and no exact match.
10823     return candidateHasExactlyCorrectType(A) &&
10824            (!candidateHasExactlyCorrectType(B) ||
10825             compareEnableIfAttrs(S, A, B) == Comparison::Better);
10826   }
10827
10828   /// \return true if we were able to eliminate all but one overload candidate,
10829   /// false otherwise.
10830   bool eliminiateSuboptimalOverloadCandidates() {
10831     // Same algorithm as overload resolution -- one pass to pick the "best",
10832     // another pass to be sure that nothing is better than the best.
10833     auto Best = Matches.begin();
10834     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10835       if (isBetterCandidate(I->second, Best->second))
10836         Best = I;
10837
10838     const FunctionDecl *BestFn = Best->second;
10839     auto IsBestOrInferiorToBest = [this, BestFn](
10840         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10841       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10842     };
10843
10844     // Note: We explicitly leave Matches unmodified if there isn't a clear best
10845     // option, so we can potentially give the user a better error
10846     if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10847       return false;
10848     Matches[0] = *Best;
10849     Matches.resize(1);
10850     return true;
10851   }
10852
10853   bool isTargetTypeAFunction() const {
10854     return TargetFunctionType->isFunctionType();
10855   }
10856
10857   // [ToType]     [Return]
10858
10859   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10860   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10861   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10862   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10863     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10864   }
10865
10866   // return true if any matching specializations were found
10867   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10868                                    const DeclAccessPair& CurAccessFunPair) {
10869     if (CXXMethodDecl *Method
10870               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10871       // Skip non-static function templates when converting to pointer, and
10872       // static when converting to member pointer.
10873       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10874         return false;
10875     }
10876     else if (TargetTypeIsNonStaticMemberFunction)
10877       return false;
10878
10879     // C++ [over.over]p2:
10880     //   If the name is a function template, template argument deduction is
10881     //   done (14.8.2.2), and if the argument deduction succeeds, the
10882     //   resulting template argument list is used to generate a single
10883     //   function template specialization, which is added to the set of
10884     //   overloaded functions considered.
10885     FunctionDecl *Specialization = nullptr;
10886     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10887     if (Sema::TemplateDeductionResult Result
10888           = S.DeduceTemplateArguments(FunctionTemplate,
10889                                       &OvlExplicitTemplateArgs,
10890                                       TargetFunctionType, Specialization,
10891                                       Info, /*IsAddressOfFunction*/true)) {
10892       // Make a note of the failed deduction for diagnostics.
10893       FailedCandidates.addCandidate()
10894           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10895                MakeDeductionFailureInfo(Context, Result, Info));
10896       return false;
10897     }
10898
10899     // Template argument deduction ensures that we have an exact match or
10900     // compatible pointer-to-function arguments that would be adjusted by ICS.
10901     // This function template specicalization works.
10902     assert(S.isSameOrCompatibleFunctionType(
10903               Context.getCanonicalType(Specialization->getType()),
10904               Context.getCanonicalType(TargetFunctionType)));
10905
10906     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10907       return false;
10908
10909     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10910     return true;
10911   }
10912
10913   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10914                                       const DeclAccessPair& CurAccessFunPair) {
10915     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10916       // Skip non-static functions when converting to pointer, and static
10917       // when converting to member pointer.
10918       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10919         return false;
10920     }
10921     else if (TargetTypeIsNonStaticMemberFunction)
10922       return false;
10923
10924     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10925       if (S.getLangOpts().CUDA)
10926         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10927           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10928             return false;
10929
10930       // If any candidate has a placeholder return type, trigger its deduction
10931       // now.
10932       if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10933                                Complain)) {
10934         HasComplained |= Complain;
10935         return false;
10936       }
10937
10938       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10939         return false;
10940
10941       // If we're in C, we need to support types that aren't exactly identical.
10942       if (!S.getLangOpts().CPlusPlus ||
10943           candidateHasExactlyCorrectType(FunDecl)) {
10944         Matches.push_back(std::make_pair(
10945             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10946         FoundNonTemplateFunction = true;
10947         return true;
10948       }
10949     }
10950
10951     return false;
10952   }
10953
10954   bool FindAllFunctionsThatMatchTargetTypeExactly() {
10955     bool Ret = false;
10956
10957     // If the overload expression doesn't have the form of a pointer to
10958     // member, don't try to convert it to a pointer-to-member type.
10959     if (IsInvalidFormOfPointerToMemberFunction())
10960       return false;
10961
10962     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10963                                E = OvlExpr->decls_end();
10964          I != E; ++I) {
10965       // Look through any using declarations to find the underlying function.
10966       NamedDecl *Fn = (*I)->getUnderlyingDecl();
10967
10968       // C++ [over.over]p3:
10969       //   Non-member functions and static member functions match
10970       //   targets of type "pointer-to-function" or "reference-to-function."
10971       //   Nonstatic member functions match targets of
10972       //   type "pointer-to-member-function."
10973       // Note that according to DR 247, the containing class does not matter.
10974       if (FunctionTemplateDecl *FunctionTemplate
10975                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
10976         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10977           Ret = true;
10978       }
10979       // If we have explicit template arguments supplied, skip non-templates.
10980       else if (!OvlExpr->hasExplicitTemplateArgs() &&
10981                AddMatchingNonTemplateFunction(Fn, I.getPair()))
10982         Ret = true;
10983     }
10984     assert(Ret || Matches.empty());
10985     return Ret;
10986   }
10987
10988   void EliminateAllExceptMostSpecializedTemplate() {
10989     //   [...] and any given function template specialization F1 is
10990     //   eliminated if the set contains a second function template
10991     //   specialization whose function template is more specialized
10992     //   than the function template of F1 according to the partial
10993     //   ordering rules of 14.5.5.2.
10994
10995     // The algorithm specified above is quadratic. We instead use a
10996     // two-pass algorithm (similar to the one used to identify the
10997     // best viable function in an overload set) that identifies the
10998     // best function template (if it exists).
10999
11000     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11001     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11002       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11003
11004     // TODO: It looks like FailedCandidates does not serve much purpose
11005     // here, since the no_viable diagnostic has index 0.
11006     UnresolvedSetIterator Result = S.getMostSpecialized(
11007         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11008         SourceExpr->getLocStart(), S.PDiag(),
11009         S.PDiag(diag::err_addr_ovl_ambiguous)
11010           << Matches[0].second->getDeclName(),
11011         S.PDiag(diag::note_ovl_candidate)
11012           << (unsigned)oc_function_template,
11013         Complain, TargetFunctionType);
11014
11015     if (Result != MatchesCopy.end()) {
11016       // Make it the first and only element
11017       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11018       Matches[0].second = cast<FunctionDecl>(*Result);
11019       Matches.resize(1);
11020     } else
11021       HasComplained |= Complain;
11022   }
11023
11024   void EliminateAllTemplateMatches() {
11025     //   [...] any function template specializations in the set are
11026     //   eliminated if the set also contains a non-template function, [...]
11027     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11028       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11029         ++I;
11030       else {
11031         Matches[I] = Matches[--N];
11032         Matches.resize(N);
11033       }
11034     }
11035   }
11036
11037   void EliminateSuboptimalCudaMatches() {
11038     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11039   }
11040
11041 public:
11042   void ComplainNoMatchesFound() const {
11043     assert(Matches.empty());
11044     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11045         << OvlExpr->getName() << TargetFunctionType
11046         << OvlExpr->getSourceRange();
11047     if (FailedCandidates.empty())
11048       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11049                                   /*TakingAddress=*/true);
11050     else {
11051       // We have some deduction failure messages. Use them to diagnose
11052       // the function templates, and diagnose the non-template candidates
11053       // normally.
11054       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11055                                  IEnd = OvlExpr->decls_end();
11056            I != IEnd; ++I)
11057         if (FunctionDecl *Fun =
11058                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11059           if (!functionHasPassObjectSizeParams(Fun))
11060             S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11061                                     /*TakingAddress=*/true);
11062       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11063     }
11064   }
11065
11066   bool IsInvalidFormOfPointerToMemberFunction() const {
11067     return TargetTypeIsNonStaticMemberFunction &&
11068       !OvlExprInfo.HasFormOfMemberPointer;
11069   }
11070
11071   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11072       // TODO: Should we condition this on whether any functions might
11073       // have matched, or is it more appropriate to do that in callers?
11074       // TODO: a fixit wouldn't hurt.
11075       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11076         << TargetType << OvlExpr->getSourceRange();
11077   }
11078
11079   bool IsStaticMemberFunctionFromBoundPointer() const {
11080     return StaticMemberFunctionFromBoundPointer;
11081   }
11082
11083   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11084     S.Diag(OvlExpr->getLocStart(),
11085            diag::err_invalid_form_pointer_member_function)
11086       << OvlExpr->getSourceRange();
11087   }
11088
11089   void ComplainOfInvalidConversion() const {
11090     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11091       << OvlExpr->getName() << TargetType;
11092   }
11093
11094   void ComplainMultipleMatchesFound() const {
11095     assert(Matches.size() > 1);
11096     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11097       << OvlExpr->getName()
11098       << OvlExpr->getSourceRange();
11099     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11100                                 /*TakingAddress=*/true);
11101   }
11102
11103   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11104
11105   int getNumMatches() const { return Matches.size(); }
11106
11107   FunctionDecl* getMatchingFunctionDecl() const {
11108     if (Matches.size() != 1) return nullptr;
11109     return Matches[0].second;
11110   }
11111
11112   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11113     if (Matches.size() != 1) return nullptr;
11114     return &Matches[0].first;
11115   }
11116 };
11117 }
11118
11119 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11120 /// an overloaded function (C++ [over.over]), where @p From is an
11121 /// expression with overloaded function type and @p ToType is the type
11122 /// we're trying to resolve to. For example:
11123 ///
11124 /// @code
11125 /// int f(double);
11126 /// int f(int);
11127 ///
11128 /// int (*pfd)(double) = f; // selects f(double)
11129 /// @endcode
11130 ///
11131 /// This routine returns the resulting FunctionDecl if it could be
11132 /// resolved, and NULL otherwise. When @p Complain is true, this
11133 /// routine will emit diagnostics if there is an error.
11134 FunctionDecl *
11135 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11136                                          QualType TargetType,
11137                                          bool Complain,
11138                                          DeclAccessPair &FoundResult,
11139                                          bool *pHadMultipleCandidates) {
11140   assert(AddressOfExpr->getType() == Context.OverloadTy);
11141
11142   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11143                                      Complain);
11144   int NumMatches = Resolver.getNumMatches();
11145   FunctionDecl *Fn = nullptr;
11146   bool ShouldComplain = Complain && !Resolver.hasComplained();
11147   if (NumMatches == 0 && ShouldComplain) {
11148     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11149       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11150     else
11151       Resolver.ComplainNoMatchesFound();
11152   }
11153   else if (NumMatches > 1 && ShouldComplain)
11154     Resolver.ComplainMultipleMatchesFound();
11155   else if (NumMatches == 1) {
11156     Fn = Resolver.getMatchingFunctionDecl();
11157     assert(Fn);
11158     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11159       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11160     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11161     if (Complain) {
11162       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11163         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11164       else
11165         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11166     }
11167   }
11168
11169   if (pHadMultipleCandidates)
11170     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11171   return Fn;
11172 }
11173
11174 /// \brief Given an expression that refers to an overloaded function, try to
11175 /// resolve that function to a single function that can have its address taken.
11176 /// This will modify `Pair` iff it returns non-null.
11177 ///
11178 /// This routine can only realistically succeed if all but one candidates in the
11179 /// overload set for SrcExpr cannot have their addresses taken.
11180 FunctionDecl *
11181 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11182                                                   DeclAccessPair &Pair) {
11183   OverloadExpr::FindResult R = OverloadExpr::find(E);
11184   OverloadExpr *Ovl = R.Expression;
11185   FunctionDecl *Result = nullptr;
11186   DeclAccessPair DAP;
11187   // Don't use the AddressOfResolver because we're specifically looking for
11188   // cases where we have one overload candidate that lacks
11189   // enable_if/pass_object_size/...
11190   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11191     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11192     if (!FD)
11193       return nullptr;
11194
11195     if (!checkAddressOfFunctionIsAvailable(FD))
11196       continue;
11197
11198     // We have more than one result; quit.
11199     if (Result)
11200       return nullptr;
11201     DAP = I.getPair();
11202     Result = FD;
11203   }
11204
11205   if (Result)
11206     Pair = DAP;
11207   return Result;
11208 }
11209
11210 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11211 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11212 /// will perform access checks, diagnose the use of the resultant decl, and, if
11213 /// requested, potentially perform a function-to-pointer decay.
11214 ///
11215 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11216 /// Otherwise, returns true. This may emit diagnostics and return true.
11217 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11218     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11219   Expr *E = SrcExpr.get();
11220   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11221
11222   DeclAccessPair DAP;
11223   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11224   if (!Found)
11225     return false;
11226
11227   // Emitting multiple diagnostics for a function that is both inaccessible and
11228   // unavailable is consistent with our behavior elsewhere. So, always check
11229   // for both.
11230   DiagnoseUseOfDecl(Found, E->getExprLoc());
11231   CheckAddressOfMemberAccess(E, DAP);
11232   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11233   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11234     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11235   else
11236     SrcExpr = Fixed;
11237   return true;
11238 }
11239
11240 /// \brief Given an expression that refers to an overloaded function, try to
11241 /// resolve that overloaded function expression down to a single function.
11242 ///
11243 /// This routine can only resolve template-ids that refer to a single function
11244 /// template, where that template-id refers to a single template whose template
11245 /// arguments are either provided by the template-id or have defaults,
11246 /// as described in C++0x [temp.arg.explicit]p3.
11247 ///
11248 /// If no template-ids are found, no diagnostics are emitted and NULL is
11249 /// returned.
11250 FunctionDecl *
11251 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11252                                                   bool Complain,
11253                                                   DeclAccessPair *FoundResult) {
11254   // C++ [over.over]p1:
11255   //   [...] [Note: any redundant set of parentheses surrounding the
11256   //   overloaded function name is ignored (5.1). ]
11257   // C++ [over.over]p1:
11258   //   [...] The overloaded function name can be preceded by the &
11259   //   operator.
11260
11261   // If we didn't actually find any template-ids, we're done.
11262   if (!ovl->hasExplicitTemplateArgs())
11263     return nullptr;
11264
11265   TemplateArgumentListInfo ExplicitTemplateArgs;
11266   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11267   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11268
11269   // Look through all of the overloaded functions, searching for one
11270   // whose type matches exactly.
11271   FunctionDecl *Matched = nullptr;
11272   for (UnresolvedSetIterator I = ovl->decls_begin(),
11273          E = ovl->decls_end(); I != E; ++I) {
11274     // C++0x [temp.arg.explicit]p3:
11275     //   [...] In contexts where deduction is done and fails, or in contexts
11276     //   where deduction is not done, if a template argument list is
11277     //   specified and it, along with any default template arguments,
11278     //   identifies a single function template specialization, then the
11279     //   template-id is an lvalue for the function template specialization.
11280     FunctionTemplateDecl *FunctionTemplate
11281       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11282
11283     // C++ [over.over]p2:
11284     //   If the name is a function template, template argument deduction is
11285     //   done (14.8.2.2), and if the argument deduction succeeds, the
11286     //   resulting template argument list is used to generate a single
11287     //   function template specialization, which is added to the set of
11288     //   overloaded functions considered.
11289     FunctionDecl *Specialization = nullptr;
11290     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11291     if (TemplateDeductionResult Result
11292           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11293                                     Specialization, Info,
11294                                     /*IsAddressOfFunction*/true)) {
11295       // Make a note of the failed deduction for diagnostics.
11296       // TODO: Actually use the failed-deduction info?
11297       FailedCandidates.addCandidate()
11298           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11299                MakeDeductionFailureInfo(Context, Result, Info));
11300       continue;
11301     }
11302
11303     assert(Specialization && "no specialization and no error?");
11304
11305     // Multiple matches; we can't resolve to a single declaration.
11306     if (Matched) {
11307       if (Complain) {
11308         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11309           << ovl->getName();
11310         NoteAllOverloadCandidates(ovl);
11311       }
11312       return nullptr;
11313     }
11314
11315     Matched = Specialization;
11316     if (FoundResult) *FoundResult = I.getPair();
11317   }
11318
11319   if (Matched &&
11320       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11321     return nullptr;
11322
11323   return Matched;
11324 }
11325
11326
11327
11328
11329 // Resolve and fix an overloaded expression that can be resolved
11330 // because it identifies a single function template specialization.
11331 //
11332 // Last three arguments should only be supplied if Complain = true
11333 //
11334 // Return true if it was logically possible to so resolve the
11335 // expression, regardless of whether or not it succeeded.  Always
11336 // returns true if 'complain' is set.
11337 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11338                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11339                       bool complain, SourceRange OpRangeForComplaining,
11340                                            QualType DestTypeForComplaining,
11341                                             unsigned DiagIDForComplaining) {
11342   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11343
11344   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11345
11346   DeclAccessPair found;
11347   ExprResult SingleFunctionExpression;
11348   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11349                            ovl.Expression, /*complain*/ false, &found)) {
11350     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11351       SrcExpr = ExprError();
11352       return true;
11353     }
11354
11355     // It is only correct to resolve to an instance method if we're
11356     // resolving a form that's permitted to be a pointer to member.
11357     // Otherwise we'll end up making a bound member expression, which
11358     // is illegal in all the contexts we resolve like this.
11359     if (!ovl.HasFormOfMemberPointer &&
11360         isa<CXXMethodDecl>(fn) &&
11361         cast<CXXMethodDecl>(fn)->isInstance()) {
11362       if (!complain) return false;
11363
11364       Diag(ovl.Expression->getExprLoc(),
11365            diag::err_bound_member_function)
11366         << 0 << ovl.Expression->getSourceRange();
11367
11368       // TODO: I believe we only end up here if there's a mix of
11369       // static and non-static candidates (otherwise the expression
11370       // would have 'bound member' type, not 'overload' type).
11371       // Ideally we would note which candidate was chosen and why
11372       // the static candidates were rejected.
11373       SrcExpr = ExprError();
11374       return true;
11375     }
11376
11377     // Fix the expression to refer to 'fn'.
11378     SingleFunctionExpression =
11379         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11380
11381     // If desired, do function-to-pointer decay.
11382     if (doFunctionPointerConverion) {
11383       SingleFunctionExpression =
11384         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11385       if (SingleFunctionExpression.isInvalid()) {
11386         SrcExpr = ExprError();
11387         return true;
11388       }
11389     }
11390   }
11391
11392   if (!SingleFunctionExpression.isUsable()) {
11393     if (complain) {
11394       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11395         << ovl.Expression->getName()
11396         << DestTypeForComplaining
11397         << OpRangeForComplaining
11398         << ovl.Expression->getQualifierLoc().getSourceRange();
11399       NoteAllOverloadCandidates(SrcExpr.get());
11400
11401       SrcExpr = ExprError();
11402       return true;
11403     }
11404
11405     return false;
11406   }
11407
11408   SrcExpr = SingleFunctionExpression;
11409   return true;
11410 }
11411
11412 /// \brief Add a single candidate to the overload set.
11413 static void AddOverloadedCallCandidate(Sema &S,
11414                                        DeclAccessPair FoundDecl,
11415                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
11416                                        ArrayRef<Expr *> Args,
11417                                        OverloadCandidateSet &CandidateSet,
11418                                        bool PartialOverloading,
11419                                        bool KnownValid) {
11420   NamedDecl *Callee = FoundDecl.getDecl();
11421   if (isa<UsingShadowDecl>(Callee))
11422     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11423
11424   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11425     if (ExplicitTemplateArgs) {
11426       assert(!KnownValid && "Explicit template arguments?");
11427       return;
11428     }
11429     // Prevent ill-formed function decls to be added as overload candidates.
11430     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11431       return;
11432
11433     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11434                            /*SuppressUsedConversions=*/false,
11435                            PartialOverloading);
11436     return;
11437   }
11438
11439   if (FunctionTemplateDecl *FuncTemplate
11440       = dyn_cast<FunctionTemplateDecl>(Callee)) {
11441     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11442                                    ExplicitTemplateArgs, Args, CandidateSet,
11443                                    /*SuppressUsedConversions=*/false,
11444                                    PartialOverloading);
11445     return;
11446   }
11447
11448   assert(!KnownValid && "unhandled case in overloaded call candidate");
11449 }
11450
11451 /// \brief Add the overload candidates named by callee and/or found by argument
11452 /// dependent lookup to the given overload set.
11453 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11454                                        ArrayRef<Expr *> Args,
11455                                        OverloadCandidateSet &CandidateSet,
11456                                        bool PartialOverloading) {
11457
11458 #ifndef NDEBUG
11459   // Verify that ArgumentDependentLookup is consistent with the rules
11460   // in C++0x [basic.lookup.argdep]p3:
11461   //
11462   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11463   //   and let Y be the lookup set produced by argument dependent
11464   //   lookup (defined as follows). If X contains
11465   //
11466   //     -- a declaration of a class member, or
11467   //
11468   //     -- a block-scope function declaration that is not a
11469   //        using-declaration, or
11470   //
11471   //     -- a declaration that is neither a function or a function
11472   //        template
11473   //
11474   //   then Y is empty.
11475
11476   if (ULE->requiresADL()) {
11477     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11478            E = ULE->decls_end(); I != E; ++I) {
11479       assert(!(*I)->getDeclContext()->isRecord());
11480       assert(isa<UsingShadowDecl>(*I) ||
11481              !(*I)->getDeclContext()->isFunctionOrMethod());
11482       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11483     }
11484   }
11485 #endif
11486
11487   // It would be nice to avoid this copy.
11488   TemplateArgumentListInfo TABuffer;
11489   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11490   if (ULE->hasExplicitTemplateArgs()) {
11491     ULE->copyTemplateArgumentsInto(TABuffer);
11492     ExplicitTemplateArgs = &TABuffer;
11493   }
11494
11495   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11496          E = ULE->decls_end(); I != E; ++I)
11497     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11498                                CandidateSet, PartialOverloading,
11499                                /*KnownValid*/ true);
11500
11501   if (ULE->requiresADL())
11502     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11503                                          Args, ExplicitTemplateArgs,
11504                                          CandidateSet, PartialOverloading);
11505 }
11506
11507 /// Determine whether a declaration with the specified name could be moved into
11508 /// a different namespace.
11509 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11510   switch (Name.getCXXOverloadedOperator()) {
11511   case OO_New: case OO_Array_New:
11512   case OO_Delete: case OO_Array_Delete:
11513     return false;
11514
11515   default:
11516     return true;
11517   }
11518 }
11519
11520 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11521 /// template, where the non-dependent name was declared after the template
11522 /// was defined. This is common in code written for a compilers which do not
11523 /// correctly implement two-stage name lookup.
11524 ///
11525 /// Returns true if a viable candidate was found and a diagnostic was issued.
11526 static bool
11527 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11528                        const CXXScopeSpec &SS, LookupResult &R,
11529                        OverloadCandidateSet::CandidateSetKind CSK,
11530                        TemplateArgumentListInfo *ExplicitTemplateArgs,
11531                        ArrayRef<Expr *> Args,
11532                        bool *DoDiagnoseEmptyLookup = nullptr) {
11533   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11534     return false;
11535
11536   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11537     if (DC->isTransparentContext())
11538       continue;
11539
11540     SemaRef.LookupQualifiedName(R, DC);
11541
11542     if (!R.empty()) {
11543       R.suppressDiagnostics();
11544
11545       if (isa<CXXRecordDecl>(DC)) {
11546         // Don't diagnose names we find in classes; we get much better
11547         // diagnostics for these from DiagnoseEmptyLookup.
11548         R.clear();
11549         if (DoDiagnoseEmptyLookup)
11550           *DoDiagnoseEmptyLookup = true;
11551         return false;
11552       }
11553
11554       OverloadCandidateSet Candidates(FnLoc, CSK);
11555       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11556         AddOverloadedCallCandidate(SemaRef, I.getPair(),
11557                                    ExplicitTemplateArgs, Args,
11558                                    Candidates, false, /*KnownValid*/ false);
11559
11560       OverloadCandidateSet::iterator Best;
11561       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11562         // No viable functions. Don't bother the user with notes for functions
11563         // which don't work and shouldn't be found anyway.
11564         R.clear();
11565         return false;
11566       }
11567
11568       // Find the namespaces where ADL would have looked, and suggest
11569       // declaring the function there instead.
11570       Sema::AssociatedNamespaceSet AssociatedNamespaces;
11571       Sema::AssociatedClassSet AssociatedClasses;
11572       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11573                                                  AssociatedNamespaces,
11574                                                  AssociatedClasses);
11575       Sema::AssociatedNamespaceSet SuggestedNamespaces;
11576       if (canBeDeclaredInNamespace(R.getLookupName())) {
11577         DeclContext *Std = SemaRef.getStdNamespace();
11578         for (Sema::AssociatedNamespaceSet::iterator
11579                it = AssociatedNamespaces.begin(),
11580                end = AssociatedNamespaces.end(); it != end; ++it) {
11581           // Never suggest declaring a function within namespace 'std'.
11582           if (Std && Std->Encloses(*it))
11583             continue;
11584
11585           // Never suggest declaring a function within a namespace with a
11586           // reserved name, like __gnu_cxx.
11587           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11588           if (NS &&
11589               NS->getQualifiedNameAsString().find("__") != std::string::npos)
11590             continue;
11591
11592           SuggestedNamespaces.insert(*it);
11593         }
11594       }
11595
11596       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11597         << R.getLookupName();
11598       if (SuggestedNamespaces.empty()) {
11599         SemaRef.Diag(Best->Function->getLocation(),
11600                      diag::note_not_found_by_two_phase_lookup)
11601           << R.getLookupName() << 0;
11602       } else if (SuggestedNamespaces.size() == 1) {
11603         SemaRef.Diag(Best->Function->getLocation(),
11604                      diag::note_not_found_by_two_phase_lookup)
11605           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11606       } else {
11607         // FIXME: It would be useful to list the associated namespaces here,
11608         // but the diagnostics infrastructure doesn't provide a way to produce
11609         // a localized representation of a list of items.
11610         SemaRef.Diag(Best->Function->getLocation(),
11611                      diag::note_not_found_by_two_phase_lookup)
11612           << R.getLookupName() << 2;
11613       }
11614
11615       // Try to recover by calling this function.
11616       return true;
11617     }
11618
11619     R.clear();
11620   }
11621
11622   return false;
11623 }
11624
11625 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11626 /// template, where the non-dependent operator was declared after the template
11627 /// was defined.
11628 ///
11629 /// Returns true if a viable candidate was found and a diagnostic was issued.
11630 static bool
11631 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11632                                SourceLocation OpLoc,
11633                                ArrayRef<Expr *> Args) {
11634   DeclarationName OpName =
11635     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11636   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11637   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11638                                 OverloadCandidateSet::CSK_Operator,
11639                                 /*ExplicitTemplateArgs=*/nullptr, Args);
11640 }
11641
11642 namespace {
11643 class BuildRecoveryCallExprRAII {
11644   Sema &SemaRef;
11645 public:
11646   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11647     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11648     SemaRef.IsBuildingRecoveryCallExpr = true;
11649   }
11650
11651   ~BuildRecoveryCallExprRAII() {
11652     SemaRef.IsBuildingRecoveryCallExpr = false;
11653   }
11654 };
11655
11656 }
11657
11658 static std::unique_ptr<CorrectionCandidateCallback>
11659 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11660               bool HasTemplateArgs, bool AllowTypoCorrection) {
11661   if (!AllowTypoCorrection)
11662     return llvm::make_unique<NoTypoCorrectionCCC>();
11663   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11664                                                   HasTemplateArgs, ME);
11665 }
11666
11667 /// Attempts to recover from a call where no functions were found.
11668 ///
11669 /// Returns true if new candidates were found.
11670 static ExprResult
11671 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11672                       UnresolvedLookupExpr *ULE,
11673                       SourceLocation LParenLoc,
11674                       MutableArrayRef<Expr *> Args,
11675                       SourceLocation RParenLoc,
11676                       bool EmptyLookup, bool AllowTypoCorrection) {
11677   // Do not try to recover if it is already building a recovery call.
11678   // This stops infinite loops for template instantiations like
11679   //
11680   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11681   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11682   //
11683   if (SemaRef.IsBuildingRecoveryCallExpr)
11684     return ExprError();
11685   BuildRecoveryCallExprRAII RCE(SemaRef);
11686
11687   CXXScopeSpec SS;
11688   SS.Adopt(ULE->getQualifierLoc());
11689   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11690
11691   TemplateArgumentListInfo TABuffer;
11692   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11693   if (ULE->hasExplicitTemplateArgs()) {
11694     ULE->copyTemplateArgumentsInto(TABuffer);
11695     ExplicitTemplateArgs = &TABuffer;
11696   }
11697
11698   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11699                  Sema::LookupOrdinaryName);
11700   bool DoDiagnoseEmptyLookup = EmptyLookup;
11701   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11702                               OverloadCandidateSet::CSK_Normal,
11703                               ExplicitTemplateArgs, Args,
11704                               &DoDiagnoseEmptyLookup) &&
11705     (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11706         S, SS, R,
11707         MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11708                       ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11709         ExplicitTemplateArgs, Args)))
11710     return ExprError();
11711
11712   assert(!R.empty() && "lookup results empty despite recovery");
11713
11714   // If recovery created an ambiguity, just bail out.
11715   if (R.isAmbiguous()) {
11716     R.suppressDiagnostics();
11717     return ExprError();
11718   }
11719
11720   // Build an implicit member call if appropriate.  Just drop the
11721   // casts and such from the call, we don't really care.
11722   ExprResult NewFn = ExprError();
11723   if ((*R.begin())->isCXXClassMember())
11724     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11725                                                     ExplicitTemplateArgs, S);
11726   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11727     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11728                                         ExplicitTemplateArgs);
11729   else
11730     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11731
11732   if (NewFn.isInvalid())
11733     return ExprError();
11734
11735   // This shouldn't cause an infinite loop because we're giving it
11736   // an expression with viable lookup results, which should never
11737   // end up here.
11738   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11739                                MultiExprArg(Args.data(), Args.size()),
11740                                RParenLoc);
11741 }
11742
11743 /// \brief Constructs and populates an OverloadedCandidateSet from
11744 /// the given function.
11745 /// \returns true when an the ExprResult output parameter has been set.
11746 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11747                                   UnresolvedLookupExpr *ULE,
11748                                   MultiExprArg Args,
11749                                   SourceLocation RParenLoc,
11750                                   OverloadCandidateSet *CandidateSet,
11751                                   ExprResult *Result) {
11752 #ifndef NDEBUG
11753   if (ULE->requiresADL()) {
11754     // To do ADL, we must have found an unqualified name.
11755     assert(!ULE->getQualifier() && "qualified name with ADL");
11756
11757     // We don't perform ADL for implicit declarations of builtins.
11758     // Verify that this was correctly set up.
11759     FunctionDecl *F;
11760     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11761         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11762         F->getBuiltinID() && F->isImplicit())
11763       llvm_unreachable("performing ADL for builtin");
11764
11765     // We don't perform ADL in C.
11766     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11767   }
11768 #endif
11769
11770   UnbridgedCastsSet UnbridgedCasts;
11771   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11772     *Result = ExprError();
11773     return true;
11774   }
11775
11776   // Add the functions denoted by the callee to the set of candidate
11777   // functions, including those from argument-dependent lookup.
11778   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11779
11780   if (getLangOpts().MSVCCompat &&
11781       CurContext->isDependentContext() && !isSFINAEContext() &&
11782       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11783
11784     OverloadCandidateSet::iterator Best;
11785     if (CandidateSet->empty() ||
11786         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11787             OR_No_Viable_Function) {
11788       // In Microsoft mode, if we are inside a template class member function then
11789       // create a type dependent CallExpr. The goal is to postpone name lookup
11790       // to instantiation time to be able to search into type dependent base
11791       // classes.
11792       CallExpr *CE = new (Context) CallExpr(
11793           Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11794       CE->setTypeDependent(true);
11795       CE->setValueDependent(true);
11796       CE->setInstantiationDependent(true);
11797       *Result = CE;
11798       return true;
11799     }
11800   }
11801
11802   if (CandidateSet->empty())
11803     return false;
11804
11805   UnbridgedCasts.restore();
11806   return false;
11807 }
11808
11809 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11810 /// the completed call expression. If overload resolution fails, emits
11811 /// diagnostics and returns ExprError()
11812 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11813                                            UnresolvedLookupExpr *ULE,
11814                                            SourceLocation LParenLoc,
11815                                            MultiExprArg Args,
11816                                            SourceLocation RParenLoc,
11817                                            Expr *ExecConfig,
11818                                            OverloadCandidateSet *CandidateSet,
11819                                            OverloadCandidateSet::iterator *Best,
11820                                            OverloadingResult OverloadResult,
11821                                            bool AllowTypoCorrection) {
11822   if (CandidateSet->empty())
11823     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11824                                  RParenLoc, /*EmptyLookup=*/true,
11825                                  AllowTypoCorrection);
11826
11827   switch (OverloadResult) {
11828   case OR_Success: {
11829     FunctionDecl *FDecl = (*Best)->Function;
11830     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11831     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11832       return ExprError();
11833     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11834     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11835                                          ExecConfig);
11836   }
11837
11838   case OR_No_Viable_Function: {
11839     // Try to recover by looking for viable functions which the user might
11840     // have meant to call.
11841     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11842                                                 Args, RParenLoc,
11843                                                 /*EmptyLookup=*/false,
11844                                                 AllowTypoCorrection);
11845     if (!Recovery.isInvalid())
11846       return Recovery;
11847
11848     // If the user passes in a function that we can't take the address of, we
11849     // generally end up emitting really bad error messages. Here, we attempt to
11850     // emit better ones.
11851     for (const Expr *Arg : Args) {
11852       if (!Arg->getType()->isFunctionType())
11853         continue;
11854       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11855         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11856         if (FD &&
11857             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11858                                                        Arg->getExprLoc()))
11859           return ExprError();
11860       }
11861     }
11862
11863     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11864         << ULE->getName() << Fn->getSourceRange();
11865     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11866     break;
11867   }
11868
11869   case OR_Ambiguous:
11870     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11871       << ULE->getName() << Fn->getSourceRange();
11872     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11873     break;
11874
11875   case OR_Deleted: {
11876     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11877       << (*Best)->Function->isDeleted()
11878       << ULE->getName()
11879       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11880       << Fn->getSourceRange();
11881     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11882
11883     // We emitted an error for the unvailable/deleted function call but keep
11884     // the call in the AST.
11885     FunctionDecl *FDecl = (*Best)->Function;
11886     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11887     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11888                                          ExecConfig);
11889   }
11890   }
11891
11892   // Overload resolution failed.
11893   return ExprError();
11894 }
11895
11896 static void markUnaddressableCandidatesUnviable(Sema &S,
11897                                                 OverloadCandidateSet &CS) {
11898   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11899     if (I->Viable &&
11900         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11901       I->Viable = false;
11902       I->FailureKind = ovl_fail_addr_not_available;
11903     }
11904   }
11905 }
11906
11907 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11908 /// (which eventually refers to the declaration Func) and the call
11909 /// arguments Args/NumArgs, attempt to resolve the function call down
11910 /// to a specific function. If overload resolution succeeds, returns
11911 /// the call expression produced by overload resolution.
11912 /// Otherwise, emits diagnostics and returns ExprError.
11913 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11914                                          UnresolvedLookupExpr *ULE,
11915                                          SourceLocation LParenLoc,
11916                                          MultiExprArg Args,
11917                                          SourceLocation RParenLoc,
11918                                          Expr *ExecConfig,
11919                                          bool AllowTypoCorrection,
11920                                          bool CalleesAddressIsTaken) {
11921   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11922                                     OverloadCandidateSet::CSK_Normal);
11923   ExprResult result;
11924
11925   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11926                              &result))
11927     return result;
11928
11929   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11930   // functions that aren't addressible are considered unviable.
11931   if (CalleesAddressIsTaken)
11932     markUnaddressableCandidatesUnviable(*this, CandidateSet);
11933
11934   OverloadCandidateSet::iterator Best;
11935   OverloadingResult OverloadResult =
11936       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11937
11938   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11939                                   RParenLoc, ExecConfig, &CandidateSet,
11940                                   &Best, OverloadResult,
11941                                   AllowTypoCorrection);
11942 }
11943
11944 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11945   return Functions.size() > 1 ||
11946     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11947 }
11948
11949 /// \brief Create a unary operation that may resolve to an overloaded
11950 /// operator.
11951 ///
11952 /// \param OpLoc The location of the operator itself (e.g., '*').
11953 ///
11954 /// \param Opc The UnaryOperatorKind that describes this operator.
11955 ///
11956 /// \param Fns The set of non-member functions that will be
11957 /// considered by overload resolution. The caller needs to build this
11958 /// set based on the context using, e.g.,
11959 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11960 /// set should not contain any member functions; those will be added
11961 /// by CreateOverloadedUnaryOp().
11962 ///
11963 /// \param Input The input argument.
11964 ExprResult
11965 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11966                               const UnresolvedSetImpl &Fns,
11967                               Expr *Input) {
11968   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11969   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11970   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11971   // TODO: provide better source location info.
11972   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11973
11974   if (checkPlaceholderForOverload(*this, Input))
11975     return ExprError();
11976
11977   Expr *Args[2] = { Input, nullptr };
11978   unsigned NumArgs = 1;
11979
11980   // For post-increment and post-decrement, add the implicit '0' as
11981   // the second argument, so that we know this is a post-increment or
11982   // post-decrement.
11983   if (Opc == UO_PostInc || Opc == UO_PostDec) {
11984     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11985     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11986                                      SourceLocation());
11987     NumArgs = 2;
11988   }
11989
11990   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11991
11992   if (Input->isTypeDependent()) {
11993     if (Fns.empty())
11994       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11995                                          VK_RValue, OK_Ordinary, OpLoc);
11996
11997     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11998     UnresolvedLookupExpr *Fn
11999       = UnresolvedLookupExpr::Create(Context, NamingClass,
12000                                      NestedNameSpecifierLoc(), OpNameInfo,
12001                                      /*ADL*/ true, IsOverloaded(Fns),
12002                                      Fns.begin(), Fns.end());
12003     return new (Context)
12004         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12005                             VK_RValue, OpLoc, FPOptions());
12006   }
12007
12008   // Build an empty overload set.
12009   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12010
12011   // Add the candidates from the given function set.
12012   AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12013
12014   // Add operator candidates that are member functions.
12015   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12016
12017   // Add candidates from ADL.
12018   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12019                                        /*ExplicitTemplateArgs*/nullptr,
12020                                        CandidateSet);
12021
12022   // Add builtin operator candidates.
12023   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12024
12025   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12026
12027   // Perform overload resolution.
12028   OverloadCandidateSet::iterator Best;
12029   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12030   case OR_Success: {
12031     // We found a built-in operator or an overloaded operator.
12032     FunctionDecl *FnDecl = Best->Function;
12033
12034     if (FnDecl) {
12035       // We matched an overloaded operator. Build a call to that
12036       // operator.
12037
12038       // Convert the arguments.
12039       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12040         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12041
12042         ExprResult InputRes =
12043           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12044                                               Best->FoundDecl, Method);
12045         if (InputRes.isInvalid())
12046           return ExprError();
12047         Input = InputRes.get();
12048       } else {
12049         // Convert the arguments.
12050         ExprResult InputInit
12051           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12052                                                       Context,
12053                                                       FnDecl->getParamDecl(0)),
12054                                       SourceLocation(),
12055                                       Input);
12056         if (InputInit.isInvalid())
12057           return ExprError();
12058         Input = InputInit.get();
12059       }
12060
12061       // Build the actual expression node.
12062       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12063                                                 HadMultipleCandidates, OpLoc);
12064       if (FnExpr.isInvalid())
12065         return ExprError();
12066
12067       // Determine the result type.
12068       QualType ResultTy = FnDecl->getReturnType();
12069       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12070       ResultTy = ResultTy.getNonLValueExprType(Context);
12071
12072       Args[0] = Input;
12073       CallExpr *TheCall =
12074         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12075                                           ResultTy, VK, OpLoc, FPOptions());
12076
12077       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12078         return ExprError();
12079
12080       if (CheckFunctionCall(FnDecl, TheCall,
12081                             FnDecl->getType()->castAs<FunctionProtoType>()))
12082         return ExprError();
12083
12084       return MaybeBindToTemporary(TheCall);
12085     } else {
12086       // We matched a built-in operator. Convert the arguments, then
12087       // break out so that we will build the appropriate built-in
12088       // operator node.
12089       ExprResult InputRes =
12090         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
12091                                   Best->Conversions[0], AA_Passing);
12092       if (InputRes.isInvalid())
12093         return ExprError();
12094       Input = InputRes.get();
12095       break;
12096     }
12097   }
12098
12099   case OR_No_Viable_Function:
12100     // This is an erroneous use of an operator which can be overloaded by
12101     // a non-member function. Check for non-member operators which were
12102     // defined too late to be candidates.
12103     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12104       // FIXME: Recover by calling the found function.
12105       return ExprError();
12106
12107     // No viable function; fall through to handling this as a
12108     // built-in operator, which will produce an error message for us.
12109     break;
12110
12111   case OR_Ambiguous:
12112     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12113         << UnaryOperator::getOpcodeStr(Opc)
12114         << Input->getType()
12115         << Input->getSourceRange();
12116     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12117                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12118     return ExprError();
12119
12120   case OR_Deleted:
12121     Diag(OpLoc, diag::err_ovl_deleted_oper)
12122       << Best->Function->isDeleted()
12123       << UnaryOperator::getOpcodeStr(Opc)
12124       << getDeletedOrUnavailableSuffix(Best->Function)
12125       << Input->getSourceRange();
12126     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12127                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12128     return ExprError();
12129   }
12130
12131   // Either we found no viable overloaded operator or we matched a
12132   // built-in operator. In either case, fall through to trying to
12133   // build a built-in operation.
12134   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12135 }
12136
12137 /// \brief Create a binary operation that may resolve to an overloaded
12138 /// operator.
12139 ///
12140 /// \param OpLoc The location of the operator itself (e.g., '+').
12141 ///
12142 /// \param Opc The BinaryOperatorKind that describes this operator.
12143 ///
12144 /// \param Fns The set of non-member functions that will be
12145 /// considered by overload resolution. The caller needs to build this
12146 /// set based on the context using, e.g.,
12147 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12148 /// set should not contain any member functions; those will be added
12149 /// by CreateOverloadedBinOp().
12150 ///
12151 /// \param LHS Left-hand argument.
12152 /// \param RHS Right-hand argument.
12153 ExprResult
12154 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12155                             BinaryOperatorKind Opc,
12156                             const UnresolvedSetImpl &Fns,
12157                             Expr *LHS, Expr *RHS) {
12158   Expr *Args[2] = { LHS, RHS };
12159   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12160
12161   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12162   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12163
12164   // If either side is type-dependent, create an appropriate dependent
12165   // expression.
12166   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12167     if (Fns.empty()) {
12168       // If there are no functions to store, just build a dependent
12169       // BinaryOperator or CompoundAssignment.
12170       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12171         return new (Context) BinaryOperator(
12172             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12173             OpLoc, FPFeatures);
12174
12175       return new (Context) CompoundAssignOperator(
12176           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12177           Context.DependentTy, Context.DependentTy, OpLoc,
12178           FPFeatures);
12179     }
12180
12181     // FIXME: save results of ADL from here?
12182     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12183     // TODO: provide better source location info in DNLoc component.
12184     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12185     UnresolvedLookupExpr *Fn
12186       = UnresolvedLookupExpr::Create(Context, NamingClass,
12187                                      NestedNameSpecifierLoc(), OpNameInfo,
12188                                      /*ADL*/ true, IsOverloaded(Fns),
12189                                      Fns.begin(), Fns.end());
12190     return new (Context)
12191         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12192                             VK_RValue, OpLoc, FPFeatures);
12193   }
12194
12195   // Always do placeholder-like conversions on the RHS.
12196   if (checkPlaceholderForOverload(*this, Args[1]))
12197     return ExprError();
12198
12199   // Do placeholder-like conversion on the LHS; note that we should
12200   // not get here with a PseudoObject LHS.
12201   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12202   if (checkPlaceholderForOverload(*this, Args[0]))
12203     return ExprError();
12204
12205   // If this is the assignment operator, we only perform overload resolution
12206   // if the left-hand side is a class or enumeration type. This is actually
12207   // a hack. The standard requires that we do overload resolution between the
12208   // various built-in candidates, but as DR507 points out, this can lead to
12209   // problems. So we do it this way, which pretty much follows what GCC does.
12210   // Note that we go the traditional code path for compound assignment forms.
12211   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12212     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12213
12214   // If this is the .* operator, which is not overloadable, just
12215   // create a built-in binary operator.
12216   if (Opc == BO_PtrMemD)
12217     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12218
12219   // Build an empty overload set.
12220   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12221
12222   // Add the candidates from the given function set.
12223   AddFunctionCandidates(Fns, Args, CandidateSet);
12224
12225   // Add operator candidates that are member functions.
12226   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12227
12228   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12229   // performed for an assignment operator (nor for operator[] nor operator->,
12230   // which don't get here).
12231   if (Opc != BO_Assign)
12232     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12233                                          /*ExplicitTemplateArgs*/ nullptr,
12234                                          CandidateSet);
12235
12236   // Add builtin operator candidates.
12237   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12238
12239   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12240
12241   // Perform overload resolution.
12242   OverloadCandidateSet::iterator Best;
12243   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12244     case OR_Success: {
12245       // We found a built-in operator or an overloaded operator.
12246       FunctionDecl *FnDecl = Best->Function;
12247
12248       if (FnDecl) {
12249         // We matched an overloaded operator. Build a call to that
12250         // operator.
12251
12252         // Convert the arguments.
12253         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12254           // Best->Access is only meaningful for class members.
12255           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12256
12257           ExprResult Arg1 =
12258             PerformCopyInitialization(
12259               InitializedEntity::InitializeParameter(Context,
12260                                                      FnDecl->getParamDecl(0)),
12261               SourceLocation(), Args[1]);
12262           if (Arg1.isInvalid())
12263             return ExprError();
12264
12265           ExprResult Arg0 =
12266             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12267                                                 Best->FoundDecl, Method);
12268           if (Arg0.isInvalid())
12269             return ExprError();
12270           Args[0] = Arg0.getAs<Expr>();
12271           Args[1] = RHS = Arg1.getAs<Expr>();
12272         } else {
12273           // Convert the arguments.
12274           ExprResult Arg0 = PerformCopyInitialization(
12275             InitializedEntity::InitializeParameter(Context,
12276                                                    FnDecl->getParamDecl(0)),
12277             SourceLocation(), Args[0]);
12278           if (Arg0.isInvalid())
12279             return ExprError();
12280
12281           ExprResult Arg1 =
12282             PerformCopyInitialization(
12283               InitializedEntity::InitializeParameter(Context,
12284                                                      FnDecl->getParamDecl(1)),
12285               SourceLocation(), Args[1]);
12286           if (Arg1.isInvalid())
12287             return ExprError();
12288           Args[0] = LHS = Arg0.getAs<Expr>();
12289           Args[1] = RHS = Arg1.getAs<Expr>();
12290         }
12291
12292         // Build the actual expression node.
12293         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12294                                                   Best->FoundDecl,
12295                                                   HadMultipleCandidates, OpLoc);
12296         if (FnExpr.isInvalid())
12297           return ExprError();
12298
12299         // Determine the result type.
12300         QualType ResultTy = FnDecl->getReturnType();
12301         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12302         ResultTy = ResultTy.getNonLValueExprType(Context);
12303
12304         CXXOperatorCallExpr *TheCall =
12305           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12306                                             Args, ResultTy, VK, OpLoc,
12307                                             FPFeatures);
12308
12309         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12310                                 FnDecl))
12311           return ExprError();
12312
12313         ArrayRef<const Expr *> ArgsArray(Args, 2);
12314         const Expr *ImplicitThis = nullptr;
12315         // Cut off the implicit 'this'.
12316         if (isa<CXXMethodDecl>(FnDecl)) {
12317           ImplicitThis = ArgsArray[0];
12318           ArgsArray = ArgsArray.slice(1);
12319         }
12320
12321         // Check for a self move.
12322         if (Op == OO_Equal)
12323           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12324
12325         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12326                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12327                   VariadicDoesNotApply);
12328
12329         return MaybeBindToTemporary(TheCall);
12330       } else {
12331         // We matched a built-in operator. Convert the arguments, then
12332         // break out so that we will build the appropriate built-in
12333         // operator node.
12334         ExprResult ArgsRes0 =
12335           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12336                                     Best->Conversions[0], AA_Passing);
12337         if (ArgsRes0.isInvalid())
12338           return ExprError();
12339         Args[0] = ArgsRes0.get();
12340
12341         ExprResult ArgsRes1 =
12342           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12343                                     Best->Conversions[1], AA_Passing);
12344         if (ArgsRes1.isInvalid())
12345           return ExprError();
12346         Args[1] = ArgsRes1.get();
12347         break;
12348       }
12349     }
12350
12351     case OR_No_Viable_Function: {
12352       // C++ [over.match.oper]p9:
12353       //   If the operator is the operator , [...] and there are no
12354       //   viable functions, then the operator is assumed to be the
12355       //   built-in operator and interpreted according to clause 5.
12356       if (Opc == BO_Comma)
12357         break;
12358
12359       // For class as left operand for assignment or compound assigment
12360       // operator do not fall through to handling in built-in, but report that
12361       // no overloaded assignment operator found
12362       ExprResult Result = ExprError();
12363       if (Args[0]->getType()->isRecordType() &&
12364           Opc >= BO_Assign && Opc <= BO_OrAssign) {
12365         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
12366              << BinaryOperator::getOpcodeStr(Opc)
12367              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12368         if (Args[0]->getType()->isIncompleteType()) {
12369           Diag(OpLoc, diag::note_assign_lhs_incomplete)
12370             << Args[0]->getType()
12371             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12372         }
12373       } else {
12374         // This is an erroneous use of an operator which can be overloaded by
12375         // a non-member function. Check for non-member operators which were
12376         // defined too late to be candidates.
12377         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12378           // FIXME: Recover by calling the found function.
12379           return ExprError();
12380
12381         // No viable function; try to create a built-in operation, which will
12382         // produce an error. Then, show the non-viable candidates.
12383         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12384       }
12385       assert(Result.isInvalid() &&
12386              "C++ binary operator overloading is missing candidates!");
12387       if (Result.isInvalid())
12388         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12389                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
12390       return Result;
12391     }
12392
12393     case OR_Ambiguous:
12394       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
12395           << BinaryOperator::getOpcodeStr(Opc)
12396           << Args[0]->getType() << Args[1]->getType()
12397           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12398       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12399                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12400       return ExprError();
12401
12402     case OR_Deleted:
12403       if (isImplicitlyDeleted(Best->Function)) {
12404         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12405         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12406           << Context.getRecordType(Method->getParent())
12407           << getSpecialMember(Method);
12408
12409         // The user probably meant to call this special member. Just
12410         // explain why it's deleted.
12411         NoteDeletedFunction(Method);
12412         return ExprError();
12413       } else {
12414         Diag(OpLoc, diag::err_ovl_deleted_oper)
12415           << Best->Function->isDeleted()
12416           << BinaryOperator::getOpcodeStr(Opc)
12417           << getDeletedOrUnavailableSuffix(Best->Function)
12418           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12419       }
12420       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12421                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
12422       return ExprError();
12423   }
12424
12425   // We matched a built-in operator; build it.
12426   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12427 }
12428
12429 ExprResult
12430 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12431                                          SourceLocation RLoc,
12432                                          Expr *Base, Expr *Idx) {
12433   Expr *Args[2] = { Base, Idx };
12434   DeclarationName OpName =
12435       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12436
12437   // If either side is type-dependent, create an appropriate dependent
12438   // expression.
12439   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12440
12441     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12442     // CHECKME: no 'operator' keyword?
12443     DeclarationNameInfo OpNameInfo(OpName, LLoc);
12444     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12445     UnresolvedLookupExpr *Fn
12446       = UnresolvedLookupExpr::Create(Context, NamingClass,
12447                                      NestedNameSpecifierLoc(), OpNameInfo,
12448                                      /*ADL*/ true, /*Overloaded*/ false,
12449                                      UnresolvedSetIterator(),
12450                                      UnresolvedSetIterator());
12451     // Can't add any actual overloads yet
12452
12453     return new (Context)
12454         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12455                             Context.DependentTy, VK_RValue, RLoc, FPOptions());
12456   }
12457
12458   // Handle placeholders on both operands.
12459   if (checkPlaceholderForOverload(*this, Args[0]))
12460     return ExprError();
12461   if (checkPlaceholderForOverload(*this, Args[1]))
12462     return ExprError();
12463
12464   // Build an empty overload set.
12465   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12466
12467   // Subscript can only be overloaded as a member function.
12468
12469   // Add operator candidates that are member functions.
12470   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12471
12472   // Add builtin operator candidates.
12473   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12474
12475   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12476
12477   // Perform overload resolution.
12478   OverloadCandidateSet::iterator Best;
12479   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12480     case OR_Success: {
12481       // We found a built-in operator or an overloaded operator.
12482       FunctionDecl *FnDecl = Best->Function;
12483
12484       if (FnDecl) {
12485         // We matched an overloaded operator. Build a call to that
12486         // operator.
12487
12488         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12489
12490         // Convert the arguments.
12491         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12492         ExprResult Arg0 =
12493           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12494                                               Best->FoundDecl, Method);
12495         if (Arg0.isInvalid())
12496           return ExprError();
12497         Args[0] = Arg0.get();
12498
12499         // Convert the arguments.
12500         ExprResult InputInit
12501           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12502                                                       Context,
12503                                                       FnDecl->getParamDecl(0)),
12504                                       SourceLocation(),
12505                                       Args[1]);
12506         if (InputInit.isInvalid())
12507           return ExprError();
12508
12509         Args[1] = InputInit.getAs<Expr>();
12510
12511         // Build the actual expression node.
12512         DeclarationNameInfo OpLocInfo(OpName, LLoc);
12513         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12514         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12515                                                   Best->FoundDecl,
12516                                                   HadMultipleCandidates,
12517                                                   OpLocInfo.getLoc(),
12518                                                   OpLocInfo.getInfo());
12519         if (FnExpr.isInvalid())
12520           return ExprError();
12521
12522         // Determine the result type
12523         QualType ResultTy = FnDecl->getReturnType();
12524         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12525         ResultTy = ResultTy.getNonLValueExprType(Context);
12526
12527         CXXOperatorCallExpr *TheCall =
12528           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12529                                             FnExpr.get(), Args,
12530                                             ResultTy, VK, RLoc,
12531                                             FPOptions());
12532
12533         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12534           return ExprError();
12535
12536         if (CheckFunctionCall(Method, TheCall,
12537                               Method->getType()->castAs<FunctionProtoType>()))
12538           return ExprError();
12539
12540         return MaybeBindToTemporary(TheCall);
12541       } else {
12542         // We matched a built-in operator. Convert the arguments, then
12543         // break out so that we will build the appropriate built-in
12544         // operator node.
12545         ExprResult ArgsRes0 =
12546           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12547                                     Best->Conversions[0], AA_Passing);
12548         if (ArgsRes0.isInvalid())
12549           return ExprError();
12550         Args[0] = ArgsRes0.get();
12551
12552         ExprResult ArgsRes1 =
12553           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12554                                     Best->Conversions[1], AA_Passing);
12555         if (ArgsRes1.isInvalid())
12556           return ExprError();
12557         Args[1] = ArgsRes1.get();
12558
12559         break;
12560       }
12561     }
12562
12563     case OR_No_Viable_Function: {
12564       if (CandidateSet.empty())
12565         Diag(LLoc, diag::err_ovl_no_oper)
12566           << Args[0]->getType() << /*subscript*/ 0
12567           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12568       else
12569         Diag(LLoc, diag::err_ovl_no_viable_subscript)
12570           << Args[0]->getType()
12571           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12572       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12573                                   "[]", LLoc);
12574       return ExprError();
12575     }
12576
12577     case OR_Ambiguous:
12578       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
12579           << "[]"
12580           << Args[0]->getType() << Args[1]->getType()
12581           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12582       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12583                                   "[]", LLoc);
12584       return ExprError();
12585
12586     case OR_Deleted:
12587       Diag(LLoc, diag::err_ovl_deleted_oper)
12588         << Best->Function->isDeleted() << "[]"
12589         << getDeletedOrUnavailableSuffix(Best->Function)
12590         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12591       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12592                                   "[]", LLoc);
12593       return ExprError();
12594     }
12595
12596   // We matched a built-in operator; build it.
12597   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12598 }
12599
12600 /// BuildCallToMemberFunction - Build a call to a member
12601 /// function. MemExpr is the expression that refers to the member
12602 /// function (and includes the object parameter), Args/NumArgs are the
12603 /// arguments to the function call (not including the object
12604 /// parameter). The caller needs to validate that the member
12605 /// expression refers to a non-static member function or an overloaded
12606 /// member function.
12607 ExprResult
12608 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12609                                 SourceLocation LParenLoc,
12610                                 MultiExprArg Args,
12611                                 SourceLocation RParenLoc) {
12612   assert(MemExprE->getType() == Context.BoundMemberTy ||
12613          MemExprE->getType() == Context.OverloadTy);
12614
12615   // Dig out the member expression. This holds both the object
12616   // argument and the member function we're referring to.
12617   Expr *NakedMemExpr = MemExprE->IgnoreParens();
12618
12619   // Determine whether this is a call to a pointer-to-member function.
12620   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12621     assert(op->getType() == Context.BoundMemberTy);
12622     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12623
12624     QualType fnType =
12625       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12626
12627     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12628     QualType resultType = proto->getCallResultType(Context);
12629     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12630
12631     // Check that the object type isn't more qualified than the
12632     // member function we're calling.
12633     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12634
12635     QualType objectType = op->getLHS()->getType();
12636     if (op->getOpcode() == BO_PtrMemI)
12637       objectType = objectType->castAs<PointerType>()->getPointeeType();
12638     Qualifiers objectQuals = objectType.getQualifiers();
12639
12640     Qualifiers difference = objectQuals - funcQuals;
12641     difference.removeObjCGCAttr();
12642     difference.removeAddressSpace();
12643     if (difference) {
12644       std::string qualsString = difference.getAsString();
12645       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12646         << fnType.getUnqualifiedType()
12647         << qualsString
12648         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12649     }
12650
12651     CXXMemberCallExpr *call
12652       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12653                                         resultType, valueKind, RParenLoc);
12654
12655     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12656                             call, nullptr))
12657       return ExprError();
12658
12659     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12660       return ExprError();
12661
12662     if (CheckOtherCall(call, proto))
12663       return ExprError();
12664
12665     return MaybeBindToTemporary(call);
12666   }
12667
12668   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12669     return new (Context)
12670         CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12671
12672   UnbridgedCastsSet UnbridgedCasts;
12673   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12674     return ExprError();
12675
12676   MemberExpr *MemExpr;
12677   CXXMethodDecl *Method = nullptr;
12678   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12679   NestedNameSpecifier *Qualifier = nullptr;
12680   if (isa<MemberExpr>(NakedMemExpr)) {
12681     MemExpr = cast<MemberExpr>(NakedMemExpr);
12682     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12683     FoundDecl = MemExpr->getFoundDecl();
12684     Qualifier = MemExpr->getQualifier();
12685     UnbridgedCasts.restore();
12686   } else {
12687     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12688     Qualifier = UnresExpr->getQualifier();
12689
12690     QualType ObjectType = UnresExpr->getBaseType();
12691     Expr::Classification ObjectClassification
12692       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12693                             : UnresExpr->getBase()->Classify(Context);
12694
12695     // Add overload candidates
12696     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12697                                       OverloadCandidateSet::CSK_Normal);
12698
12699     // FIXME: avoid copy.
12700     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12701     if (UnresExpr->hasExplicitTemplateArgs()) {
12702       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12703       TemplateArgs = &TemplateArgsBuffer;
12704     }
12705
12706     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12707            E = UnresExpr->decls_end(); I != E; ++I) {
12708
12709       NamedDecl *Func = *I;
12710       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12711       if (isa<UsingShadowDecl>(Func))
12712         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12713
12714
12715       // Microsoft supports direct constructor calls.
12716       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12717         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12718                              Args, CandidateSet);
12719       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12720         // If explicit template arguments were provided, we can't call a
12721         // non-template member function.
12722         if (TemplateArgs)
12723           continue;
12724
12725         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12726                            ObjectClassification, Args, CandidateSet,
12727                            /*SuppressUserConversions=*/false);
12728       } else {
12729         AddMethodTemplateCandidate(
12730             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12731             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12732             /*SuppressUsedConversions=*/false);
12733       }
12734     }
12735
12736     DeclarationName DeclName = UnresExpr->getMemberName();
12737
12738     UnbridgedCasts.restore();
12739
12740     OverloadCandidateSet::iterator Best;
12741     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12742                                             Best)) {
12743     case OR_Success:
12744       Method = cast<CXXMethodDecl>(Best->Function);
12745       FoundDecl = Best->FoundDecl;
12746       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12747       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12748         return ExprError();
12749       // If FoundDecl is different from Method (such as if one is a template
12750       // and the other a specialization), make sure DiagnoseUseOfDecl is
12751       // called on both.
12752       // FIXME: This would be more comprehensively addressed by modifying
12753       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12754       // being used.
12755       if (Method != FoundDecl.getDecl() &&
12756                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12757         return ExprError();
12758       break;
12759
12760     case OR_No_Viable_Function:
12761       Diag(UnresExpr->getMemberLoc(),
12762            diag::err_ovl_no_viable_member_function_in_call)
12763         << DeclName << MemExprE->getSourceRange();
12764       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12765       // FIXME: Leaking incoming expressions!
12766       return ExprError();
12767
12768     case OR_Ambiguous:
12769       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12770         << DeclName << MemExprE->getSourceRange();
12771       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12772       // FIXME: Leaking incoming expressions!
12773       return ExprError();
12774
12775     case OR_Deleted:
12776       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12777         << Best->Function->isDeleted()
12778         << DeclName
12779         << getDeletedOrUnavailableSuffix(Best->Function)
12780         << MemExprE->getSourceRange();
12781       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12782       // FIXME: Leaking incoming expressions!
12783       return ExprError();
12784     }
12785
12786     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12787
12788     // If overload resolution picked a static member, build a
12789     // non-member call based on that function.
12790     if (Method->isStatic()) {
12791       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12792                                    RParenLoc);
12793     }
12794
12795     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12796   }
12797
12798   QualType ResultType = Method->getReturnType();
12799   ExprValueKind VK = Expr::getValueKindForType(ResultType);
12800   ResultType = ResultType.getNonLValueExprType(Context);
12801
12802   assert(Method && "Member call to something that isn't a method?");
12803   CXXMemberCallExpr *TheCall =
12804     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12805                                     ResultType, VK, RParenLoc);
12806
12807   // Check for a valid return type.
12808   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12809                           TheCall, Method))
12810     return ExprError();
12811
12812   // Convert the object argument (for a non-static member function call).
12813   // We only need to do this if there was actually an overload; otherwise
12814   // it was done at lookup.
12815   if (!Method->isStatic()) {
12816     ExprResult ObjectArg =
12817       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12818                                           FoundDecl, Method);
12819     if (ObjectArg.isInvalid())
12820       return ExprError();
12821     MemExpr->setBase(ObjectArg.get());
12822   }
12823
12824   // Convert the rest of the arguments
12825   const FunctionProtoType *Proto =
12826     Method->getType()->getAs<FunctionProtoType>();
12827   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12828                               RParenLoc))
12829     return ExprError();
12830
12831   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12832
12833   if (CheckFunctionCall(Method, TheCall, Proto))
12834     return ExprError();
12835
12836   // In the case the method to call was not selected by the overloading
12837   // resolution process, we still need to handle the enable_if attribute. Do
12838   // that here, so it will not hide previous -- and more relevant -- errors.
12839   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12840     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12841       Diag(MemE->getMemberLoc(),
12842            diag::err_ovl_no_viable_member_function_in_call)
12843           << Method << Method->getSourceRange();
12844       Diag(Method->getLocation(),
12845            diag::note_ovl_candidate_disabled_by_function_cond_attr)
12846           << Attr->getCond()->getSourceRange() << Attr->getMessage();
12847       return ExprError();
12848     }
12849   }
12850
12851   if ((isa<CXXConstructorDecl>(CurContext) ||
12852        isa<CXXDestructorDecl>(CurContext)) &&
12853       TheCall->getMethodDecl()->isPure()) {
12854     const CXXMethodDecl *MD = TheCall->getMethodDecl();
12855
12856     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12857         MemExpr->performsVirtualDispatch(getLangOpts())) {
12858       Diag(MemExpr->getLocStart(),
12859            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12860         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12861         << MD->getParent()->getDeclName();
12862
12863       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12864       if (getLangOpts().AppleKext)
12865         Diag(MemExpr->getLocStart(),
12866              diag::note_pure_qualified_call_kext)
12867              << MD->getParent()->getDeclName()
12868              << MD->getDeclName();
12869     }
12870   }
12871
12872   if (CXXDestructorDecl *DD =
12873           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12874     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12875     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12876     CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12877                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12878                          MemExpr->getMemberLoc());
12879   }
12880
12881   return MaybeBindToTemporary(TheCall);
12882 }
12883
12884 /// BuildCallToObjectOfClassType - Build a call to an object of class
12885 /// type (C++ [over.call.object]), which can end up invoking an
12886 /// overloaded function call operator (@c operator()) or performing a
12887 /// user-defined conversion on the object argument.
12888 ExprResult
12889 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12890                                    SourceLocation LParenLoc,
12891                                    MultiExprArg Args,
12892                                    SourceLocation RParenLoc) {
12893   if (checkPlaceholderForOverload(*this, Obj))
12894     return ExprError();
12895   ExprResult Object = Obj;
12896
12897   UnbridgedCastsSet UnbridgedCasts;
12898   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12899     return ExprError();
12900
12901   assert(Object.get()->getType()->isRecordType() &&
12902          "Requires object type argument");
12903   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12904
12905   // C++ [over.call.object]p1:
12906   //  If the primary-expression E in the function call syntax
12907   //  evaluates to a class object of type "cv T", then the set of
12908   //  candidate functions includes at least the function call
12909   //  operators of T. The function call operators of T are obtained by
12910   //  ordinary lookup of the name operator() in the context of
12911   //  (E).operator().
12912   OverloadCandidateSet CandidateSet(LParenLoc,
12913                                     OverloadCandidateSet::CSK_Operator);
12914   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12915
12916   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12917                           diag::err_incomplete_object_call, Object.get()))
12918     return true;
12919
12920   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12921   LookupQualifiedName(R, Record->getDecl());
12922   R.suppressDiagnostics();
12923
12924   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12925        Oper != OperEnd; ++Oper) {
12926     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12927                        Object.get()->Classify(Context), Args, CandidateSet,
12928                        /*SuppressUserConversions=*/false);
12929   }
12930
12931   // C++ [over.call.object]p2:
12932   //   In addition, for each (non-explicit in C++0x) conversion function
12933   //   declared in T of the form
12934   //
12935   //        operator conversion-type-id () cv-qualifier;
12936   //
12937   //   where cv-qualifier is the same cv-qualification as, or a
12938   //   greater cv-qualification than, cv, and where conversion-type-id
12939   //   denotes the type "pointer to function of (P1,...,Pn) returning
12940   //   R", or the type "reference to pointer to function of
12941   //   (P1,...,Pn) returning R", or the type "reference to function
12942   //   of (P1,...,Pn) returning R", a surrogate call function [...]
12943   //   is also considered as a candidate function. Similarly,
12944   //   surrogate call functions are added to the set of candidate
12945   //   functions for each conversion function declared in an
12946   //   accessible base class provided the function is not hidden
12947   //   within T by another intervening declaration.
12948   const auto &Conversions =
12949       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12950   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12951     NamedDecl *D = *I;
12952     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12953     if (isa<UsingShadowDecl>(D))
12954       D = cast<UsingShadowDecl>(D)->getTargetDecl();
12955
12956     // Skip over templated conversion functions; they aren't
12957     // surrogates.
12958     if (isa<FunctionTemplateDecl>(D))
12959       continue;
12960
12961     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12962     if (!Conv->isExplicit()) {
12963       // Strip the reference type (if any) and then the pointer type (if
12964       // any) to get down to what might be a function type.
12965       QualType ConvType = Conv->getConversionType().getNonReferenceType();
12966       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12967         ConvType = ConvPtrType->getPointeeType();
12968
12969       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12970       {
12971         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12972                               Object.get(), Args, CandidateSet);
12973       }
12974     }
12975   }
12976
12977   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12978
12979   // Perform overload resolution.
12980   OverloadCandidateSet::iterator Best;
12981   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12982                              Best)) {
12983   case OR_Success:
12984     // Overload resolution succeeded; we'll build the appropriate call
12985     // below.
12986     break;
12987
12988   case OR_No_Viable_Function:
12989     if (CandidateSet.empty())
12990       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12991         << Object.get()->getType() << /*call*/ 1
12992         << Object.get()->getSourceRange();
12993     else
12994       Diag(Object.get()->getLocStart(),
12995            diag::err_ovl_no_viable_object_call)
12996         << Object.get()->getType() << Object.get()->getSourceRange();
12997     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12998     break;
12999
13000   case OR_Ambiguous:
13001     Diag(Object.get()->getLocStart(),
13002          diag::err_ovl_ambiguous_object_call)
13003       << Object.get()->getType() << Object.get()->getSourceRange();
13004     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13005     break;
13006
13007   case OR_Deleted:
13008     Diag(Object.get()->getLocStart(),
13009          diag::err_ovl_deleted_object_call)
13010       << Best->Function->isDeleted()
13011       << Object.get()->getType()
13012       << getDeletedOrUnavailableSuffix(Best->Function)
13013       << Object.get()->getSourceRange();
13014     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13015     break;
13016   }
13017
13018   if (Best == CandidateSet.end())
13019     return true;
13020
13021   UnbridgedCasts.restore();
13022
13023   if (Best->Function == nullptr) {
13024     // Since there is no function declaration, this is one of the
13025     // surrogate candidates. Dig out the conversion function.
13026     CXXConversionDecl *Conv
13027       = cast<CXXConversionDecl>(
13028                          Best->Conversions[0].UserDefined.ConversionFunction);
13029
13030     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13031                               Best->FoundDecl);
13032     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13033       return ExprError();
13034     assert(Conv == Best->FoundDecl.getDecl() &&
13035              "Found Decl & conversion-to-functionptr should be same, right?!");
13036     // We selected one of the surrogate functions that converts the
13037     // object parameter to a function pointer. Perform the conversion
13038     // on the object argument, then let ActOnCallExpr finish the job.
13039
13040     // Create an implicit member expr to refer to the conversion operator.
13041     // and then call it.
13042     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13043                                              Conv, HadMultipleCandidates);
13044     if (Call.isInvalid())
13045       return ExprError();
13046     // Record usage of conversion in an implicit cast.
13047     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13048                                     CK_UserDefinedConversion, Call.get(),
13049                                     nullptr, VK_RValue);
13050
13051     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13052   }
13053
13054   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13055
13056   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13057   // that calls this method, using Object for the implicit object
13058   // parameter and passing along the remaining arguments.
13059   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13060
13061   // An error diagnostic has already been printed when parsing the declaration.
13062   if (Method->isInvalidDecl())
13063     return ExprError();
13064
13065   const FunctionProtoType *Proto =
13066     Method->getType()->getAs<FunctionProtoType>();
13067
13068   unsigned NumParams = Proto->getNumParams();
13069
13070   DeclarationNameInfo OpLocInfo(
13071                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13072   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13073   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13074                                            HadMultipleCandidates,
13075                                            OpLocInfo.getLoc(),
13076                                            OpLocInfo.getInfo());
13077   if (NewFn.isInvalid())
13078     return true;
13079
13080   // Build the full argument list for the method call (the implicit object
13081   // parameter is placed at the beginning of the list).
13082   SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13083   MethodArgs[0] = Object.get();
13084   std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13085
13086   // Once we've built TheCall, all of the expressions are properly
13087   // owned.
13088   QualType ResultTy = Method->getReturnType();
13089   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13090   ResultTy = ResultTy.getNonLValueExprType(Context);
13091
13092   CXXOperatorCallExpr *TheCall = new (Context)
13093       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13094                           VK, RParenLoc, FPOptions());
13095
13096   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13097     return true;
13098
13099   // We may have default arguments. If so, we need to allocate more
13100   // slots in the call for them.
13101   if (Args.size() < NumParams)
13102     TheCall->setNumArgs(Context, NumParams + 1);
13103
13104   bool IsError = false;
13105
13106   // Initialize the implicit object parameter.
13107   ExprResult ObjRes =
13108     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13109                                         Best->FoundDecl, Method);
13110   if (ObjRes.isInvalid())
13111     IsError = true;
13112   else
13113     Object = ObjRes;
13114   TheCall->setArg(0, Object.get());
13115
13116   // Check the argument types.
13117   for (unsigned i = 0; i != NumParams; i++) {
13118     Expr *Arg;
13119     if (i < Args.size()) {
13120       Arg = Args[i];
13121
13122       // Pass the argument.
13123
13124       ExprResult InputInit
13125         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13126                                                     Context,
13127                                                     Method->getParamDecl(i)),
13128                                     SourceLocation(), Arg);
13129
13130       IsError |= InputInit.isInvalid();
13131       Arg = InputInit.getAs<Expr>();
13132     } else {
13133       ExprResult DefArg
13134         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13135       if (DefArg.isInvalid()) {
13136         IsError = true;
13137         break;
13138       }
13139
13140       Arg = DefArg.getAs<Expr>();
13141     }
13142
13143     TheCall->setArg(i + 1, Arg);
13144   }
13145
13146   // If this is a variadic call, handle args passed through "...".
13147   if (Proto->isVariadic()) {
13148     // Promote the arguments (C99 6.5.2.2p7).
13149     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13150       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13151                                                         nullptr);
13152       IsError |= Arg.isInvalid();
13153       TheCall->setArg(i + 1, Arg.get());
13154     }
13155   }
13156
13157   if (IsError) return true;
13158
13159   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13160
13161   if (CheckFunctionCall(Method, TheCall, Proto))
13162     return true;
13163
13164   return MaybeBindToTemporary(TheCall);
13165 }
13166
13167 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13168 ///  (if one exists), where @c Base is an expression of class type and
13169 /// @c Member is the name of the member we're trying to find.
13170 ExprResult
13171 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13172                                bool *NoArrowOperatorFound) {
13173   assert(Base->getType()->isRecordType() &&
13174          "left-hand side must have class type");
13175
13176   if (checkPlaceholderForOverload(*this, Base))
13177     return ExprError();
13178
13179   SourceLocation Loc = Base->getExprLoc();
13180
13181   // C++ [over.ref]p1:
13182   //
13183   //   [...] An expression x->m is interpreted as (x.operator->())->m
13184   //   for a class object x of type T if T::operator->() exists and if
13185   //   the operator is selected as the best match function by the
13186   //   overload resolution mechanism (13.3).
13187   DeclarationName OpName =
13188     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13189   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13190   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13191
13192   if (RequireCompleteType(Loc, Base->getType(),
13193                           diag::err_typecheck_incomplete_tag, Base))
13194     return ExprError();
13195
13196   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13197   LookupQualifiedName(R, BaseRecord->getDecl());
13198   R.suppressDiagnostics();
13199
13200   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13201        Oper != OperEnd; ++Oper) {
13202     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13203                        None, CandidateSet, /*SuppressUserConversions=*/false);
13204   }
13205
13206   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13207
13208   // Perform overload resolution.
13209   OverloadCandidateSet::iterator Best;
13210   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13211   case OR_Success:
13212     // Overload resolution succeeded; we'll build the call below.
13213     break;
13214
13215   case OR_No_Viable_Function:
13216     if (CandidateSet.empty()) {
13217       QualType BaseType = Base->getType();
13218       if (NoArrowOperatorFound) {
13219         // Report this specific error to the caller instead of emitting a
13220         // diagnostic, as requested.
13221         *NoArrowOperatorFound = true;
13222         return ExprError();
13223       }
13224       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13225         << BaseType << Base->getSourceRange();
13226       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13227         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13228           << FixItHint::CreateReplacement(OpLoc, ".");
13229       }
13230     } else
13231       Diag(OpLoc, diag::err_ovl_no_viable_oper)
13232         << "operator->" << Base->getSourceRange();
13233     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13234     return ExprError();
13235
13236   case OR_Ambiguous:
13237     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
13238       << "->" << Base->getType() << Base->getSourceRange();
13239     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13240     return ExprError();
13241
13242   case OR_Deleted:
13243     Diag(OpLoc,  diag::err_ovl_deleted_oper)
13244       << Best->Function->isDeleted()
13245       << "->"
13246       << getDeletedOrUnavailableSuffix(Best->Function)
13247       << Base->getSourceRange();
13248     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13249     return ExprError();
13250   }
13251
13252   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13253
13254   // Convert the object parameter.
13255   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13256   ExprResult BaseResult =
13257     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13258                                         Best->FoundDecl, Method);
13259   if (BaseResult.isInvalid())
13260     return ExprError();
13261   Base = BaseResult.get();
13262
13263   // Build the operator call.
13264   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13265                                             HadMultipleCandidates, OpLoc);
13266   if (FnExpr.isInvalid())
13267     return ExprError();
13268
13269   QualType ResultTy = Method->getReturnType();
13270   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13271   ResultTy = ResultTy.getNonLValueExprType(Context);
13272   CXXOperatorCallExpr *TheCall =
13273     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13274                                       Base, ResultTy, VK, OpLoc, FPOptions());
13275
13276   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13277     return ExprError();
13278
13279   if (CheckFunctionCall(Method, TheCall,
13280                         Method->getType()->castAs<FunctionProtoType>()))
13281     return ExprError();
13282
13283   return MaybeBindToTemporary(TheCall);
13284 }
13285
13286 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13287 /// a literal operator described by the provided lookup results.
13288 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13289                                           DeclarationNameInfo &SuffixInfo,
13290                                           ArrayRef<Expr*> Args,
13291                                           SourceLocation LitEndLoc,
13292                                        TemplateArgumentListInfo *TemplateArgs) {
13293   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13294
13295   OverloadCandidateSet CandidateSet(UDSuffixLoc,
13296                                     OverloadCandidateSet::CSK_Normal);
13297   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13298                         /*SuppressUserConversions=*/true);
13299
13300   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13301
13302   // Perform overload resolution. This will usually be trivial, but might need
13303   // to perform substitutions for a literal operator template.
13304   OverloadCandidateSet::iterator Best;
13305   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13306   case OR_Success:
13307   case OR_Deleted:
13308     break;
13309
13310   case OR_No_Viable_Function:
13311     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13312       << R.getLookupName();
13313     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13314     return ExprError();
13315
13316   case OR_Ambiguous:
13317     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13318     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13319     return ExprError();
13320   }
13321
13322   FunctionDecl *FD = Best->Function;
13323   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13324                                         HadMultipleCandidates,
13325                                         SuffixInfo.getLoc(),
13326                                         SuffixInfo.getInfo());
13327   if (Fn.isInvalid())
13328     return true;
13329
13330   // Check the argument types. This should almost always be a no-op, except
13331   // that array-to-pointer decay is applied to string literals.
13332   Expr *ConvArgs[2];
13333   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13334     ExprResult InputInit = PerformCopyInitialization(
13335       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13336       SourceLocation(), Args[ArgIdx]);
13337     if (InputInit.isInvalid())
13338       return true;
13339     ConvArgs[ArgIdx] = InputInit.get();
13340   }
13341
13342   QualType ResultTy = FD->getReturnType();
13343   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13344   ResultTy = ResultTy.getNonLValueExprType(Context);
13345
13346   UserDefinedLiteral *UDL =
13347     new (Context) UserDefinedLiteral(Context, Fn.get(),
13348                                      llvm::makeArrayRef(ConvArgs, Args.size()),
13349                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
13350
13351   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13352     return ExprError();
13353
13354   if (CheckFunctionCall(FD, UDL, nullptr))
13355     return ExprError();
13356
13357   return MaybeBindToTemporary(UDL);
13358 }
13359
13360 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13361 /// given LookupResult is non-empty, it is assumed to describe a member which
13362 /// will be invoked. Otherwise, the function will be found via argument
13363 /// dependent lookup.
13364 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13365 /// otherwise CallExpr is set to ExprError() and some non-success value
13366 /// is returned.
13367 Sema::ForRangeStatus
13368 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13369                                 SourceLocation RangeLoc,
13370                                 const DeclarationNameInfo &NameInfo,
13371                                 LookupResult &MemberLookup,
13372                                 OverloadCandidateSet *CandidateSet,
13373                                 Expr *Range, ExprResult *CallExpr) {
13374   Scope *S = nullptr;
13375
13376   CandidateSet->clear();
13377   if (!MemberLookup.empty()) {
13378     ExprResult MemberRef =
13379         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13380                                  /*IsPtr=*/false, CXXScopeSpec(),
13381                                  /*TemplateKWLoc=*/SourceLocation(),
13382                                  /*FirstQualifierInScope=*/nullptr,
13383                                  MemberLookup,
13384                                  /*TemplateArgs=*/nullptr, S);
13385     if (MemberRef.isInvalid()) {
13386       *CallExpr = ExprError();
13387       return FRS_DiagnosticIssued;
13388     }
13389     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13390     if (CallExpr->isInvalid()) {
13391       *CallExpr = ExprError();
13392       return FRS_DiagnosticIssued;
13393     }
13394   } else {
13395     UnresolvedSet<0> FoundNames;
13396     UnresolvedLookupExpr *Fn =
13397       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13398                                    NestedNameSpecifierLoc(), NameInfo,
13399                                    /*NeedsADL=*/true, /*Overloaded=*/false,
13400                                    FoundNames.begin(), FoundNames.end());
13401
13402     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13403                                                     CandidateSet, CallExpr);
13404     if (CandidateSet->empty() || CandidateSetError) {
13405       *CallExpr = ExprError();
13406       return FRS_NoViableFunction;
13407     }
13408     OverloadCandidateSet::iterator Best;
13409     OverloadingResult OverloadResult =
13410         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13411
13412     if (OverloadResult == OR_No_Viable_Function) {
13413       *CallExpr = ExprError();
13414       return FRS_NoViableFunction;
13415     }
13416     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13417                                          Loc, nullptr, CandidateSet, &Best,
13418                                          OverloadResult,
13419                                          /*AllowTypoCorrection=*/false);
13420     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13421       *CallExpr = ExprError();
13422       return FRS_DiagnosticIssued;
13423     }
13424   }
13425   return FRS_Success;
13426 }
13427
13428
13429 /// FixOverloadedFunctionReference - E is an expression that refers to
13430 /// a C++ overloaded function (possibly with some parentheses and
13431 /// perhaps a '&' around it). We have resolved the overloaded function
13432 /// to the function declaration Fn, so patch up the expression E to
13433 /// refer (possibly indirectly) to Fn. Returns the new expr.
13434 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13435                                            FunctionDecl *Fn) {
13436   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13437     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13438                                                    Found, Fn);
13439     if (SubExpr == PE->getSubExpr())
13440       return PE;
13441
13442     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13443   }
13444
13445   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13446     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13447                                                    Found, Fn);
13448     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13449                                SubExpr->getType()) &&
13450            "Implicit cast type cannot be determined from overload");
13451     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13452     if (SubExpr == ICE->getSubExpr())
13453       return ICE;
13454
13455     return ImplicitCastExpr::Create(Context, ICE->getType(),
13456                                     ICE->getCastKind(),
13457                                     SubExpr, nullptr,
13458                                     ICE->getValueKind());
13459   }
13460
13461   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13462     if (!GSE->isResultDependent()) {
13463       Expr *SubExpr =
13464           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13465       if (SubExpr == GSE->getResultExpr())
13466         return GSE;
13467
13468       // Replace the resulting type information before rebuilding the generic
13469       // selection expression.
13470       ArrayRef<Expr *> A = GSE->getAssocExprs();
13471       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13472       unsigned ResultIdx = GSE->getResultIndex();
13473       AssocExprs[ResultIdx] = SubExpr;
13474
13475       return new (Context) GenericSelectionExpr(
13476           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13477           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13478           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13479           ResultIdx);
13480     }
13481     // Rather than fall through to the unreachable, return the original generic
13482     // selection expression.
13483     return GSE;
13484   }
13485
13486   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13487     assert(UnOp->getOpcode() == UO_AddrOf &&
13488            "Can only take the address of an overloaded function");
13489     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13490       if (Method->isStatic()) {
13491         // Do nothing: static member functions aren't any different
13492         // from non-member functions.
13493       } else {
13494         // Fix the subexpression, which really has to be an
13495         // UnresolvedLookupExpr holding an overloaded member function
13496         // or template.
13497         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13498                                                        Found, Fn);
13499         if (SubExpr == UnOp->getSubExpr())
13500           return UnOp;
13501
13502         assert(isa<DeclRefExpr>(SubExpr)
13503                && "fixed to something other than a decl ref");
13504         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13505                && "fixed to a member ref with no nested name qualifier");
13506
13507         // We have taken the address of a pointer to member
13508         // function. Perform the computation here so that we get the
13509         // appropriate pointer to member type.
13510         QualType ClassType
13511           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13512         QualType MemPtrType
13513           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13514         // Under the MS ABI, lock down the inheritance model now.
13515         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13516           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13517
13518         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13519                                            VK_RValue, OK_Ordinary,
13520                                            UnOp->getOperatorLoc());
13521       }
13522     }
13523     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13524                                                    Found, Fn);
13525     if (SubExpr == UnOp->getSubExpr())
13526       return UnOp;
13527
13528     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13529                                      Context.getPointerType(SubExpr->getType()),
13530                                        VK_RValue, OK_Ordinary,
13531                                        UnOp->getOperatorLoc());
13532   }
13533
13534   // C++ [except.spec]p17:
13535   //   An exception-specification is considered to be needed when:
13536   //   - in an expression the function is the unique lookup result or the
13537   //     selected member of a set of overloaded functions
13538   if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13539     ResolveExceptionSpec(E->getExprLoc(), FPT);
13540
13541   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13542     // FIXME: avoid copy.
13543     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13544     if (ULE->hasExplicitTemplateArgs()) {
13545       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13546       TemplateArgs = &TemplateArgsBuffer;
13547     }
13548
13549     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13550                                            ULE->getQualifierLoc(),
13551                                            ULE->getTemplateKeywordLoc(),
13552                                            Fn,
13553                                            /*enclosing*/ false, // FIXME?
13554                                            ULE->getNameLoc(),
13555                                            Fn->getType(),
13556                                            VK_LValue,
13557                                            Found.getDecl(),
13558                                            TemplateArgs);
13559     MarkDeclRefReferenced(DRE);
13560     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13561     return DRE;
13562   }
13563
13564   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13565     // FIXME: avoid copy.
13566     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13567     if (MemExpr->hasExplicitTemplateArgs()) {
13568       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13569       TemplateArgs = &TemplateArgsBuffer;
13570     }
13571
13572     Expr *Base;
13573
13574     // If we're filling in a static method where we used to have an
13575     // implicit member access, rewrite to a simple decl ref.
13576     if (MemExpr->isImplicitAccess()) {
13577       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13578         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13579                                                MemExpr->getQualifierLoc(),
13580                                                MemExpr->getTemplateKeywordLoc(),
13581                                                Fn,
13582                                                /*enclosing*/ false,
13583                                                MemExpr->getMemberLoc(),
13584                                                Fn->getType(),
13585                                                VK_LValue,
13586                                                Found.getDecl(),
13587                                                TemplateArgs);
13588         MarkDeclRefReferenced(DRE);
13589         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13590         return DRE;
13591       } else {
13592         SourceLocation Loc = MemExpr->getMemberLoc();
13593         if (MemExpr->getQualifier())
13594           Loc = MemExpr->getQualifierLoc().getBeginLoc();
13595         CheckCXXThisCapture(Loc);
13596         Base = new (Context) CXXThisExpr(Loc,
13597                                          MemExpr->getBaseType(),
13598                                          /*isImplicit=*/true);
13599       }
13600     } else
13601       Base = MemExpr->getBase();
13602
13603     ExprValueKind valueKind;
13604     QualType type;
13605     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13606       valueKind = VK_LValue;
13607       type = Fn->getType();
13608     } else {
13609       valueKind = VK_RValue;
13610       type = Context.BoundMemberTy;
13611     }
13612
13613     MemberExpr *ME = MemberExpr::Create(
13614         Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13615         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13616         MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13617         OK_Ordinary);
13618     ME->setHadMultipleCandidates(true);
13619     MarkMemberReferenced(ME);
13620     return ME;
13621   }
13622
13623   llvm_unreachable("Invalid reference to overloaded function");
13624 }
13625
13626 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13627                                                 DeclAccessPair Found,
13628                                                 FunctionDecl *Fn) {
13629   return FixOverloadedFunctionReference(E.get(), Found, Fn);
13630 }