1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
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/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Template.h"
18 #include "clang/Sema/TemplateDeduction.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include <algorithm>
34 
35 namespace clang {
36 using namespace sema;
37 
38 /// A convenience routine for creating a decayed reference to a
39 /// function.
40 static ExprResult
41 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
42                       SourceLocation Loc = SourceLocation(),
43                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
44   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
45                                                  VK_LValue, Loc, LocInfo);
46   if (HadMultipleCandidates)
47     DRE->setHadMultipleCandidates(true);
48   ExprResult E = S.Owned(DRE);
49   E = S.DefaultFunctionArrayConversion(E.take());
50   if (E.isInvalid())
51     return ExprError();
52   return move(E);
53 }
54 
55 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
56                                  bool InOverloadResolution,
57                                  StandardConversionSequence &SCS,
58                                  bool CStyle,
59                                  bool AllowObjCWritebackConversion);
60 
61 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
62                                                  QualType &ToType,
63                                                  bool InOverloadResolution,
64                                                  StandardConversionSequence &SCS,
65                                                  bool CStyle);
66 static OverloadingResult
67 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
68                         UserDefinedConversionSequence& User,
69                         OverloadCandidateSet& Conversions,
70                         bool AllowExplicit);
71 
72 
73 static ImplicitConversionSequence::CompareKind
74 CompareStandardConversionSequences(Sema &S,
75                                    const StandardConversionSequence& SCS1,
76                                    const StandardConversionSequence& SCS2);
77 
78 static ImplicitConversionSequence::CompareKind
79 CompareQualificationConversions(Sema &S,
80                                 const StandardConversionSequence& SCS1,
81                                 const StandardConversionSequence& SCS2);
82 
83 static ImplicitConversionSequence::CompareKind
84 CompareDerivedToBaseConversions(Sema &S,
85                                 const StandardConversionSequence& SCS1,
86                                 const StandardConversionSequence& SCS2);
87 
88 
89 
90 /// GetConversionCategory - Retrieve the implicit conversion
91 /// category corresponding to the given implicit conversion kind.
92 ImplicitConversionCategory
93 GetConversionCategory(ImplicitConversionKind Kind) {
94   static const ImplicitConversionCategory
95     Category[(int)ICK_Num_Conversion_Kinds] = {
96     ICC_Identity,
97     ICC_Lvalue_Transformation,
98     ICC_Lvalue_Transformation,
99     ICC_Lvalue_Transformation,
100     ICC_Identity,
101     ICC_Qualification_Adjustment,
102     ICC_Promotion,
103     ICC_Promotion,
104     ICC_Promotion,
105     ICC_Conversion,
106     ICC_Conversion,
107     ICC_Conversion,
108     ICC_Conversion,
109     ICC_Conversion,
110     ICC_Conversion,
111     ICC_Conversion,
112     ICC_Conversion,
113     ICC_Conversion,
114     ICC_Conversion,
115     ICC_Conversion,
116     ICC_Conversion,
117     ICC_Conversion
118   };
119   return Category[(int)Kind];
120 }
121 
122 /// GetConversionRank - Retrieve the implicit conversion rank
123 /// corresponding to the given implicit conversion kind.
124 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
125   static const ImplicitConversionRank
126     Rank[(int)ICK_Num_Conversion_Kinds] = {
127     ICR_Exact_Match,
128     ICR_Exact_Match,
129     ICR_Exact_Match,
130     ICR_Exact_Match,
131     ICR_Exact_Match,
132     ICR_Exact_Match,
133     ICR_Promotion,
134     ICR_Promotion,
135     ICR_Promotion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Conversion,
146     ICR_Conversion,
147     ICR_Complex_Real_Conversion,
148     ICR_Conversion,
149     ICR_Conversion,
150     ICR_Writeback_Conversion
151   };
152   return Rank[(int)Kind];
153 }
154 
155 /// GetImplicitConversionName - Return the name of this kind of
156 /// implicit conversion.
157 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159     "No conversion",
160     "Lvalue-to-rvalue",
161     "Array-to-pointer",
162     "Function-to-pointer",
163     "Noreturn adjustment",
164     "Qualification",
165     "Integral promotion",
166     "Floating point promotion",
167     "Complex promotion",
168     "Integral conversion",
169     "Floating conversion",
170     "Complex conversion",
171     "Floating-integral conversion",
172     "Pointer conversion",
173     "Pointer-to-member conversion",
174     "Boolean conversion",
175     "Compatible-types conversion",
176     "Derived-to-base conversion",
177     "Vector conversion",
178     "Vector splat",
179     "Complex-real conversion",
180     "Block Pointer conversion",
181     "Transparent Union Conversion"
182     "Writeback conversion"
183   };
184   return Name[Kind];
185 }
186 
187 /// StandardConversionSequence - Set the standard conversion
188 /// sequence to the identity conversion.
189 void StandardConversionSequence::setAsIdentityConversion() {
190   First = ICK_Identity;
191   Second = ICK_Identity;
192   Third = ICK_Identity;
193   DeprecatedStringLiteralToCharPtr = false;
194   QualificationIncludesObjCLifetime = false;
195   ReferenceBinding = false;
196   DirectBinding = false;
197   IsLvalueReference = true;
198   BindsToFunctionLvalue = false;
199   BindsToRvalue = false;
200   BindsImplicitObjectArgumentWithoutRefQualifier = false;
201   ObjCLifetimeConversionBinding = false;
202   CopyConstructor = 0;
203 }
204 
205 /// getRank - Retrieve the rank of this standard conversion sequence
206 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
207 /// implicit conversions.
208 ImplicitConversionRank StandardConversionSequence::getRank() const {
209   ImplicitConversionRank Rank = ICR_Exact_Match;
210   if  (GetConversionRank(First) > Rank)
211     Rank = GetConversionRank(First);
212   if  (GetConversionRank(Second) > Rank)
213     Rank = GetConversionRank(Second);
214   if  (GetConversionRank(Third) > Rank)
215     Rank = GetConversionRank(Third);
216   return Rank;
217 }
218 
219 /// isPointerConversionToBool - Determines whether this conversion is
220 /// a conversion of a pointer or pointer-to-member to bool. This is
221 /// used as part of the ranking of standard conversion sequences
222 /// (C++ 13.3.3.2p4).
223 bool StandardConversionSequence::isPointerConversionToBool() const {
224   // Note that FromType has not necessarily been transformed by the
225   // array-to-pointer or function-to-pointer implicit conversions, so
226   // check for their presence as well as checking whether FromType is
227   // a pointer.
228   if (getToType(1)->isBooleanType() &&
229       (getFromType()->isPointerType() ||
230        getFromType()->isObjCObjectPointerType() ||
231        getFromType()->isBlockPointerType() ||
232        getFromType()->isNullPtrType() ||
233        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234     return true;
235 
236   return false;
237 }
238 
239 /// isPointerConversionToVoidPointer - Determines whether this
240 /// conversion is a conversion of a pointer to a void pointer. This is
241 /// used as part of the ranking of standard conversion sequences (C++
242 /// 13.3.3.2p4).
243 bool
244 StandardConversionSequence::
245 isPointerConversionToVoidPointer(ASTContext& Context) const {
246   QualType FromType = getFromType();
247   QualType ToType = getToType(1);
248 
249   // Note that FromType has not necessarily been transformed by the
250   // array-to-pointer implicit conversion, so check for its presence
251   // and redo the conversion to get a pointer.
252   if (First == ICK_Array_To_Pointer)
253     FromType = Context.getArrayDecayedType(FromType);
254 
255   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
256     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
257       return ToPtrType->getPointeeType()->isVoidType();
258 
259   return false;
260 }
261 
262 /// Skip any implicit casts which could be either part of a narrowing conversion
263 /// or after one in an implicit conversion.
264 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
265   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
266     switch (ICE->getCastKind()) {
267     case CK_NoOp:
268     case CK_IntegralCast:
269     case CK_IntegralToBoolean:
270     case CK_IntegralToFloating:
271     case CK_FloatingToIntegral:
272     case CK_FloatingToBoolean:
273     case CK_FloatingCast:
274       Converted = ICE->getSubExpr();
275       continue;
276 
277     default:
278       return Converted;
279     }
280   }
281 
282   return Converted;
283 }
284 
285 /// Check if this standard conversion sequence represents a narrowing
286 /// conversion, according to C++11 [dcl.init.list]p7.
287 ///
288 /// \param Ctx  The AST context.
289 /// \param Converted  The result of applying this standard conversion sequence.
290 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
291 ///        value of the expression prior to the narrowing conversion.
292 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
293 ///        type of the expression prior to the narrowing conversion.
294 NarrowingKind
295 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
296                                              const Expr *Converted,
297                                              APValue &ConstantValue,
298                                              QualType &ConstantType) const {
299   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
300 
301   // C++11 [dcl.init.list]p7:
302   //   A narrowing conversion is an implicit conversion ...
303   QualType FromType = getToType(0);
304   QualType ToType = getToType(1);
305   switch (Second) {
306   // -- from a floating-point type to an integer type, or
307   //
308   // -- from an integer type or unscoped enumeration type to a floating-point
309   //    type, except where the source is a constant expression and the actual
310   //    value after conversion will fit into the target type and will produce
311   //    the original value when converted back to the original type, or
312   case ICK_Floating_Integral:
313     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
314       return NK_Type_Narrowing;
315     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
316       llvm::APSInt IntConstantValue;
317       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
318       if (Initializer &&
319           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
320         // Convert the integer to the floating type.
321         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
322         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
323                                 llvm::APFloat::rmNearestTiesToEven);
324         // And back.
325         llvm::APSInt ConvertedValue = IntConstantValue;
326         bool ignored;
327         Result.convertToInteger(ConvertedValue,
328                                 llvm::APFloat::rmTowardZero, &ignored);
329         // If the resulting value is different, this was a narrowing conversion.
330         if (IntConstantValue != ConvertedValue) {
331           ConstantValue = APValue(IntConstantValue);
332           ConstantType = Initializer->getType();
333           return NK_Constant_Narrowing;
334         }
335       } else {
336         // Variables are always narrowings.
337         return NK_Variable_Narrowing;
338       }
339     }
340     return NK_Not_Narrowing;
341 
342   // -- from long double to double or float, or from double to float, except
343   //    where the source is a constant expression and the actual value after
344   //    conversion is within the range of values that can be represented (even
345   //    if it cannot be represented exactly), or
346   case ICK_Floating_Conversion:
347     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
348         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
349       // FromType is larger than ToType.
350       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
351       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
352         // Constant!
353         assert(ConstantValue.isFloat());
354         llvm::APFloat FloatVal = ConstantValue.getFloat();
355         // Convert the source value into the target type.
356         bool ignored;
357         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
358           Ctx.getFloatTypeSemantics(ToType),
359           llvm::APFloat::rmNearestTiesToEven, &ignored);
360         // If there was no overflow, the source value is within the range of
361         // values that can be represented.
362         if (ConvertStatus & llvm::APFloat::opOverflow) {
363           ConstantType = Initializer->getType();
364           return NK_Constant_Narrowing;
365         }
366       } else {
367         return NK_Variable_Narrowing;
368       }
369     }
370     return NK_Not_Narrowing;
371 
372   // -- from an integer type or unscoped enumeration type to an integer type
373   //    that cannot represent all the values of the original type, except where
374   //    the source is a constant expression and the actual value after
375   //    conversion will fit into the target type and will produce the original
376   //    value when converted back to the original type.
377   case ICK_Boolean_Conversion:  // Bools are integers too.
378     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
379       // Boolean conversions can be from pointers and pointers to members
380       // [conv.bool], and those aren't considered narrowing conversions.
381       return NK_Not_Narrowing;
382     }  // Otherwise, fall through to the integral case.
383   case ICK_Integral_Conversion: {
384     assert(FromType->isIntegralOrUnscopedEnumerationType());
385     assert(ToType->isIntegralOrUnscopedEnumerationType());
386     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
387     const unsigned FromWidth = Ctx.getIntWidth(FromType);
388     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
389     const unsigned ToWidth = Ctx.getIntWidth(ToType);
390 
391     if (FromWidth > ToWidth ||
392         (FromWidth == ToWidth && FromSigned != ToSigned) ||
393         (FromSigned && !ToSigned)) {
394       // Not all values of FromType can be represented in ToType.
395       llvm::APSInt InitializerValue;
396       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
397       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
398         // Such conversions on variables are always narrowing.
399         return NK_Variable_Narrowing;
400       }
401       bool Narrowing = false;
402       if (FromWidth < ToWidth) {
403         // Negative -> unsigned is narrowing. Otherwise, more bits is never
404         // narrowing.
405         if (InitializerValue.isSigned() && InitializerValue.isNegative())
406           Narrowing = true;
407       } else {
408         // Add a bit to the InitializerValue so we don't have to worry about
409         // signed vs. unsigned comparisons.
410         InitializerValue = InitializerValue.extend(
411           InitializerValue.getBitWidth() + 1);
412         // Convert the initializer to and from the target width and signed-ness.
413         llvm::APSInt ConvertedValue = InitializerValue;
414         ConvertedValue = ConvertedValue.trunc(ToWidth);
415         ConvertedValue.setIsSigned(ToSigned);
416         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
417         ConvertedValue.setIsSigned(InitializerValue.isSigned());
418         // If the result is different, this was a narrowing conversion.
419         if (ConvertedValue != InitializerValue)
420           Narrowing = true;
421       }
422       if (Narrowing) {
423         ConstantType = Initializer->getType();
424         ConstantValue = APValue(InitializerValue);
425         return NK_Constant_Narrowing;
426       }
427     }
428     return NK_Not_Narrowing;
429   }
430 
431   default:
432     // Other kinds of conversions are not narrowings.
433     return NK_Not_Narrowing;
434   }
435 }
436 
437 /// DebugPrint - Print this standard conversion sequence to standard
438 /// error. Useful for debugging overloading issues.
439 void StandardConversionSequence::DebugPrint() const {
440   raw_ostream &OS = llvm::errs();
441   bool PrintedSomething = false;
442   if (First != ICK_Identity) {
443     OS << GetImplicitConversionName(First);
444     PrintedSomething = true;
445   }
446 
447   if (Second != ICK_Identity) {
448     if (PrintedSomething) {
449       OS << " -> ";
450     }
451     OS << GetImplicitConversionName(Second);
452 
453     if (CopyConstructor) {
454       OS << " (by copy constructor)";
455     } else if (DirectBinding) {
456       OS << " (direct reference binding)";
457     } else if (ReferenceBinding) {
458       OS << " (reference binding)";
459     }
460     PrintedSomething = true;
461   }
462 
463   if (Third != ICK_Identity) {
464     if (PrintedSomething) {
465       OS << " -> ";
466     }
467     OS << GetImplicitConversionName(Third);
468     PrintedSomething = true;
469   }
470 
471   if (!PrintedSomething) {
472     OS << "No conversions required";
473   }
474 }
475 
476 /// DebugPrint - Print this user-defined conversion sequence to standard
477 /// error. Useful for debugging overloading issues.
478 void UserDefinedConversionSequence::DebugPrint() const {
479   raw_ostream &OS = llvm::errs();
480   if (Before.First || Before.Second || Before.Third) {
481     Before.DebugPrint();
482     OS << " -> ";
483   }
484   if (ConversionFunction)
485     OS << '\'' << *ConversionFunction << '\'';
486   else
487     OS << "aggregate initialization";
488   if (After.First || After.Second || After.Third) {
489     OS << " -> ";
490     After.DebugPrint();
491   }
492 }
493 
494 /// DebugPrint - Print this implicit conversion sequence to standard
495 /// error. Useful for debugging overloading issues.
496 void ImplicitConversionSequence::DebugPrint() const {
497   raw_ostream &OS = llvm::errs();
498   switch (ConversionKind) {
499   case StandardConversion:
500     OS << "Standard conversion: ";
501     Standard.DebugPrint();
502     break;
503   case UserDefinedConversion:
504     OS << "User-defined conversion: ";
505     UserDefined.DebugPrint();
506     break;
507   case EllipsisConversion:
508     OS << "Ellipsis conversion";
509     break;
510   case AmbiguousConversion:
511     OS << "Ambiguous conversion";
512     break;
513   case BadConversion:
514     OS << "Bad conversion";
515     break;
516   }
517 
518   OS << "\n";
519 }
520 
521 void AmbiguousConversionSequence::construct() {
522   new (&conversions()) ConversionSet();
523 }
524 
525 void AmbiguousConversionSequence::destruct() {
526   conversions().~ConversionSet();
527 }
528 
529 void
530 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
531   FromTypePtr = O.FromTypePtr;
532   ToTypePtr = O.ToTypePtr;
533   new (&conversions()) ConversionSet(O.conversions());
534 }
535 
536 namespace {
537   // Structure used by OverloadCandidate::DeductionFailureInfo to store
538   // template parameter and template argument information.
539   struct DFIParamWithArguments {
540     TemplateParameter Param;
541     TemplateArgument FirstArg;
542     TemplateArgument SecondArg;
543   };
544 }
545 
546 /// \brief Convert from Sema's representation of template deduction information
547 /// to the form used in overload-candidate information.
548 OverloadCandidate::DeductionFailureInfo
549 static MakeDeductionFailureInfo(ASTContext &Context,
550                                 Sema::TemplateDeductionResult TDK,
551                                 TemplateDeductionInfo &Info) {
552   OverloadCandidate::DeductionFailureInfo Result;
553   Result.Result = static_cast<unsigned>(TDK);
554   Result.HasDiagnostic = false;
555   Result.Data = 0;
556   switch (TDK) {
557   case Sema::TDK_Success:
558   case Sema::TDK_InstantiationDepth:
559   case Sema::TDK_TooManyArguments:
560   case Sema::TDK_TooFewArguments:
561     break;
562 
563   case Sema::TDK_Incomplete:
564   case Sema::TDK_InvalidExplicitArguments:
565     Result.Data = Info.Param.getOpaqueValue();
566     break;
567 
568   case Sema::TDK_Inconsistent:
569   case Sema::TDK_Underqualified: {
570     // FIXME: Should allocate from normal heap so that we can free this later.
571     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
572     Saved->Param = Info.Param;
573     Saved->FirstArg = Info.FirstArg;
574     Saved->SecondArg = Info.SecondArg;
575     Result.Data = Saved;
576     break;
577   }
578 
579   case Sema::TDK_SubstitutionFailure:
580     Result.Data = Info.take();
581     if (Info.hasSFINAEDiagnostic()) {
582       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
583           SourceLocation(), PartialDiagnostic::NullDiagnostic());
584       Info.takeSFINAEDiagnostic(*Diag);
585       Result.HasDiagnostic = true;
586     }
587     break;
588 
589   case Sema::TDK_NonDeducedMismatch:
590   case Sema::TDK_FailedOverloadResolution:
591     break;
592   }
593 
594   return Result;
595 }
596 
597 void OverloadCandidate::DeductionFailureInfo::Destroy() {
598   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
599   case Sema::TDK_Success:
600   case Sema::TDK_InstantiationDepth:
601   case Sema::TDK_Incomplete:
602   case Sema::TDK_TooManyArguments:
603   case Sema::TDK_TooFewArguments:
604   case Sema::TDK_InvalidExplicitArguments:
605     break;
606 
607   case Sema::TDK_Inconsistent:
608   case Sema::TDK_Underqualified:
609     // FIXME: Destroy the data?
610     Data = 0;
611     break;
612 
613   case Sema::TDK_SubstitutionFailure:
614     // FIXME: Destroy the template argument list?
615     Data = 0;
616     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
617       Diag->~PartialDiagnosticAt();
618       HasDiagnostic = false;
619     }
620     break;
621 
622   // Unhandled
623   case Sema::TDK_NonDeducedMismatch:
624   case Sema::TDK_FailedOverloadResolution:
625     break;
626   }
627 }
628 
629 PartialDiagnosticAt *
630 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
631   if (HasDiagnostic)
632     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
633   return 0;
634 }
635 
636 TemplateParameter
637 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
638   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
639   case Sema::TDK_Success:
640   case Sema::TDK_InstantiationDepth:
641   case Sema::TDK_TooManyArguments:
642   case Sema::TDK_TooFewArguments:
643   case Sema::TDK_SubstitutionFailure:
644     return TemplateParameter();
645 
646   case Sema::TDK_Incomplete:
647   case Sema::TDK_InvalidExplicitArguments:
648     return TemplateParameter::getFromOpaqueValue(Data);
649 
650   case Sema::TDK_Inconsistent:
651   case Sema::TDK_Underqualified:
652     return static_cast<DFIParamWithArguments*>(Data)->Param;
653 
654   // Unhandled
655   case Sema::TDK_NonDeducedMismatch:
656   case Sema::TDK_FailedOverloadResolution:
657     break;
658   }
659 
660   return TemplateParameter();
661 }
662 
663 TemplateArgumentList *
664 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
665   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
666     case Sema::TDK_Success:
667     case Sema::TDK_InstantiationDepth:
668     case Sema::TDK_TooManyArguments:
669     case Sema::TDK_TooFewArguments:
670     case Sema::TDK_Incomplete:
671     case Sema::TDK_InvalidExplicitArguments:
672     case Sema::TDK_Inconsistent:
673     case Sema::TDK_Underqualified:
674       return 0;
675 
676     case Sema::TDK_SubstitutionFailure:
677       return static_cast<TemplateArgumentList*>(Data);
678 
679     // Unhandled
680     case Sema::TDK_NonDeducedMismatch:
681     case Sema::TDK_FailedOverloadResolution:
682       break;
683   }
684 
685   return 0;
686 }
687 
688 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
689   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
690   case Sema::TDK_Success:
691   case Sema::TDK_InstantiationDepth:
692   case Sema::TDK_Incomplete:
693   case Sema::TDK_TooManyArguments:
694   case Sema::TDK_TooFewArguments:
695   case Sema::TDK_InvalidExplicitArguments:
696   case Sema::TDK_SubstitutionFailure:
697     return 0;
698 
699   case Sema::TDK_Inconsistent:
700   case Sema::TDK_Underqualified:
701     return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
702 
703   // Unhandled
704   case Sema::TDK_NonDeducedMismatch:
705   case Sema::TDK_FailedOverloadResolution:
706     break;
707   }
708 
709   return 0;
710 }
711 
712 const TemplateArgument *
713 OverloadCandidate::DeductionFailureInfo::getSecondArg() {
714   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
715   case Sema::TDK_Success:
716   case Sema::TDK_InstantiationDepth:
717   case Sema::TDK_Incomplete:
718   case Sema::TDK_TooManyArguments:
719   case Sema::TDK_TooFewArguments:
720   case Sema::TDK_InvalidExplicitArguments:
721   case Sema::TDK_SubstitutionFailure:
722     return 0;
723 
724   case Sema::TDK_Inconsistent:
725   case Sema::TDK_Underqualified:
726     return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
727 
728   // Unhandled
729   case Sema::TDK_NonDeducedMismatch:
730   case Sema::TDK_FailedOverloadResolution:
731     break;
732   }
733 
734   return 0;
735 }
736 
737 void OverloadCandidateSet::clear() {
738   for (iterator i = begin(), e = end(); i != e; ++i) {
739     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
740       i->Conversions[ii].~ImplicitConversionSequence();
741     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
742       i->DeductionFailure.Destroy();
743   }
744   NumInlineSequences = 0;
745   Candidates.clear();
746   Functions.clear();
747 }
748 
749 namespace {
750   class UnbridgedCastsSet {
751     struct Entry {
752       Expr **Addr;
753       Expr *Saved;
754     };
755     SmallVector<Entry, 2> Entries;
756 
757   public:
758     void save(Sema &S, Expr *&E) {
759       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
760       Entry entry = { &E, E };
761       Entries.push_back(entry);
762       E = S.stripARCUnbridgedCast(E);
763     }
764 
765     void restore() {
766       for (SmallVectorImpl<Entry>::iterator
767              i = Entries.begin(), e = Entries.end(); i != e; ++i)
768         *i->Addr = i->Saved;
769     }
770   };
771 }
772 
773 /// checkPlaceholderForOverload - Do any interesting placeholder-like
774 /// preprocessing on the given expression.
775 ///
776 /// \param unbridgedCasts a collection to which to add unbridged casts;
777 ///   without this, they will be immediately diagnosed as errors
778 ///
779 /// Return true on unrecoverable error.
780 static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
781                                         UnbridgedCastsSet *unbridgedCasts = 0) {
782   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
783     // We can't handle overloaded expressions here because overload
784     // resolution might reasonably tweak them.
785     if (placeholder->getKind() == BuiltinType::Overload) return false;
786 
787     // If the context potentially accepts unbridged ARC casts, strip
788     // the unbridged cast and add it to the collection for later restoration.
789     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
790         unbridgedCasts) {
791       unbridgedCasts->save(S, E);
792       return false;
793     }
794 
795     // Go ahead and check everything else.
796     ExprResult result = S.CheckPlaceholderExpr(E);
797     if (result.isInvalid())
798       return true;
799 
800     E = result.take();
801     return false;
802   }
803 
804   // Nothing to do.
805   return false;
806 }
807 
808 /// checkArgPlaceholdersForOverload - Check a set of call operands for
809 /// placeholders.
810 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
811                                             unsigned numArgs,
812                                             UnbridgedCastsSet &unbridged) {
813   for (unsigned i = 0; i != numArgs; ++i)
814     if (checkPlaceholderForOverload(S, args[i], &unbridged))
815       return true;
816 
817   return false;
818 }
819 
820 // IsOverload - Determine whether the given New declaration is an
821 // overload of the declarations in Old. This routine returns false if
822 // New and Old cannot be overloaded, e.g., if New has the same
823 // signature as some function in Old (C++ 1.3.10) or if the Old
824 // declarations aren't functions (or function templates) at all. When
825 // it does return false, MatchedDecl will point to the decl that New
826 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
827 // top of the underlying declaration.
828 //
829 // Example: Given the following input:
830 //
831 //   void f(int, float); // #1
832 //   void f(int, int); // #2
833 //   int f(int, int); // #3
834 //
835 // When we process #1, there is no previous declaration of "f",
836 // so IsOverload will not be used.
837 //
838 // When we process #2, Old contains only the FunctionDecl for #1.  By
839 // comparing the parameter types, we see that #1 and #2 are overloaded
840 // (since they have different signatures), so this routine returns
841 // false; MatchedDecl is unchanged.
842 //
843 // When we process #3, Old is an overload set containing #1 and #2. We
844 // compare the signatures of #3 to #1 (they're overloaded, so we do
845 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
846 // identical (return types of functions are not part of the
847 // signature), IsOverload returns false and MatchedDecl will be set to
848 // point to the FunctionDecl for #2.
849 //
850 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
851 // into a class by a using declaration.  The rules for whether to hide
852 // shadow declarations ignore some properties which otherwise figure
853 // into a function template's signature.
854 Sema::OverloadKind
855 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
856                     NamedDecl *&Match, bool NewIsUsingDecl) {
857   for (LookupResult::iterator I = Old.begin(), E = Old.end();
858          I != E; ++I) {
859     NamedDecl *OldD = *I;
860 
861     bool OldIsUsingDecl = false;
862     if (isa<UsingShadowDecl>(OldD)) {
863       OldIsUsingDecl = true;
864 
865       // We can always introduce two using declarations into the same
866       // context, even if they have identical signatures.
867       if (NewIsUsingDecl) continue;
868 
869       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
870     }
871 
872     // If either declaration was introduced by a using declaration,
873     // we'll need to use slightly different rules for matching.
874     // Essentially, these rules are the normal rules, except that
875     // function templates hide function templates with different
876     // return types or template parameter lists.
877     bool UseMemberUsingDeclRules =
878       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
879 
880     if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
881       if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
882         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
883           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
884           continue;
885         }
886 
887         Match = *I;
888         return Ovl_Match;
889       }
890     } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
891       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
892         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
893           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
894           continue;
895         }
896 
897         Match = *I;
898         return Ovl_Match;
899       }
900     } else if (isa<UsingDecl>(OldD)) {
901       // We can overload with these, which can show up when doing
902       // redeclaration checks for UsingDecls.
903       assert(Old.getLookupKind() == LookupUsingDeclName);
904     } else if (isa<TagDecl>(OldD)) {
905       // We can always overload with tags by hiding them.
906     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
907       // Optimistically assume that an unresolved using decl will
908       // overload; if it doesn't, we'll have to diagnose during
909       // template instantiation.
910     } else {
911       // (C++ 13p1):
912       //   Only function declarations can be overloaded; object and type
913       //   declarations cannot be overloaded.
914       Match = *I;
915       return Ovl_NonFunction;
916     }
917   }
918 
919   return Ovl_Overload;
920 }
921 
922 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
923                       bool UseUsingDeclRules) {
924   // If both of the functions are extern "C", then they are not
925   // overloads.
926   if (Old->isExternC() && New->isExternC())
927     return false;
928 
929   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
930   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
931 
932   // C++ [temp.fct]p2:
933   //   A function template can be overloaded with other function templates
934   //   and with normal (non-template) functions.
935   if ((OldTemplate == 0) != (NewTemplate == 0))
936     return true;
937 
938   // Is the function New an overload of the function Old?
939   QualType OldQType = Context.getCanonicalType(Old->getType());
940   QualType NewQType = Context.getCanonicalType(New->getType());
941 
942   // Compare the signatures (C++ 1.3.10) of the two functions to
943   // determine whether they are overloads. If we find any mismatch
944   // in the signature, they are overloads.
945 
946   // If either of these functions is a K&R-style function (no
947   // prototype), then we consider them to have matching signatures.
948   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
949       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
950     return false;
951 
952   const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
953   const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
954 
955   // The signature of a function includes the types of its
956   // parameters (C++ 1.3.10), which includes the presence or absence
957   // of the ellipsis; see C++ DR 357).
958   if (OldQType != NewQType &&
959       (OldType->getNumArgs() != NewType->getNumArgs() ||
960        OldType->isVariadic() != NewType->isVariadic() ||
961        !FunctionArgTypesAreEqual(OldType, NewType)))
962     return true;
963 
964   // C++ [temp.over.link]p4:
965   //   The signature of a function template consists of its function
966   //   signature, its return type and its template parameter list. The names
967   //   of the template parameters are significant only for establishing the
968   //   relationship between the template parameters and the rest of the
969   //   signature.
970   //
971   // We check the return type and template parameter lists for function
972   // templates first; the remaining checks follow.
973   //
974   // However, we don't consider either of these when deciding whether
975   // a member introduced by a shadow declaration is hidden.
976   if (!UseUsingDeclRules && NewTemplate &&
977       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
978                                        OldTemplate->getTemplateParameters(),
979                                        false, TPL_TemplateMatch) ||
980        OldType->getResultType() != NewType->getResultType()))
981     return true;
982 
983   // If the function is a class member, its signature includes the
984   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
985   //
986   // As part of this, also check whether one of the member functions
987   // is static, in which case they are not overloads (C++
988   // 13.1p2). While not part of the definition of the signature,
989   // this check is important to determine whether these functions
990   // can be overloaded.
991   CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
992   CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
993   if (OldMethod && NewMethod &&
994       !OldMethod->isStatic() && !NewMethod->isStatic() &&
995       (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
996        OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
997     if (!UseUsingDeclRules &&
998         OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
999         (OldMethod->getRefQualifier() == RQ_None ||
1000          NewMethod->getRefQualifier() == RQ_None)) {
1001       // C++0x [over.load]p2:
1002       //   - Member function declarations with the same name and the same
1003       //     parameter-type-list as well as member function template
1004       //     declarations with the same name, the same parameter-type-list, and
1005       //     the same template parameter lists cannot be overloaded if any of
1006       //     them, but not all, have a ref-qualifier (8.3.5).
1007       Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1008         << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1009       Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1010     }
1011 
1012     return true;
1013   }
1014 
1015   // The signatures match; this is not an overload.
1016   return false;
1017 }
1018 
1019 /// \brief Checks availability of the function depending on the current
1020 /// function context. Inside an unavailable function, unavailability is ignored.
1021 ///
1022 /// \returns true if \arg FD is unavailable and current context is inside
1023 /// an available function, false otherwise.
1024 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1025   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1026 }
1027 
1028 /// \brief Tries a user-defined conversion from From to ToType.
1029 ///
1030 /// Produces an implicit conversion sequence for when a standard conversion
1031 /// is not an option. See TryImplicitConversion for more information.
1032 static ImplicitConversionSequence
1033 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1034                          bool SuppressUserConversions,
1035                          bool AllowExplicit,
1036                          bool InOverloadResolution,
1037                          bool CStyle,
1038                          bool AllowObjCWritebackConversion) {
1039   ImplicitConversionSequence ICS;
1040 
1041   if (SuppressUserConversions) {
1042     // We're not in the case above, so there is no conversion that
1043     // we can perform.
1044     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1045     return ICS;
1046   }
1047 
1048   // Attempt user-defined conversion.
1049   OverloadCandidateSet Conversions(From->getExprLoc());
1050   OverloadingResult UserDefResult
1051     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1052                               AllowExplicit);
1053 
1054   if (UserDefResult == OR_Success) {
1055     ICS.setUserDefined();
1056     // C++ [over.ics.user]p4:
1057     //   A conversion of an expression of class type to the same class
1058     //   type is given Exact Match rank, and a conversion of an
1059     //   expression of class type to a base class of that type is
1060     //   given Conversion rank, in spite of the fact that a copy
1061     //   constructor (i.e., a user-defined conversion function) is
1062     //   called for those cases.
1063     if (CXXConstructorDecl *Constructor
1064           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1065       QualType FromCanon
1066         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1067       QualType ToCanon
1068         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1069       if (Constructor->isCopyConstructor() &&
1070           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1071         // Turn this into a "standard" conversion sequence, so that it
1072         // gets ranked with standard conversion sequences.
1073         ICS.setStandard();
1074         ICS.Standard.setAsIdentityConversion();
1075         ICS.Standard.setFromType(From->getType());
1076         ICS.Standard.setAllToTypes(ToType);
1077         ICS.Standard.CopyConstructor = Constructor;
1078         if (ToCanon != FromCanon)
1079           ICS.Standard.Second = ICK_Derived_To_Base;
1080       }
1081     }
1082 
1083     // C++ [over.best.ics]p4:
1084     //   However, when considering the argument of a user-defined
1085     //   conversion function that is a candidate by 13.3.1.3 when
1086     //   invoked for the copying of the temporary in the second step
1087     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1088     //   13.3.1.6 in all cases, only standard conversion sequences and
1089     //   ellipsis conversion sequences are allowed.
1090     if (SuppressUserConversions && ICS.isUserDefined()) {
1091       ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1092     }
1093   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1094     ICS.setAmbiguous();
1095     ICS.Ambiguous.setFromType(From->getType());
1096     ICS.Ambiguous.setToType(ToType);
1097     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1098          Cand != Conversions.end(); ++Cand)
1099       if (Cand->Viable)
1100         ICS.Ambiguous.addConversion(Cand->Function);
1101   } else {
1102     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1103   }
1104 
1105   return ICS;
1106 }
1107 
1108 /// TryImplicitConversion - Attempt to perform an implicit conversion
1109 /// from the given expression (Expr) to the given type (ToType). This
1110 /// function returns an implicit conversion sequence that can be used
1111 /// to perform the initialization. Given
1112 ///
1113 ///   void f(float f);
1114 ///   void g(int i) { f(i); }
1115 ///
1116 /// this routine would produce an implicit conversion sequence to
1117 /// describe the initialization of f from i, which will be a standard
1118 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1119 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1120 //
1121 /// Note that this routine only determines how the conversion can be
1122 /// performed; it does not actually perform the conversion. As such,
1123 /// it will not produce any diagnostics if no conversion is available,
1124 /// but will instead return an implicit conversion sequence of kind
1125 /// "BadConversion".
1126 ///
1127 /// If @p SuppressUserConversions, then user-defined conversions are
1128 /// not permitted.
1129 /// If @p AllowExplicit, then explicit user-defined conversions are
1130 /// permitted.
1131 ///
1132 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1133 /// writeback conversion, which allows __autoreleasing id* parameters to
1134 /// be initialized with __strong id* or __weak id* arguments.
1135 static ImplicitConversionSequence
1136 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1137                       bool SuppressUserConversions,
1138                       bool AllowExplicit,
1139                       bool InOverloadResolution,
1140                       bool CStyle,
1141                       bool AllowObjCWritebackConversion) {
1142   ImplicitConversionSequence ICS;
1143   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1144                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1145     ICS.setStandard();
1146     return ICS;
1147   }
1148 
1149   if (!S.getLangOpts().CPlusPlus) {
1150     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1151     return ICS;
1152   }
1153 
1154   // C++ [over.ics.user]p4:
1155   //   A conversion of an expression of class type to the same class
1156   //   type is given Exact Match rank, and a conversion of an
1157   //   expression of class type to a base class of that type is
1158   //   given Conversion rank, in spite of the fact that a copy/move
1159   //   constructor (i.e., a user-defined conversion function) is
1160   //   called for those cases.
1161   QualType FromType = From->getType();
1162   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1163       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1164        S.IsDerivedFrom(FromType, ToType))) {
1165     ICS.setStandard();
1166     ICS.Standard.setAsIdentityConversion();
1167     ICS.Standard.setFromType(FromType);
1168     ICS.Standard.setAllToTypes(ToType);
1169 
1170     // We don't actually check at this point whether there is a valid
1171     // copy/move constructor, since overloading just assumes that it
1172     // exists. When we actually perform initialization, we'll find the
1173     // appropriate constructor to copy the returned object, if needed.
1174     ICS.Standard.CopyConstructor = 0;
1175 
1176     // Determine whether this is considered a derived-to-base conversion.
1177     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1178       ICS.Standard.Second = ICK_Derived_To_Base;
1179 
1180     return ICS;
1181   }
1182 
1183   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1184                                   AllowExplicit, InOverloadResolution, CStyle,
1185                                   AllowObjCWritebackConversion);
1186 }
1187 
1188 ImplicitConversionSequence
1189 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1190                             bool SuppressUserConversions,
1191                             bool AllowExplicit,
1192                             bool InOverloadResolution,
1193                             bool CStyle,
1194                             bool AllowObjCWritebackConversion) {
1195   return clang::TryImplicitConversion(*this, From, ToType,
1196                                       SuppressUserConversions, AllowExplicit,
1197                                       InOverloadResolution, CStyle,
1198                                       AllowObjCWritebackConversion);
1199 }
1200 
1201 /// PerformImplicitConversion - Perform an implicit conversion of the
1202 /// expression From to the type ToType. Returns the
1203 /// converted expression. Flavor is the kind of conversion we're
1204 /// performing, used in the error message. If @p AllowExplicit,
1205 /// explicit user-defined conversions are permitted.
1206 ExprResult
1207 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1208                                 AssignmentAction Action, bool AllowExplicit) {
1209   ImplicitConversionSequence ICS;
1210   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1211 }
1212 
1213 ExprResult
1214 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1215                                 AssignmentAction Action, bool AllowExplicit,
1216                                 ImplicitConversionSequence& ICS) {
1217   if (checkPlaceholderForOverload(*this, From))
1218     return ExprError();
1219 
1220   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1221   bool AllowObjCWritebackConversion
1222     = getLangOpts().ObjCAutoRefCount &&
1223       (Action == AA_Passing || Action == AA_Sending);
1224 
1225   ICS = clang::TryImplicitConversion(*this, From, ToType,
1226                                      /*SuppressUserConversions=*/false,
1227                                      AllowExplicit,
1228                                      /*InOverloadResolution=*/false,
1229                                      /*CStyle=*/false,
1230                                      AllowObjCWritebackConversion);
1231   return PerformImplicitConversion(From, ToType, ICS, Action);
1232 }
1233 
1234 /// \brief Determine whether the conversion from FromType to ToType is a valid
1235 /// conversion that strips "noreturn" off the nested function type.
1236 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1237                                 QualType &ResultTy) {
1238   if (Context.hasSameUnqualifiedType(FromType, ToType))
1239     return false;
1240 
1241   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1242   // where F adds one of the following at most once:
1243   //   - a pointer
1244   //   - a member pointer
1245   //   - a block pointer
1246   CanQualType CanTo = Context.getCanonicalType(ToType);
1247   CanQualType CanFrom = Context.getCanonicalType(FromType);
1248   Type::TypeClass TyClass = CanTo->getTypeClass();
1249   if (TyClass != CanFrom->getTypeClass()) return false;
1250   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1251     if (TyClass == Type::Pointer) {
1252       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1253       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1254     } else if (TyClass == Type::BlockPointer) {
1255       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1256       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1257     } else if (TyClass == Type::MemberPointer) {
1258       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1259       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1260     } else {
1261       return false;
1262     }
1263 
1264     TyClass = CanTo->getTypeClass();
1265     if (TyClass != CanFrom->getTypeClass()) return false;
1266     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1267       return false;
1268   }
1269 
1270   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1271   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1272   if (!EInfo.getNoReturn()) return false;
1273 
1274   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1275   assert(QualType(FromFn, 0).isCanonical());
1276   if (QualType(FromFn, 0) != CanTo) return false;
1277 
1278   ResultTy = ToType;
1279   return true;
1280 }
1281 
1282 /// \brief Determine whether the conversion from FromType to ToType is a valid
1283 /// vector conversion.
1284 ///
1285 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1286 /// conversion.
1287 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1288                                QualType ToType, ImplicitConversionKind &ICK) {
1289   // We need at least one of these types to be a vector type to have a vector
1290   // conversion.
1291   if (!ToType->isVectorType() && !FromType->isVectorType())
1292     return false;
1293 
1294   // Identical types require no conversions.
1295   if (Context.hasSameUnqualifiedType(FromType, ToType))
1296     return false;
1297 
1298   // There are no conversions between extended vector types, only identity.
1299   if (ToType->isExtVectorType()) {
1300     // There are no conversions between extended vector types other than the
1301     // identity conversion.
1302     if (FromType->isExtVectorType())
1303       return false;
1304 
1305     // Vector splat from any arithmetic type to a vector.
1306     if (FromType->isArithmeticType()) {
1307       ICK = ICK_Vector_Splat;
1308       return true;
1309     }
1310   }
1311 
1312   // We can perform the conversion between vector types in the following cases:
1313   // 1)vector types are equivalent AltiVec and GCC vector types
1314   // 2)lax vector conversions are permitted and the vector types are of the
1315   //   same size
1316   if (ToType->isVectorType() && FromType->isVectorType()) {
1317     if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1318         (Context.getLangOpts().LaxVectorConversions &&
1319          (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1320       ICK = ICK_Vector_Conversion;
1321       return true;
1322     }
1323   }
1324 
1325   return false;
1326 }
1327 
1328 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1329                                 bool InOverloadResolution,
1330                                 StandardConversionSequence &SCS,
1331                                 bool CStyle);
1332 
1333 /// IsStandardConversion - Determines whether there is a standard
1334 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1335 /// expression From to the type ToType. Standard conversion sequences
1336 /// only consider non-class types; for conversions that involve class
1337 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1338 /// contain the standard conversion sequence required to perform this
1339 /// conversion and this routine will return true. Otherwise, this
1340 /// routine will return false and the value of SCS is unspecified.
1341 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1342                                  bool InOverloadResolution,
1343                                  StandardConversionSequence &SCS,
1344                                  bool CStyle,
1345                                  bool AllowObjCWritebackConversion) {
1346   QualType FromType = From->getType();
1347 
1348   // Standard conversions (C++ [conv])
1349   SCS.setAsIdentityConversion();
1350   SCS.DeprecatedStringLiteralToCharPtr = false;
1351   SCS.IncompatibleObjC = false;
1352   SCS.setFromType(FromType);
1353   SCS.CopyConstructor = 0;
1354 
1355   // There are no standard conversions for class types in C++, so
1356   // abort early. When overloading in C, however, we do permit
1357   if (FromType->isRecordType() || ToType->isRecordType()) {
1358     if (S.getLangOpts().CPlusPlus)
1359       return false;
1360 
1361     // When we're overloading in C, we allow, as standard conversions,
1362   }
1363 
1364   // The first conversion can be an lvalue-to-rvalue conversion,
1365   // array-to-pointer conversion, or function-to-pointer conversion
1366   // (C++ 4p1).
1367 
1368   if (FromType == S.Context.OverloadTy) {
1369     DeclAccessPair AccessPair;
1370     if (FunctionDecl *Fn
1371           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1372                                                  AccessPair)) {
1373       // We were able to resolve the address of the overloaded function,
1374       // so we can convert to the type of that function.
1375       FromType = Fn->getType();
1376 
1377       // we can sometimes resolve &foo<int> regardless of ToType, so check
1378       // if the type matches (identity) or we are converting to bool
1379       if (!S.Context.hasSameUnqualifiedType(
1380                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1381         QualType resultTy;
1382         // if the function type matches except for [[noreturn]], it's ok
1383         if (!S.IsNoReturnConversion(FromType,
1384               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1385           // otherwise, only a boolean conversion is standard
1386           if (!ToType->isBooleanType())
1387             return false;
1388       }
1389 
1390       // Check if the "from" expression is taking the address of an overloaded
1391       // function and recompute the FromType accordingly. Take advantage of the
1392       // fact that non-static member functions *must* have such an address-of
1393       // expression.
1394       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1395       if (Method && !Method->isStatic()) {
1396         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1397                "Non-unary operator on non-static member address");
1398         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1399                == UO_AddrOf &&
1400                "Non-address-of operator on non-static member address");
1401         const Type *ClassType
1402           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1403         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1404       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1405         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1406                UO_AddrOf &&
1407                "Non-address-of operator for overloaded function expression");
1408         FromType = S.Context.getPointerType(FromType);
1409       }
1410 
1411       // Check that we've computed the proper type after overload resolution.
1412       assert(S.Context.hasSameType(
1413         FromType,
1414         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1415     } else {
1416       return false;
1417     }
1418   }
1419   // Lvalue-to-rvalue conversion (C++11 4.1):
1420   //   A glvalue (3.10) of a non-function, non-array type T can
1421   //   be converted to a prvalue.
1422   bool argIsLValue = From->isGLValue();
1423   if (argIsLValue &&
1424       !FromType->isFunctionType() && !FromType->isArrayType() &&
1425       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1426     SCS.First = ICK_Lvalue_To_Rvalue;
1427 
1428     // C11 6.3.2.1p2:
1429     //   ... if the lvalue has atomic type, the value has the non-atomic version
1430     //   of the type of the lvalue ...
1431     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1432       FromType = Atomic->getValueType();
1433 
1434     // If T is a non-class type, the type of the rvalue is the
1435     // cv-unqualified version of T. Otherwise, the type of the rvalue
1436     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1437     // just strip the qualifiers because they don't matter.
1438     FromType = FromType.getUnqualifiedType();
1439   } else if (FromType->isArrayType()) {
1440     // Array-to-pointer conversion (C++ 4.2)
1441     SCS.First = ICK_Array_To_Pointer;
1442 
1443     // An lvalue or rvalue of type "array of N T" or "array of unknown
1444     // bound of T" can be converted to an rvalue of type "pointer to
1445     // T" (C++ 4.2p1).
1446     FromType = S.Context.getArrayDecayedType(FromType);
1447 
1448     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1449       // This conversion is deprecated. (C++ D.4).
1450       SCS.DeprecatedStringLiteralToCharPtr = true;
1451 
1452       // For the purpose of ranking in overload resolution
1453       // (13.3.3.1.1), this conversion is considered an
1454       // array-to-pointer conversion followed by a qualification
1455       // conversion (4.4). (C++ 4.2p2)
1456       SCS.Second = ICK_Identity;
1457       SCS.Third = ICK_Qualification;
1458       SCS.QualificationIncludesObjCLifetime = false;
1459       SCS.setAllToTypes(FromType);
1460       return true;
1461     }
1462   } else if (FromType->isFunctionType() && argIsLValue) {
1463     // Function-to-pointer conversion (C++ 4.3).
1464     SCS.First = ICK_Function_To_Pointer;
1465 
1466     // An lvalue of function type T can be converted to an rvalue of
1467     // type "pointer to T." The result is a pointer to the
1468     // function. (C++ 4.3p1).
1469     FromType = S.Context.getPointerType(FromType);
1470   } else {
1471     // We don't require any conversions for the first step.
1472     SCS.First = ICK_Identity;
1473   }
1474   SCS.setToType(0, FromType);
1475 
1476   // The second conversion can be an integral promotion, floating
1477   // point promotion, integral conversion, floating point conversion,
1478   // floating-integral conversion, pointer conversion,
1479   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1480   // For overloading in C, this can also be a "compatible-type"
1481   // conversion.
1482   bool IncompatibleObjC = false;
1483   ImplicitConversionKind SecondICK = ICK_Identity;
1484   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1485     // The unqualified versions of the types are the same: there's no
1486     // conversion to do.
1487     SCS.Second = ICK_Identity;
1488   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1489     // Integral promotion (C++ 4.5).
1490     SCS.Second = ICK_Integral_Promotion;
1491     FromType = ToType.getUnqualifiedType();
1492   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1493     // Floating point promotion (C++ 4.6).
1494     SCS.Second = ICK_Floating_Promotion;
1495     FromType = ToType.getUnqualifiedType();
1496   } else if (S.IsComplexPromotion(FromType, ToType)) {
1497     // Complex promotion (Clang extension)
1498     SCS.Second = ICK_Complex_Promotion;
1499     FromType = ToType.getUnqualifiedType();
1500   } else if (ToType->isBooleanType() &&
1501              (FromType->isArithmeticType() ||
1502               FromType->isAnyPointerType() ||
1503               FromType->isBlockPointerType() ||
1504               FromType->isMemberPointerType() ||
1505               FromType->isNullPtrType())) {
1506     // Boolean conversions (C++ 4.12).
1507     SCS.Second = ICK_Boolean_Conversion;
1508     FromType = S.Context.BoolTy;
1509   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1510              ToType->isIntegralType(S.Context)) {
1511     // Integral conversions (C++ 4.7).
1512     SCS.Second = ICK_Integral_Conversion;
1513     FromType = ToType.getUnqualifiedType();
1514   } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1515     // Complex conversions (C99 6.3.1.6)
1516     SCS.Second = ICK_Complex_Conversion;
1517     FromType = ToType.getUnqualifiedType();
1518   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1519              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1520     // Complex-real conversions (C99 6.3.1.7)
1521     SCS.Second = ICK_Complex_Real;
1522     FromType = ToType.getUnqualifiedType();
1523   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1524     // Floating point conversions (C++ 4.8).
1525     SCS.Second = ICK_Floating_Conversion;
1526     FromType = ToType.getUnqualifiedType();
1527   } else if ((FromType->isRealFloatingType() &&
1528               ToType->isIntegralType(S.Context)) ||
1529              (FromType->isIntegralOrUnscopedEnumerationType() &&
1530               ToType->isRealFloatingType())) {
1531     // Floating-integral conversions (C++ 4.9).
1532     SCS.Second = ICK_Floating_Integral;
1533     FromType = ToType.getUnqualifiedType();
1534   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1535     SCS.Second = ICK_Block_Pointer_Conversion;
1536   } else if (AllowObjCWritebackConversion &&
1537              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1538     SCS.Second = ICK_Writeback_Conversion;
1539   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1540                                    FromType, IncompatibleObjC)) {
1541     // Pointer conversions (C++ 4.10).
1542     SCS.Second = ICK_Pointer_Conversion;
1543     SCS.IncompatibleObjC = IncompatibleObjC;
1544     FromType = FromType.getUnqualifiedType();
1545   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1546                                          InOverloadResolution, FromType)) {
1547     // Pointer to member conversions (4.11).
1548     SCS.Second = ICK_Pointer_Member;
1549   } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1550     SCS.Second = SecondICK;
1551     FromType = ToType.getUnqualifiedType();
1552   } else if (!S.getLangOpts().CPlusPlus &&
1553              S.Context.typesAreCompatible(ToType, FromType)) {
1554     // Compatible conversions (Clang extension for C function overloading)
1555     SCS.Second = ICK_Compatible_Conversion;
1556     FromType = ToType.getUnqualifiedType();
1557   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1558     // Treat a conversion that strips "noreturn" as an identity conversion.
1559     SCS.Second = ICK_NoReturn_Adjustment;
1560   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1561                                              InOverloadResolution,
1562                                              SCS, CStyle)) {
1563     SCS.Second = ICK_TransparentUnionConversion;
1564     FromType = ToType;
1565   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1566                                  CStyle)) {
1567     // tryAtomicConversion has updated the standard conversion sequence
1568     // appropriately.
1569     return true;
1570   } else {
1571     // No second conversion required.
1572     SCS.Second = ICK_Identity;
1573   }
1574   SCS.setToType(1, FromType);
1575 
1576   QualType CanonFrom;
1577   QualType CanonTo;
1578   // The third conversion can be a qualification conversion (C++ 4p1).
1579   bool ObjCLifetimeConversion;
1580   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1581                                   ObjCLifetimeConversion)) {
1582     SCS.Third = ICK_Qualification;
1583     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1584     FromType = ToType;
1585     CanonFrom = S.Context.getCanonicalType(FromType);
1586     CanonTo = S.Context.getCanonicalType(ToType);
1587   } else {
1588     // No conversion required
1589     SCS.Third = ICK_Identity;
1590 
1591     // C++ [over.best.ics]p6:
1592     //   [...] Any difference in top-level cv-qualification is
1593     //   subsumed by the initialization itself and does not constitute
1594     //   a conversion. [...]
1595     CanonFrom = S.Context.getCanonicalType(FromType);
1596     CanonTo = S.Context.getCanonicalType(ToType);
1597     if (CanonFrom.getLocalUnqualifiedType()
1598                                        == CanonTo.getLocalUnqualifiedType() &&
1599         (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1600          || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1601          || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1602       FromType = ToType;
1603       CanonFrom = CanonTo;
1604     }
1605   }
1606   SCS.setToType(2, FromType);
1607 
1608   // If we have not converted the argument type to the parameter type,
1609   // this is a bad conversion sequence.
1610   if (CanonFrom != CanonTo)
1611     return false;
1612 
1613   return true;
1614 }
1615 
1616 static bool
1617 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1618                                      QualType &ToType,
1619                                      bool InOverloadResolution,
1620                                      StandardConversionSequence &SCS,
1621                                      bool CStyle) {
1622 
1623   const RecordType *UT = ToType->getAsUnionType();
1624   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1625     return false;
1626   // The field to initialize within the transparent union.
1627   RecordDecl *UD = UT->getDecl();
1628   // It's compatible if the expression matches any of the fields.
1629   for (RecordDecl::field_iterator it = UD->field_begin(),
1630        itend = UD->field_end();
1631        it != itend; ++it) {
1632     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1633                              CStyle, /*ObjCWritebackConversion=*/false)) {
1634       ToType = it->getType();
1635       return true;
1636     }
1637   }
1638   return false;
1639 }
1640 
1641 /// IsIntegralPromotion - Determines whether the conversion from the
1642 /// expression From (whose potentially-adjusted type is FromType) to
1643 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1644 /// sets PromotedType to the promoted type.
1645 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1646   const BuiltinType *To = ToType->getAs<BuiltinType>();
1647   // All integers are built-in.
1648   if (!To) {
1649     return false;
1650   }
1651 
1652   // An rvalue of type char, signed char, unsigned char, short int, or
1653   // unsigned short int can be converted to an rvalue of type int if
1654   // int can represent all the values of the source type; otherwise,
1655   // the source rvalue can be converted to an rvalue of type unsigned
1656   // int (C++ 4.5p1).
1657   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1658       !FromType->isEnumeralType()) {
1659     if (// We can promote any signed, promotable integer type to an int
1660         (FromType->isSignedIntegerType() ||
1661          // We can promote any unsigned integer type whose size is
1662          // less than int to an int.
1663          (!FromType->isSignedIntegerType() &&
1664           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1665       return To->getKind() == BuiltinType::Int;
1666     }
1667 
1668     return To->getKind() == BuiltinType::UInt;
1669   }
1670 
1671   // C++0x [conv.prom]p3:
1672   //   A prvalue of an unscoped enumeration type whose underlying type is not
1673   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1674   //   following types that can represent all the values of the enumeration
1675   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1676   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1677   //   long long int. If none of the types in that list can represent all the
1678   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1679   //   type can be converted to an rvalue a prvalue of the extended integer type
1680   //   with lowest integer conversion rank (4.13) greater than the rank of long
1681   //   long in which all the values of the enumeration can be represented. If
1682   //   there are two such extended types, the signed one is chosen.
1683   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1684     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1685     // provided for a scoped enumeration.
1686     if (FromEnumType->getDecl()->isScoped())
1687       return false;
1688 
1689     // We have already pre-calculated the promotion type, so this is trivial.
1690     if (ToType->isIntegerType() &&
1691         !RequireCompleteType(From->getLocStart(), FromType, 0))
1692       return Context.hasSameUnqualifiedType(ToType,
1693                                 FromEnumType->getDecl()->getPromotionType());
1694   }
1695 
1696   // C++0x [conv.prom]p2:
1697   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1698   //   to an rvalue a prvalue of the first of the following types that can
1699   //   represent all the values of its underlying type: int, unsigned int,
1700   //   long int, unsigned long int, long long int, or unsigned long long int.
1701   //   If none of the types in that list can represent all the values of its
1702   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1703   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1704   //   type.
1705   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1706       ToType->isIntegerType()) {
1707     // Determine whether the type we're converting from is signed or
1708     // unsigned.
1709     bool FromIsSigned = FromType->isSignedIntegerType();
1710     uint64_t FromSize = Context.getTypeSize(FromType);
1711 
1712     // The types we'll try to promote to, in the appropriate
1713     // order. Try each of these types.
1714     QualType PromoteTypes[6] = {
1715       Context.IntTy, Context.UnsignedIntTy,
1716       Context.LongTy, Context.UnsignedLongTy ,
1717       Context.LongLongTy, Context.UnsignedLongLongTy
1718     };
1719     for (int Idx = 0; Idx < 6; ++Idx) {
1720       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1721       if (FromSize < ToSize ||
1722           (FromSize == ToSize &&
1723            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1724         // We found the type that we can promote to. If this is the
1725         // type we wanted, we have a promotion. Otherwise, no
1726         // promotion.
1727         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1728       }
1729     }
1730   }
1731 
1732   // An rvalue for an integral bit-field (9.6) can be converted to an
1733   // rvalue of type int if int can represent all the values of the
1734   // bit-field; otherwise, it can be converted to unsigned int if
1735   // unsigned int can represent all the values of the bit-field. If
1736   // the bit-field is larger yet, no integral promotion applies to
1737   // it. If the bit-field has an enumerated type, it is treated as any
1738   // other value of that type for promotion purposes (C++ 4.5p3).
1739   // FIXME: We should delay checking of bit-fields until we actually perform the
1740   // conversion.
1741   using llvm::APSInt;
1742   if (From)
1743     if (FieldDecl *MemberDecl = From->getBitField()) {
1744       APSInt BitWidth;
1745       if (FromType->isIntegralType(Context) &&
1746           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1747         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1748         ToSize = Context.getTypeSize(ToType);
1749 
1750         // Are we promoting to an int from a bitfield that fits in an int?
1751         if (BitWidth < ToSize ||
1752             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1753           return To->getKind() == BuiltinType::Int;
1754         }
1755 
1756         // Are we promoting to an unsigned int from an unsigned bitfield
1757         // that fits into an unsigned int?
1758         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1759           return To->getKind() == BuiltinType::UInt;
1760         }
1761 
1762         return false;
1763       }
1764     }
1765 
1766   // An rvalue of type bool can be converted to an rvalue of type int,
1767   // with false becoming zero and true becoming one (C++ 4.5p4).
1768   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1769     return true;
1770   }
1771 
1772   return false;
1773 }
1774 
1775 /// IsFloatingPointPromotion - Determines whether the conversion from
1776 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1777 /// returns true and sets PromotedType to the promoted type.
1778 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1779   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1780     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1781       /// An rvalue of type float can be converted to an rvalue of type
1782       /// double. (C++ 4.6p1).
1783       if (FromBuiltin->getKind() == BuiltinType::Float &&
1784           ToBuiltin->getKind() == BuiltinType::Double)
1785         return true;
1786 
1787       // C99 6.3.1.5p1:
1788       //   When a float is promoted to double or long double, or a
1789       //   double is promoted to long double [...].
1790       if (!getLangOpts().CPlusPlus &&
1791           (FromBuiltin->getKind() == BuiltinType::Float ||
1792            FromBuiltin->getKind() == BuiltinType::Double) &&
1793           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1794         return true;
1795 
1796       // Half can be promoted to float.
1797       if (FromBuiltin->getKind() == BuiltinType::Half &&
1798           ToBuiltin->getKind() == BuiltinType::Float)
1799         return true;
1800     }
1801 
1802   return false;
1803 }
1804 
1805 /// \brief Determine if a conversion is a complex promotion.
1806 ///
1807 /// A complex promotion is defined as a complex -> complex conversion
1808 /// where the conversion between the underlying real types is a
1809 /// floating-point or integral promotion.
1810 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1811   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1812   if (!FromComplex)
1813     return false;
1814 
1815   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1816   if (!ToComplex)
1817     return false;
1818 
1819   return IsFloatingPointPromotion(FromComplex->getElementType(),
1820                                   ToComplex->getElementType()) ||
1821     IsIntegralPromotion(0, FromComplex->getElementType(),
1822                         ToComplex->getElementType());
1823 }
1824 
1825 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1826 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1827 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1828 /// if non-empty, will be a pointer to ToType that may or may not have
1829 /// the right set of qualifiers on its pointee.
1830 ///
1831 static QualType
1832 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1833                                    QualType ToPointee, QualType ToType,
1834                                    ASTContext &Context,
1835                                    bool StripObjCLifetime = false) {
1836   assert((FromPtr->getTypeClass() == Type::Pointer ||
1837           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1838          "Invalid similarly-qualified pointer type");
1839 
1840   /// Conversions to 'id' subsume cv-qualifier conversions.
1841   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1842     return ToType.getUnqualifiedType();
1843 
1844   QualType CanonFromPointee
1845     = Context.getCanonicalType(FromPtr->getPointeeType());
1846   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1847   Qualifiers Quals = CanonFromPointee.getQualifiers();
1848 
1849   if (StripObjCLifetime)
1850     Quals.removeObjCLifetime();
1851 
1852   // Exact qualifier match -> return the pointer type we're converting to.
1853   if (CanonToPointee.getLocalQualifiers() == Quals) {
1854     // ToType is exactly what we need. Return it.
1855     if (!ToType.isNull())
1856       return ToType.getUnqualifiedType();
1857 
1858     // Build a pointer to ToPointee. It has the right qualifiers
1859     // already.
1860     if (isa<ObjCObjectPointerType>(ToType))
1861       return Context.getObjCObjectPointerType(ToPointee);
1862     return Context.getPointerType(ToPointee);
1863   }
1864 
1865   // Just build a canonical type that has the right qualifiers.
1866   QualType QualifiedCanonToPointee
1867     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1868 
1869   if (isa<ObjCObjectPointerType>(ToType))
1870     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1871   return Context.getPointerType(QualifiedCanonToPointee);
1872 }
1873 
1874 static bool isNullPointerConstantForConversion(Expr *Expr,
1875                                                bool InOverloadResolution,
1876                                                ASTContext &Context) {
1877   // Handle value-dependent integral null pointer constants correctly.
1878   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1879   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1880       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1881     return !InOverloadResolution;
1882 
1883   return Expr->isNullPointerConstant(Context,
1884                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1885                                         : Expr::NPC_ValueDependentIsNull);
1886 }
1887 
1888 /// IsPointerConversion - Determines whether the conversion of the
1889 /// expression From, which has the (possibly adjusted) type FromType,
1890 /// can be converted to the type ToType via a pointer conversion (C++
1891 /// 4.10). If so, returns true and places the converted type (that
1892 /// might differ from ToType in its cv-qualifiers at some level) into
1893 /// ConvertedType.
1894 ///
1895 /// This routine also supports conversions to and from block pointers
1896 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1897 /// pointers to interfaces. FIXME: Once we've determined the
1898 /// appropriate overloading rules for Objective-C, we may want to
1899 /// split the Objective-C checks into a different routine; however,
1900 /// GCC seems to consider all of these conversions to be pointer
1901 /// conversions, so for now they live here. IncompatibleObjC will be
1902 /// set if the conversion is an allowed Objective-C conversion that
1903 /// should result in a warning.
1904 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1905                                bool InOverloadResolution,
1906                                QualType& ConvertedType,
1907                                bool &IncompatibleObjC) {
1908   IncompatibleObjC = false;
1909   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1910                               IncompatibleObjC))
1911     return true;
1912 
1913   // Conversion from a null pointer constant to any Objective-C pointer type.
1914   if (ToType->isObjCObjectPointerType() &&
1915       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1916     ConvertedType = ToType;
1917     return true;
1918   }
1919 
1920   // Blocks: Block pointers can be converted to void*.
1921   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1922       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1923     ConvertedType = ToType;
1924     return true;
1925   }
1926   // Blocks: A null pointer constant can be converted to a block
1927   // pointer type.
1928   if (ToType->isBlockPointerType() &&
1929       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1930     ConvertedType = ToType;
1931     return true;
1932   }
1933 
1934   // If the left-hand-side is nullptr_t, the right side can be a null
1935   // pointer constant.
1936   if (ToType->isNullPtrType() &&
1937       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1938     ConvertedType = ToType;
1939     return true;
1940   }
1941 
1942   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1943   if (!ToTypePtr)
1944     return false;
1945 
1946   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1947   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1948     ConvertedType = ToType;
1949     return true;
1950   }
1951 
1952   // Beyond this point, both types need to be pointers
1953   // , including objective-c pointers.
1954   QualType ToPointeeType = ToTypePtr->getPointeeType();
1955   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1956       !getLangOpts().ObjCAutoRefCount) {
1957     ConvertedType = BuildSimilarlyQualifiedPointerType(
1958                                       FromType->getAs<ObjCObjectPointerType>(),
1959                                                        ToPointeeType,
1960                                                        ToType, Context);
1961     return true;
1962   }
1963   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1964   if (!FromTypePtr)
1965     return false;
1966 
1967   QualType FromPointeeType = FromTypePtr->getPointeeType();
1968 
1969   // If the unqualified pointee types are the same, this can't be a
1970   // pointer conversion, so don't do all of the work below.
1971   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1972     return false;
1973 
1974   // An rvalue of type "pointer to cv T," where T is an object type,
1975   // can be converted to an rvalue of type "pointer to cv void" (C++
1976   // 4.10p2).
1977   if (FromPointeeType->isIncompleteOrObjectType() &&
1978       ToPointeeType->isVoidType()) {
1979     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1980                                                        ToPointeeType,
1981                                                        ToType, Context,
1982                                                    /*StripObjCLifetime=*/true);
1983     return true;
1984   }
1985 
1986   // MSVC allows implicit function to void* type conversion.
1987   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
1988       ToPointeeType->isVoidType()) {
1989     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1990                                                        ToPointeeType,
1991                                                        ToType, Context);
1992     return true;
1993   }
1994 
1995   // When we're overloading in C, we allow a special kind of pointer
1996   // conversion for compatible-but-not-identical pointee types.
1997   if (!getLangOpts().CPlusPlus &&
1998       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1999     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2000                                                        ToPointeeType,
2001                                                        ToType, Context);
2002     return true;
2003   }
2004 
2005   // C++ [conv.ptr]p3:
2006   //
2007   //   An rvalue of type "pointer to cv D," where D is a class type,
2008   //   can be converted to an rvalue of type "pointer to cv B," where
2009   //   B is a base class (clause 10) of D. If B is an inaccessible
2010   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2011   //   necessitates this conversion is ill-formed. The result of the
2012   //   conversion is a pointer to the base class sub-object of the
2013   //   derived class object. The null pointer value is converted to
2014   //   the null pointer value of the destination type.
2015   //
2016   // Note that we do not check for ambiguity or inaccessibility
2017   // here. That is handled by CheckPointerConversion.
2018   if (getLangOpts().CPlusPlus &&
2019       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2020       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2021       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2022       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2023     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2024                                                        ToPointeeType,
2025                                                        ToType, Context);
2026     return true;
2027   }
2028 
2029   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2030       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2031     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2032                                                        ToPointeeType,
2033                                                        ToType, Context);
2034     return true;
2035   }
2036 
2037   return false;
2038 }
2039 
2040 /// \brief Adopt the given qualifiers for the given type.
2041 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2042   Qualifiers TQs = T.getQualifiers();
2043 
2044   // Check whether qualifiers already match.
2045   if (TQs == Qs)
2046     return T;
2047 
2048   if (Qs.compatiblyIncludes(TQs))
2049     return Context.getQualifiedType(T, Qs);
2050 
2051   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2052 }
2053 
2054 /// isObjCPointerConversion - Determines whether this is an
2055 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2056 /// with the same arguments and return values.
2057 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2058                                    QualType& ConvertedType,
2059                                    bool &IncompatibleObjC) {
2060   if (!getLangOpts().ObjC1)
2061     return false;
2062 
2063   // The set of qualifiers on the type we're converting from.
2064   Qualifiers FromQualifiers = FromType.getQualifiers();
2065 
2066   // First, we handle all conversions on ObjC object pointer types.
2067   const ObjCObjectPointerType* ToObjCPtr =
2068     ToType->getAs<ObjCObjectPointerType>();
2069   const ObjCObjectPointerType *FromObjCPtr =
2070     FromType->getAs<ObjCObjectPointerType>();
2071 
2072   if (ToObjCPtr && FromObjCPtr) {
2073     // If the pointee types are the same (ignoring qualifications),
2074     // then this is not a pointer conversion.
2075     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2076                                        FromObjCPtr->getPointeeType()))
2077       return false;
2078 
2079     // Check for compatible
2080     // Objective C++: We're able to convert between "id" or "Class" and a
2081     // pointer to any interface (in both directions).
2082     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2083       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2084       return true;
2085     }
2086     // Conversions with Objective-C's id<...>.
2087     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2088          ToObjCPtr->isObjCQualifiedIdType()) &&
2089         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2090                                                   /*compare=*/false)) {
2091       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2092       return true;
2093     }
2094     // Objective C++: We're able to convert from a pointer to an
2095     // interface to a pointer to a different interface.
2096     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2097       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2098       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2099       if (getLangOpts().CPlusPlus && LHS && RHS &&
2100           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2101                                                 FromObjCPtr->getPointeeType()))
2102         return false;
2103       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2104                                                    ToObjCPtr->getPointeeType(),
2105                                                          ToType, Context);
2106       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2107       return true;
2108     }
2109 
2110     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2111       // Okay: this is some kind of implicit downcast of Objective-C
2112       // interfaces, which is permitted. However, we're going to
2113       // complain about it.
2114       IncompatibleObjC = true;
2115       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2116                                                    ToObjCPtr->getPointeeType(),
2117                                                          ToType, Context);
2118       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2119       return true;
2120     }
2121   }
2122   // Beyond this point, both types need to be C pointers or block pointers.
2123   QualType ToPointeeType;
2124   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2125     ToPointeeType = ToCPtr->getPointeeType();
2126   else if (const BlockPointerType *ToBlockPtr =
2127             ToType->getAs<BlockPointerType>()) {
2128     // Objective C++: We're able to convert from a pointer to any object
2129     // to a block pointer type.
2130     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2131       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2132       return true;
2133     }
2134     ToPointeeType = ToBlockPtr->getPointeeType();
2135   }
2136   else if (FromType->getAs<BlockPointerType>() &&
2137            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2138     // Objective C++: We're able to convert from a block pointer type to a
2139     // pointer to any object.
2140     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2141     return true;
2142   }
2143   else
2144     return false;
2145 
2146   QualType FromPointeeType;
2147   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2148     FromPointeeType = FromCPtr->getPointeeType();
2149   else if (const BlockPointerType *FromBlockPtr =
2150            FromType->getAs<BlockPointerType>())
2151     FromPointeeType = FromBlockPtr->getPointeeType();
2152   else
2153     return false;
2154 
2155   // If we have pointers to pointers, recursively check whether this
2156   // is an Objective-C conversion.
2157   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2158       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2159                               IncompatibleObjC)) {
2160     // We always complain about this conversion.
2161     IncompatibleObjC = true;
2162     ConvertedType = Context.getPointerType(ConvertedType);
2163     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2164     return true;
2165   }
2166   // Allow conversion of pointee being objective-c pointer to another one;
2167   // as in I* to id.
2168   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2169       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2170       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2171                               IncompatibleObjC)) {
2172 
2173     ConvertedType = Context.getPointerType(ConvertedType);
2174     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2175     return true;
2176   }
2177 
2178   // If we have pointers to functions or blocks, check whether the only
2179   // differences in the argument and result types are in Objective-C
2180   // pointer conversions. If so, we permit the conversion (but
2181   // complain about it).
2182   const FunctionProtoType *FromFunctionType
2183     = FromPointeeType->getAs<FunctionProtoType>();
2184   const FunctionProtoType *ToFunctionType
2185     = ToPointeeType->getAs<FunctionProtoType>();
2186   if (FromFunctionType && ToFunctionType) {
2187     // If the function types are exactly the same, this isn't an
2188     // Objective-C pointer conversion.
2189     if (Context.getCanonicalType(FromPointeeType)
2190           == Context.getCanonicalType(ToPointeeType))
2191       return false;
2192 
2193     // Perform the quick checks that will tell us whether these
2194     // function types are obviously different.
2195     if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2196         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2197         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2198       return false;
2199 
2200     bool HasObjCConversion = false;
2201     if (Context.getCanonicalType(FromFunctionType->getResultType())
2202           == Context.getCanonicalType(ToFunctionType->getResultType())) {
2203       // Okay, the types match exactly. Nothing to do.
2204     } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2205                                        ToFunctionType->getResultType(),
2206                                        ConvertedType, IncompatibleObjC)) {
2207       // Okay, we have an Objective-C pointer conversion.
2208       HasObjCConversion = true;
2209     } else {
2210       // Function types are too different. Abort.
2211       return false;
2212     }
2213 
2214     // Check argument types.
2215     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2216          ArgIdx != NumArgs; ++ArgIdx) {
2217       QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2218       QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2219       if (Context.getCanonicalType(FromArgType)
2220             == Context.getCanonicalType(ToArgType)) {
2221         // Okay, the types match exactly. Nothing to do.
2222       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2223                                          ConvertedType, IncompatibleObjC)) {
2224         // Okay, we have an Objective-C pointer conversion.
2225         HasObjCConversion = true;
2226       } else {
2227         // Argument types are too different. Abort.
2228         return false;
2229       }
2230     }
2231 
2232     if (HasObjCConversion) {
2233       // We had an Objective-C conversion. Allow this pointer
2234       // conversion, but complain about it.
2235       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2236       IncompatibleObjC = true;
2237       return true;
2238     }
2239   }
2240 
2241   return false;
2242 }
2243 
2244 /// \brief Determine whether this is an Objective-C writeback conversion,
2245 /// used for parameter passing when performing automatic reference counting.
2246 ///
2247 /// \param FromType The type we're converting form.
2248 ///
2249 /// \param ToType The type we're converting to.
2250 ///
2251 /// \param ConvertedType The type that will be produced after applying
2252 /// this conversion.
2253 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2254                                      QualType &ConvertedType) {
2255   if (!getLangOpts().ObjCAutoRefCount ||
2256       Context.hasSameUnqualifiedType(FromType, ToType))
2257     return false;
2258 
2259   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2260   QualType ToPointee;
2261   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2262     ToPointee = ToPointer->getPointeeType();
2263   else
2264     return false;
2265 
2266   Qualifiers ToQuals = ToPointee.getQualifiers();
2267   if (!ToPointee->isObjCLifetimeType() ||
2268       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2269       !ToQuals.withoutObjCLifetime().empty())
2270     return false;
2271 
2272   // Argument must be a pointer to __strong to __weak.
2273   QualType FromPointee;
2274   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2275     FromPointee = FromPointer->getPointeeType();
2276   else
2277     return false;
2278 
2279   Qualifiers FromQuals = FromPointee.getQualifiers();
2280   if (!FromPointee->isObjCLifetimeType() ||
2281       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2282        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2283     return false;
2284 
2285   // Make sure that we have compatible qualifiers.
2286   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2287   if (!ToQuals.compatiblyIncludes(FromQuals))
2288     return false;
2289 
2290   // Remove qualifiers from the pointee type we're converting from; they
2291   // aren't used in the compatibility check belong, and we'll be adding back
2292   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2293   FromPointee = FromPointee.getUnqualifiedType();
2294 
2295   // The unqualified form of the pointee types must be compatible.
2296   ToPointee = ToPointee.getUnqualifiedType();
2297   bool IncompatibleObjC;
2298   if (Context.typesAreCompatible(FromPointee, ToPointee))
2299     FromPointee = ToPointee;
2300   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2301                                     IncompatibleObjC))
2302     return false;
2303 
2304   /// \brief Construct the type we're converting to, which is a pointer to
2305   /// __autoreleasing pointee.
2306   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2307   ConvertedType = Context.getPointerType(FromPointee);
2308   return true;
2309 }
2310 
2311 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2312                                     QualType& ConvertedType) {
2313   QualType ToPointeeType;
2314   if (const BlockPointerType *ToBlockPtr =
2315         ToType->getAs<BlockPointerType>())
2316     ToPointeeType = ToBlockPtr->getPointeeType();
2317   else
2318     return false;
2319 
2320   QualType FromPointeeType;
2321   if (const BlockPointerType *FromBlockPtr =
2322       FromType->getAs<BlockPointerType>())
2323     FromPointeeType = FromBlockPtr->getPointeeType();
2324   else
2325     return false;
2326   // We have pointer to blocks, check whether the only
2327   // differences in the argument and result types are in Objective-C
2328   // pointer conversions. If so, we permit the conversion.
2329 
2330   const FunctionProtoType *FromFunctionType
2331     = FromPointeeType->getAs<FunctionProtoType>();
2332   const FunctionProtoType *ToFunctionType
2333     = ToPointeeType->getAs<FunctionProtoType>();
2334 
2335   if (!FromFunctionType || !ToFunctionType)
2336     return false;
2337 
2338   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2339     return true;
2340 
2341   // Perform the quick checks that will tell us whether these
2342   // function types are obviously different.
2343   if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2344       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2345     return false;
2346 
2347   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2348   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2349   if (FromEInfo != ToEInfo)
2350     return false;
2351 
2352   bool IncompatibleObjC = false;
2353   if (Context.hasSameType(FromFunctionType->getResultType(),
2354                           ToFunctionType->getResultType())) {
2355     // Okay, the types match exactly. Nothing to do.
2356   } else {
2357     QualType RHS = FromFunctionType->getResultType();
2358     QualType LHS = ToFunctionType->getResultType();
2359     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2360         !RHS.hasQualifiers() && LHS.hasQualifiers())
2361        LHS = LHS.getUnqualifiedType();
2362 
2363      if (Context.hasSameType(RHS,LHS)) {
2364        // OK exact match.
2365      } else if (isObjCPointerConversion(RHS, LHS,
2366                                         ConvertedType, IncompatibleObjC)) {
2367      if (IncompatibleObjC)
2368        return false;
2369      // Okay, we have an Objective-C pointer conversion.
2370      }
2371      else
2372        return false;
2373    }
2374 
2375    // Check argument types.
2376    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2377         ArgIdx != NumArgs; ++ArgIdx) {
2378      IncompatibleObjC = false;
2379      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2380      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2381      if (Context.hasSameType(FromArgType, ToArgType)) {
2382        // Okay, the types match exactly. Nothing to do.
2383      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2384                                         ConvertedType, IncompatibleObjC)) {
2385        if (IncompatibleObjC)
2386          return false;
2387        // Okay, we have an Objective-C pointer conversion.
2388      } else
2389        // Argument types are too different. Abort.
2390        return false;
2391    }
2392    if (LangOpts.ObjCAutoRefCount &&
2393        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2394                                                     ToFunctionType))
2395      return false;
2396 
2397    ConvertedType = ToType;
2398    return true;
2399 }
2400 
2401 enum {
2402   ft_default,
2403   ft_different_class,
2404   ft_parameter_arity,
2405   ft_parameter_mismatch,
2406   ft_return_type,
2407   ft_qualifer_mismatch
2408 };
2409 
2410 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2411 /// function types.  Catches different number of parameter, mismatch in
2412 /// parameter types, and different return types.
2413 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2414                                       QualType FromType, QualType ToType) {
2415   // If either type is not valid, include no extra info.
2416   if (FromType.isNull() || ToType.isNull()) {
2417     PDiag << ft_default;
2418     return;
2419   }
2420 
2421   // Get the function type from the pointers.
2422   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2423     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2424                             *ToMember = ToType->getAs<MemberPointerType>();
2425     if (FromMember->getClass() != ToMember->getClass()) {
2426       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2427             << QualType(FromMember->getClass(), 0);
2428       return;
2429     }
2430     FromType = FromMember->getPointeeType();
2431     ToType = ToMember->getPointeeType();
2432   }
2433 
2434   if (FromType->isPointerType())
2435     FromType = FromType->getPointeeType();
2436   if (ToType->isPointerType())
2437     ToType = ToType->getPointeeType();
2438 
2439   // Remove references.
2440   FromType = FromType.getNonReferenceType();
2441   ToType = ToType.getNonReferenceType();
2442 
2443   // Don't print extra info for non-specialized template functions.
2444   if (FromType->isInstantiationDependentType() &&
2445       !FromType->getAs<TemplateSpecializationType>()) {
2446     PDiag << ft_default;
2447     return;
2448   }
2449 
2450   // No extra info for same types.
2451   if (Context.hasSameType(FromType, ToType)) {
2452     PDiag << ft_default;
2453     return;
2454   }
2455 
2456   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2457                           *ToFunction = ToType->getAs<FunctionProtoType>();
2458 
2459   // Both types need to be function types.
2460   if (!FromFunction || !ToFunction) {
2461     PDiag << ft_default;
2462     return;
2463   }
2464 
2465   if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2466     PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2467           << FromFunction->getNumArgs();
2468     return;
2469   }
2470 
2471   // Handle different parameter types.
2472   unsigned ArgPos;
2473   if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2474     PDiag << ft_parameter_mismatch << ArgPos + 1
2475           << ToFunction->getArgType(ArgPos)
2476           << FromFunction->getArgType(ArgPos);
2477     return;
2478   }
2479 
2480   // Handle different return type.
2481   if (!Context.hasSameType(FromFunction->getResultType(),
2482                            ToFunction->getResultType())) {
2483     PDiag << ft_return_type << ToFunction->getResultType()
2484           << FromFunction->getResultType();
2485     return;
2486   }
2487 
2488   unsigned FromQuals = FromFunction->getTypeQuals(),
2489            ToQuals = ToFunction->getTypeQuals();
2490   if (FromQuals != ToQuals) {
2491     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2492     return;
2493   }
2494 
2495   // Unable to find a difference, so add no extra info.
2496   PDiag << ft_default;
2497 }
2498 
2499 /// FunctionArgTypesAreEqual - This routine checks two function proto types
2500 /// for equality of their argument types. Caller has already checked that
2501 /// they have same number of arguments. This routine assumes that Objective-C
2502 /// pointer types which only differ in their protocol qualifiers are equal.
2503 /// If the parameters are different, ArgPos will have the parameter index
2504 /// of the first different parameter.
2505 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2506                                     const FunctionProtoType *NewType,
2507                                     unsigned *ArgPos) {
2508   if (!getLangOpts().ObjC1) {
2509     for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2510          N = NewType->arg_type_begin(),
2511          E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2512       if (!Context.hasSameType(*O, *N)) {
2513         if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2514         return false;
2515       }
2516     }
2517     return true;
2518   }
2519 
2520   for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2521        N = NewType->arg_type_begin(),
2522        E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2523     QualType ToType = (*O);
2524     QualType FromType = (*N);
2525     if (!Context.hasSameType(ToType, FromType)) {
2526       if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2527         if (const PointerType *PTFr = FromType->getAs<PointerType>())
2528           if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2529                PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2530               (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2531                PTFr->getPointeeType()->isObjCQualifiedClassType()))
2532             continue;
2533       }
2534       else if (const ObjCObjectPointerType *PTTo =
2535                  ToType->getAs<ObjCObjectPointerType>()) {
2536         if (const ObjCObjectPointerType *PTFr =
2537               FromType->getAs<ObjCObjectPointerType>())
2538           if (Context.hasSameUnqualifiedType(
2539                 PTTo->getObjectType()->getBaseType(),
2540                 PTFr->getObjectType()->getBaseType()))
2541             continue;
2542       }
2543       if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2544       return false;
2545     }
2546   }
2547   return true;
2548 }
2549 
2550 /// CheckPointerConversion - Check the pointer conversion from the
2551 /// expression From to the type ToType. This routine checks for
2552 /// ambiguous or inaccessible derived-to-base pointer
2553 /// conversions for which IsPointerConversion has already returned
2554 /// true. It returns true and produces a diagnostic if there was an
2555 /// error, or returns false otherwise.
2556 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2557                                   CastKind &Kind,
2558                                   CXXCastPath& BasePath,
2559                                   bool IgnoreBaseAccess) {
2560   QualType FromType = From->getType();
2561   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2562 
2563   Kind = CK_BitCast;
2564 
2565   if (!IsCStyleOrFunctionalCast &&
2566       Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2567       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2568     DiagRuntimeBehavior(From->getExprLoc(), From,
2569                         PDiag(diag::warn_impcast_bool_to_null_pointer)
2570                           << ToType << From->getSourceRange());
2571 
2572   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2573     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2574       QualType FromPointeeType = FromPtrType->getPointeeType(),
2575                ToPointeeType   = ToPtrType->getPointeeType();
2576 
2577       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2578           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2579         // We must have a derived-to-base conversion. Check an
2580         // ambiguous or inaccessible conversion.
2581         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2582                                          From->getExprLoc(),
2583                                          From->getSourceRange(), &BasePath,
2584                                          IgnoreBaseAccess))
2585           return true;
2586 
2587         // The conversion was successful.
2588         Kind = CK_DerivedToBase;
2589       }
2590     }
2591   } else if (const ObjCObjectPointerType *ToPtrType =
2592                ToType->getAs<ObjCObjectPointerType>()) {
2593     if (const ObjCObjectPointerType *FromPtrType =
2594           FromType->getAs<ObjCObjectPointerType>()) {
2595       // Objective-C++ conversions are always okay.
2596       // FIXME: We should have a different class of conversions for the
2597       // Objective-C++ implicit conversions.
2598       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2599         return false;
2600     } else if (FromType->isBlockPointerType()) {
2601       Kind = CK_BlockPointerToObjCPointerCast;
2602     } else {
2603       Kind = CK_CPointerToObjCPointerCast;
2604     }
2605   } else if (ToType->isBlockPointerType()) {
2606     if (!FromType->isBlockPointerType())
2607       Kind = CK_AnyPointerToBlockPointerCast;
2608   }
2609 
2610   // We shouldn't fall into this case unless it's valid for other
2611   // reasons.
2612   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2613     Kind = CK_NullToPointer;
2614 
2615   return false;
2616 }
2617 
2618 /// IsMemberPointerConversion - Determines whether the conversion of the
2619 /// expression From, which has the (possibly adjusted) type FromType, can be
2620 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2621 /// If so, returns true and places the converted type (that might differ from
2622 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2623 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2624                                      QualType ToType,
2625                                      bool InOverloadResolution,
2626                                      QualType &ConvertedType) {
2627   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2628   if (!ToTypePtr)
2629     return false;
2630 
2631   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2632   if (From->isNullPointerConstant(Context,
2633                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2634                                         : Expr::NPC_ValueDependentIsNull)) {
2635     ConvertedType = ToType;
2636     return true;
2637   }
2638 
2639   // Otherwise, both types have to be member pointers.
2640   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2641   if (!FromTypePtr)
2642     return false;
2643 
2644   // A pointer to member of B can be converted to a pointer to member of D,
2645   // where D is derived from B (C++ 4.11p2).
2646   QualType FromClass(FromTypePtr->getClass(), 0);
2647   QualType ToClass(ToTypePtr->getClass(), 0);
2648 
2649   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2650       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2651       IsDerivedFrom(ToClass, FromClass)) {
2652     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2653                                                  ToClass.getTypePtr());
2654     return true;
2655   }
2656 
2657   return false;
2658 }
2659 
2660 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2661 /// expression From to the type ToType. This routine checks for ambiguous or
2662 /// virtual or inaccessible base-to-derived member pointer conversions
2663 /// for which IsMemberPointerConversion has already returned true. It returns
2664 /// true and produces a diagnostic if there was an error, or returns false
2665 /// otherwise.
2666 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2667                                         CastKind &Kind,
2668                                         CXXCastPath &BasePath,
2669                                         bool IgnoreBaseAccess) {
2670   QualType FromType = From->getType();
2671   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2672   if (!FromPtrType) {
2673     // This must be a null pointer to member pointer conversion
2674     assert(From->isNullPointerConstant(Context,
2675                                        Expr::NPC_ValueDependentIsNull) &&
2676            "Expr must be null pointer constant!");
2677     Kind = CK_NullToMemberPointer;
2678     return false;
2679   }
2680 
2681   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2682   assert(ToPtrType && "No member pointer cast has a target type "
2683                       "that is not a member pointer.");
2684 
2685   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2686   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2687 
2688   // FIXME: What about dependent types?
2689   assert(FromClass->isRecordType() && "Pointer into non-class.");
2690   assert(ToClass->isRecordType() && "Pointer into non-class.");
2691 
2692   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2693                      /*DetectVirtual=*/true);
2694   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2695   assert(DerivationOkay &&
2696          "Should not have been called if derivation isn't OK.");
2697   (void)DerivationOkay;
2698 
2699   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2700                                   getUnqualifiedType())) {
2701     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2702     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2703       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2704     return true;
2705   }
2706 
2707   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2708     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2709       << FromClass << ToClass << QualType(VBase, 0)
2710       << From->getSourceRange();
2711     return true;
2712   }
2713 
2714   if (!IgnoreBaseAccess)
2715     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2716                          Paths.front(),
2717                          diag::err_downcast_from_inaccessible_base);
2718 
2719   // Must be a base to derived member conversion.
2720   BuildBasePathArray(Paths, BasePath);
2721   Kind = CK_BaseToDerivedMemberPointer;
2722   return false;
2723 }
2724 
2725 /// IsQualificationConversion - Determines whether the conversion from
2726 /// an rvalue of type FromType to ToType is a qualification conversion
2727 /// (C++ 4.4).
2728 ///
2729 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2730 /// when the qualification conversion involves a change in the Objective-C
2731 /// object lifetime.
2732 bool
2733 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2734                                 bool CStyle, bool &ObjCLifetimeConversion) {
2735   FromType = Context.getCanonicalType(FromType);
2736   ToType = Context.getCanonicalType(ToType);
2737   ObjCLifetimeConversion = false;
2738 
2739   // If FromType and ToType are the same type, this is not a
2740   // qualification conversion.
2741   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2742     return false;
2743 
2744   // (C++ 4.4p4):
2745   //   A conversion can add cv-qualifiers at levels other than the first
2746   //   in multi-level pointers, subject to the following rules: [...]
2747   bool PreviousToQualsIncludeConst = true;
2748   bool UnwrappedAnyPointer = false;
2749   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2750     // Within each iteration of the loop, we check the qualifiers to
2751     // determine if this still looks like a qualification
2752     // conversion. Then, if all is well, we unwrap one more level of
2753     // pointers or pointers-to-members and do it all again
2754     // until there are no more pointers or pointers-to-members left to
2755     // unwrap.
2756     UnwrappedAnyPointer = true;
2757 
2758     Qualifiers FromQuals = FromType.getQualifiers();
2759     Qualifiers ToQuals = ToType.getQualifiers();
2760 
2761     // Objective-C ARC:
2762     //   Check Objective-C lifetime conversions.
2763     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2764         UnwrappedAnyPointer) {
2765       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2766         ObjCLifetimeConversion = true;
2767         FromQuals.removeObjCLifetime();
2768         ToQuals.removeObjCLifetime();
2769       } else {
2770         // Qualification conversions cannot cast between different
2771         // Objective-C lifetime qualifiers.
2772         return false;
2773       }
2774     }
2775 
2776     // Allow addition/removal of GC attributes but not changing GC attributes.
2777     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2778         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2779       FromQuals.removeObjCGCAttr();
2780       ToQuals.removeObjCGCAttr();
2781     }
2782 
2783     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2784     //      2,j, and similarly for volatile.
2785     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2786       return false;
2787 
2788     //   -- if the cv 1,j and cv 2,j are different, then const is in
2789     //      every cv for 0 < k < j.
2790     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2791         && !PreviousToQualsIncludeConst)
2792       return false;
2793 
2794     // Keep track of whether all prior cv-qualifiers in the "to" type
2795     // include const.
2796     PreviousToQualsIncludeConst
2797       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2798   }
2799 
2800   // We are left with FromType and ToType being the pointee types
2801   // after unwrapping the original FromType and ToType the same number
2802   // of types. If we unwrapped any pointers, and if FromType and
2803   // ToType have the same unqualified type (since we checked
2804   // qualifiers above), then this is a qualification conversion.
2805   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2806 }
2807 
2808 /// \brief - Determine whether this is a conversion from a scalar type to an
2809 /// atomic type.
2810 ///
2811 /// If successful, updates \c SCS's second and third steps in the conversion
2812 /// sequence to finish the conversion.
2813 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2814                                 bool InOverloadResolution,
2815                                 StandardConversionSequence &SCS,
2816                                 bool CStyle) {
2817   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2818   if (!ToAtomic)
2819     return false;
2820 
2821   StandardConversionSequence InnerSCS;
2822   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2823                             InOverloadResolution, InnerSCS,
2824                             CStyle, /*AllowObjCWritebackConversion=*/false))
2825     return false;
2826 
2827   SCS.Second = InnerSCS.Second;
2828   SCS.setToType(1, InnerSCS.getToType(1));
2829   SCS.Third = InnerSCS.Third;
2830   SCS.QualificationIncludesObjCLifetime
2831     = InnerSCS.QualificationIncludesObjCLifetime;
2832   SCS.setToType(2, InnerSCS.getToType(2));
2833   return true;
2834 }
2835 
2836 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2837                                               CXXConstructorDecl *Constructor,
2838                                               QualType Type) {
2839   const FunctionProtoType *CtorType =
2840       Constructor->getType()->getAs<FunctionProtoType>();
2841   if (CtorType->getNumArgs() > 0) {
2842     QualType FirstArg = CtorType->getArgType(0);
2843     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2844       return true;
2845   }
2846   return false;
2847 }
2848 
2849 static OverloadingResult
2850 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2851                                        CXXRecordDecl *To,
2852                                        UserDefinedConversionSequence &User,
2853                                        OverloadCandidateSet &CandidateSet,
2854                                        bool AllowExplicit) {
2855   DeclContext::lookup_iterator Con, ConEnd;
2856   for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2857        Con != ConEnd; ++Con) {
2858     NamedDecl *D = *Con;
2859     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2860 
2861     // Find the constructor (which may be a template).
2862     CXXConstructorDecl *Constructor = 0;
2863     FunctionTemplateDecl *ConstructorTmpl
2864       = dyn_cast<FunctionTemplateDecl>(D);
2865     if (ConstructorTmpl)
2866       Constructor
2867         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2868     else
2869       Constructor = cast<CXXConstructorDecl>(D);
2870 
2871     bool Usable = !Constructor->isInvalidDecl() &&
2872                   S.isInitListConstructor(Constructor) &&
2873                   (AllowExplicit || !Constructor->isExplicit());
2874     if (Usable) {
2875       // If the first argument is (a reference to) the target type,
2876       // suppress conversions.
2877       bool SuppressUserConversions =
2878           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2879       if (ConstructorTmpl)
2880         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2881                                        /*ExplicitArgs*/ 0,
2882                                        From, CandidateSet,
2883                                        SuppressUserConversions);
2884       else
2885         S.AddOverloadCandidate(Constructor, FoundDecl,
2886                                From, CandidateSet,
2887                                SuppressUserConversions);
2888     }
2889   }
2890 
2891   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2892 
2893   OverloadCandidateSet::iterator Best;
2894   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2895   case OR_Success: {
2896     // Record the standard conversion we used and the conversion function.
2897     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2898     S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2899 
2900     QualType ThisType = Constructor->getThisType(S.Context);
2901     // Initializer lists don't have conversions as such.
2902     User.Before.setAsIdentityConversion();
2903     User.HadMultipleCandidates = HadMultipleCandidates;
2904     User.ConversionFunction = Constructor;
2905     User.FoundConversionFunction = Best->FoundDecl;
2906     User.After.setAsIdentityConversion();
2907     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2908     User.After.setAllToTypes(ToType);
2909     return OR_Success;
2910   }
2911 
2912   case OR_No_Viable_Function:
2913     return OR_No_Viable_Function;
2914   case OR_Deleted:
2915     return OR_Deleted;
2916   case OR_Ambiguous:
2917     return OR_Ambiguous;
2918   }
2919 
2920   llvm_unreachable("Invalid OverloadResult!");
2921 }
2922 
2923 /// Determines whether there is a user-defined conversion sequence
2924 /// (C++ [over.ics.user]) that converts expression From to the type
2925 /// ToType. If such a conversion exists, User will contain the
2926 /// user-defined conversion sequence that performs such a conversion
2927 /// and this routine will return true. Otherwise, this routine returns
2928 /// false and User is unspecified.
2929 ///
2930 /// \param AllowExplicit  true if the conversion should consider C++0x
2931 /// "explicit" conversion functions as well as non-explicit conversion
2932 /// functions (C++0x [class.conv.fct]p2).
2933 static OverloadingResult
2934 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2935                         UserDefinedConversionSequence &User,
2936                         OverloadCandidateSet &CandidateSet,
2937                         bool AllowExplicit) {
2938   // Whether we will only visit constructors.
2939   bool ConstructorsOnly = false;
2940 
2941   // If the type we are conversion to is a class type, enumerate its
2942   // constructors.
2943   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2944     // C++ [over.match.ctor]p1:
2945     //   When objects of class type are direct-initialized (8.5), or
2946     //   copy-initialized from an expression of the same or a
2947     //   derived class type (8.5), overload resolution selects the
2948     //   constructor. [...] For copy-initialization, the candidate
2949     //   functions are all the converting constructors (12.3.1) of
2950     //   that class. The argument list is the expression-list within
2951     //   the parentheses of the initializer.
2952     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2953         (From->getType()->getAs<RecordType>() &&
2954          S.IsDerivedFrom(From->getType(), ToType)))
2955       ConstructorsOnly = true;
2956 
2957     S.RequireCompleteType(From->getLocStart(), ToType, 0);
2958     // RequireCompleteType may have returned true due to some invalid decl
2959     // during template instantiation, but ToType may be complete enough now
2960     // to try to recover.
2961     if (ToType->isIncompleteType()) {
2962       // We're not going to find any constructors.
2963     } else if (CXXRecordDecl *ToRecordDecl
2964                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2965 
2966       Expr **Args = &From;
2967       unsigned NumArgs = 1;
2968       bool ListInitializing = false;
2969       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2970         // But first, see if there is an init-list-contructor that will work.
2971         OverloadingResult Result = IsInitializerListConstructorConversion(
2972             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2973         if (Result != OR_No_Viable_Function)
2974           return Result;
2975         // Never mind.
2976         CandidateSet.clear();
2977 
2978         // If we're list-initializing, we pass the individual elements as
2979         // arguments, not the entire list.
2980         Args = InitList->getInits();
2981         NumArgs = InitList->getNumInits();
2982         ListInitializing = true;
2983       }
2984 
2985       DeclContext::lookup_iterator Con, ConEnd;
2986       for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
2987            Con != ConEnd; ++Con) {
2988         NamedDecl *D = *Con;
2989         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2990 
2991         // Find the constructor (which may be a template).
2992         CXXConstructorDecl *Constructor = 0;
2993         FunctionTemplateDecl *ConstructorTmpl
2994           = dyn_cast<FunctionTemplateDecl>(D);
2995         if (ConstructorTmpl)
2996           Constructor
2997             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2998         else
2999           Constructor = cast<CXXConstructorDecl>(D);
3000 
3001         bool Usable = !Constructor->isInvalidDecl();
3002         if (ListInitializing)
3003           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3004         else
3005           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3006         if (Usable) {
3007           bool SuppressUserConversions = !ConstructorsOnly;
3008           if (SuppressUserConversions && ListInitializing) {
3009             SuppressUserConversions = false;
3010             if (NumArgs == 1) {
3011               // If the first argument is (a reference to) the target type,
3012               // suppress conversions.
3013               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3014                                                 S.Context, Constructor, ToType);
3015             }
3016           }
3017           if (ConstructorTmpl)
3018             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3019                                            /*ExplicitArgs*/ 0,
3020                                            llvm::makeArrayRef(Args, NumArgs),
3021                                            CandidateSet, SuppressUserConversions);
3022           else
3023             // Allow one user-defined conversion when user specifies a
3024             // From->ToType conversion via an static cast (c-style, etc).
3025             S.AddOverloadCandidate(Constructor, FoundDecl,
3026                                    llvm::makeArrayRef(Args, NumArgs),
3027                                    CandidateSet, SuppressUserConversions);
3028         }
3029       }
3030     }
3031   }
3032 
3033   // Enumerate conversion functions, if we're allowed to.
3034   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3035   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3036     // No conversion functions from incomplete types.
3037   } else if (const RecordType *FromRecordType
3038                                    = From->getType()->getAs<RecordType>()) {
3039     if (CXXRecordDecl *FromRecordDecl
3040          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3041       // Add all of the conversion functions as candidates.
3042       const UnresolvedSetImpl *Conversions
3043         = FromRecordDecl->getVisibleConversionFunctions();
3044       for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3045              E = Conversions->end(); I != E; ++I) {
3046         DeclAccessPair FoundDecl = I.getPair();
3047         NamedDecl *D = FoundDecl.getDecl();
3048         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3049         if (isa<UsingShadowDecl>(D))
3050           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3051 
3052         CXXConversionDecl *Conv;
3053         FunctionTemplateDecl *ConvTemplate;
3054         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3055           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3056         else
3057           Conv = cast<CXXConversionDecl>(D);
3058 
3059         if (AllowExplicit || !Conv->isExplicit()) {
3060           if (ConvTemplate)
3061             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3062                                              ActingContext, From, ToType,
3063                                              CandidateSet);
3064           else
3065             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3066                                      From, ToType, CandidateSet);
3067         }
3068       }
3069     }
3070   }
3071 
3072   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3073 
3074   OverloadCandidateSet::iterator Best;
3075   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3076   case OR_Success:
3077     // Record the standard conversion we used and the conversion function.
3078     if (CXXConstructorDecl *Constructor
3079           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3080       S.MarkFunctionReferenced(From->getLocStart(), Constructor);
3081 
3082       // C++ [over.ics.user]p1:
3083       //   If the user-defined conversion is specified by a
3084       //   constructor (12.3.1), the initial standard conversion
3085       //   sequence converts the source type to the type required by
3086       //   the argument of the constructor.
3087       //
3088       QualType ThisType = Constructor->getThisType(S.Context);
3089       if (isa<InitListExpr>(From)) {
3090         // Initializer lists don't have conversions as such.
3091         User.Before.setAsIdentityConversion();
3092       } else {
3093         if (Best->Conversions[0].isEllipsis())
3094           User.EllipsisConversion = true;
3095         else {
3096           User.Before = Best->Conversions[0].Standard;
3097           User.EllipsisConversion = false;
3098         }
3099       }
3100       User.HadMultipleCandidates = HadMultipleCandidates;
3101       User.ConversionFunction = Constructor;
3102       User.FoundConversionFunction = Best->FoundDecl;
3103       User.After.setAsIdentityConversion();
3104       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3105       User.After.setAllToTypes(ToType);
3106       return OR_Success;
3107     }
3108     if (CXXConversionDecl *Conversion
3109                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3110       S.MarkFunctionReferenced(From->getLocStart(), Conversion);
3111 
3112       // C++ [over.ics.user]p1:
3113       //
3114       //   [...] If the user-defined conversion is specified by a
3115       //   conversion function (12.3.2), the initial standard
3116       //   conversion sequence converts the source type to the
3117       //   implicit object parameter of the conversion function.
3118       User.Before = Best->Conversions[0].Standard;
3119       User.HadMultipleCandidates = HadMultipleCandidates;
3120       User.ConversionFunction = Conversion;
3121       User.FoundConversionFunction = Best->FoundDecl;
3122       User.EllipsisConversion = false;
3123 
3124       // C++ [over.ics.user]p2:
3125       //   The second standard conversion sequence converts the
3126       //   result of the user-defined conversion to the target type
3127       //   for the sequence. Since an implicit conversion sequence
3128       //   is an initialization, the special rules for
3129       //   initialization by user-defined conversion apply when
3130       //   selecting the best user-defined conversion for a
3131       //   user-defined conversion sequence (see 13.3.3 and
3132       //   13.3.3.1).
3133       User.After = Best->FinalConversion;
3134       return OR_Success;
3135     }
3136     llvm_unreachable("Not a constructor or conversion function?");
3137 
3138   case OR_No_Viable_Function:
3139     return OR_No_Viable_Function;
3140   case OR_Deleted:
3141     // No conversion here! We're done.
3142     return OR_Deleted;
3143 
3144   case OR_Ambiguous:
3145     return OR_Ambiguous;
3146   }
3147 
3148   llvm_unreachable("Invalid OverloadResult!");
3149 }
3150 
3151 bool
3152 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3153   ImplicitConversionSequence ICS;
3154   OverloadCandidateSet CandidateSet(From->getExprLoc());
3155   OverloadingResult OvResult =
3156     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3157                             CandidateSet, false);
3158   if (OvResult == OR_Ambiguous)
3159     Diag(From->getLocStart(),
3160          diag::err_typecheck_ambiguous_condition)
3161           << From->getType() << ToType << From->getSourceRange();
3162   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3163     Diag(From->getLocStart(),
3164          diag::err_typecheck_nonviable_condition)
3165     << From->getType() << ToType << From->getSourceRange();
3166   else
3167     return false;
3168   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3169   return true;
3170 }
3171 
3172 /// \brief Compare the user-defined conversion functions or constructors
3173 /// of two user-defined conversion sequences to determine whether any ordering
3174 /// is possible.
3175 static ImplicitConversionSequence::CompareKind
3176 compareConversionFunctions(Sema &S,
3177                            FunctionDecl *Function1,
3178                            FunctionDecl *Function2) {
3179   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
3180     return ImplicitConversionSequence::Indistinguishable;
3181 
3182   // Objective-C++:
3183   //   If both conversion functions are implicitly-declared conversions from
3184   //   a lambda closure type to a function pointer and a block pointer,
3185   //   respectively, always prefer the conversion to a function pointer,
3186   //   because the function pointer is more lightweight and is more likely
3187   //   to keep code working.
3188   CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3189   if (!Conv1)
3190     return ImplicitConversionSequence::Indistinguishable;
3191 
3192   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3193   if (!Conv2)
3194     return ImplicitConversionSequence::Indistinguishable;
3195 
3196   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3197     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3198     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3199     if (Block1 != Block2)
3200       return Block1? ImplicitConversionSequence::Worse
3201                    : ImplicitConversionSequence::Better;
3202   }
3203 
3204   return ImplicitConversionSequence::Indistinguishable;
3205 }
3206 
3207 /// CompareImplicitConversionSequences - Compare two implicit
3208 /// conversion sequences to determine whether one is better than the
3209 /// other or if they are indistinguishable (C++ 13.3.3.2).
3210 static ImplicitConversionSequence::CompareKind
3211 CompareImplicitConversionSequences(Sema &S,
3212                                    const ImplicitConversionSequence& ICS1,
3213                                    const ImplicitConversionSequence& ICS2)
3214 {
3215   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3216   // conversion sequences (as defined in 13.3.3.1)
3217   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3218   //      conversion sequence than a user-defined conversion sequence or
3219   //      an ellipsis conversion sequence, and
3220   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3221   //      conversion sequence than an ellipsis conversion sequence
3222   //      (13.3.3.1.3).
3223   //
3224   // C++0x [over.best.ics]p10:
3225   //   For the purpose of ranking implicit conversion sequences as
3226   //   described in 13.3.3.2, the ambiguous conversion sequence is
3227   //   treated as a user-defined sequence that is indistinguishable
3228   //   from any other user-defined conversion sequence.
3229   if (ICS1.getKindRank() < ICS2.getKindRank())
3230     return ImplicitConversionSequence::Better;
3231   if (ICS2.getKindRank() < ICS1.getKindRank())
3232     return ImplicitConversionSequence::Worse;
3233 
3234   // The following checks require both conversion sequences to be of
3235   // the same kind.
3236   if (ICS1.getKind() != ICS2.getKind())
3237     return ImplicitConversionSequence::Indistinguishable;
3238 
3239   ImplicitConversionSequence::CompareKind Result =
3240       ImplicitConversionSequence::Indistinguishable;
3241 
3242   // Two implicit conversion sequences of the same form are
3243   // indistinguishable conversion sequences unless one of the
3244   // following rules apply: (C++ 13.3.3.2p3):
3245   if (ICS1.isStandard())
3246     Result = CompareStandardConversionSequences(S,
3247                                                 ICS1.Standard, ICS2.Standard);
3248   else if (ICS1.isUserDefined()) {
3249     // User-defined conversion sequence U1 is a better conversion
3250     // sequence than another user-defined conversion sequence U2 if
3251     // they contain the same user-defined conversion function or
3252     // constructor and if the second standard conversion sequence of
3253     // U1 is better than the second standard conversion sequence of
3254     // U2 (C++ 13.3.3.2p3).
3255     if (ICS1.UserDefined.ConversionFunction ==
3256           ICS2.UserDefined.ConversionFunction)
3257       Result = CompareStandardConversionSequences(S,
3258                                                   ICS1.UserDefined.After,
3259                                                   ICS2.UserDefined.After);
3260     else
3261       Result = compareConversionFunctions(S,
3262                                           ICS1.UserDefined.ConversionFunction,
3263                                           ICS2.UserDefined.ConversionFunction);
3264   }
3265 
3266   // List-initialization sequence L1 is a better conversion sequence than
3267   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3268   // for some X and L2 does not.
3269   if (Result == ImplicitConversionSequence::Indistinguishable &&
3270       !ICS1.isBad() &&
3271       ICS1.isListInitializationSequence() &&
3272       ICS2.isListInitializationSequence()) {
3273     if (ICS1.isStdInitializerListElement() &&
3274         !ICS2.isStdInitializerListElement())
3275       return ImplicitConversionSequence::Better;
3276     if (!ICS1.isStdInitializerListElement() &&
3277         ICS2.isStdInitializerListElement())
3278       return ImplicitConversionSequence::Worse;
3279   }
3280 
3281   return Result;
3282 }
3283 
3284 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3285   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3286     Qualifiers Quals;
3287     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3288     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3289   }
3290 
3291   return Context.hasSameUnqualifiedType(T1, T2);
3292 }
3293 
3294 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3295 // determine if one is a proper subset of the other.
3296 static ImplicitConversionSequence::CompareKind
3297 compareStandardConversionSubsets(ASTContext &Context,
3298                                  const StandardConversionSequence& SCS1,
3299                                  const StandardConversionSequence& SCS2) {
3300   ImplicitConversionSequence::CompareKind Result
3301     = ImplicitConversionSequence::Indistinguishable;
3302 
3303   // the identity conversion sequence is considered to be a subsequence of
3304   // any non-identity conversion sequence
3305   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3306     return ImplicitConversionSequence::Better;
3307   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3308     return ImplicitConversionSequence::Worse;
3309 
3310   if (SCS1.Second != SCS2.Second) {
3311     if (SCS1.Second == ICK_Identity)
3312       Result = ImplicitConversionSequence::Better;
3313     else if (SCS2.Second == ICK_Identity)
3314       Result = ImplicitConversionSequence::Worse;
3315     else
3316       return ImplicitConversionSequence::Indistinguishable;
3317   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3318     return ImplicitConversionSequence::Indistinguishable;
3319 
3320   if (SCS1.Third == SCS2.Third) {
3321     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3322                              : ImplicitConversionSequence::Indistinguishable;
3323   }
3324 
3325   if (SCS1.Third == ICK_Identity)
3326     return Result == ImplicitConversionSequence::Worse
3327              ? ImplicitConversionSequence::Indistinguishable
3328              : ImplicitConversionSequence::Better;
3329 
3330   if (SCS2.Third == ICK_Identity)
3331     return Result == ImplicitConversionSequence::Better
3332              ? ImplicitConversionSequence::Indistinguishable
3333              : ImplicitConversionSequence::Worse;
3334 
3335   return ImplicitConversionSequence::Indistinguishable;
3336 }
3337 
3338 /// \brief Determine whether one of the given reference bindings is better
3339 /// than the other based on what kind of bindings they are.
3340 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3341                                        const StandardConversionSequence &SCS2) {
3342   // C++0x [over.ics.rank]p3b4:
3343   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3344   //      implicit object parameter of a non-static member function declared
3345   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3346   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3347   //      lvalue reference to a function lvalue and S2 binds an rvalue
3348   //      reference*.
3349   //
3350   // FIXME: Rvalue references. We're going rogue with the above edits,
3351   // because the semantics in the current C++0x working paper (N3225 at the
3352   // time of this writing) break the standard definition of std::forward
3353   // and std::reference_wrapper when dealing with references to functions.
3354   // Proposed wording changes submitted to CWG for consideration.
3355   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3356       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3357     return false;
3358 
3359   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3360           SCS2.IsLvalueReference) ||
3361          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3362           !SCS2.IsLvalueReference);
3363 }
3364 
3365 /// CompareStandardConversionSequences - Compare two standard
3366 /// conversion sequences to determine whether one is better than the
3367 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3368 static ImplicitConversionSequence::CompareKind
3369 CompareStandardConversionSequences(Sema &S,
3370                                    const StandardConversionSequence& SCS1,
3371                                    const StandardConversionSequence& SCS2)
3372 {
3373   // Standard conversion sequence S1 is a better conversion sequence
3374   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3375 
3376   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3377   //     sequences in the canonical form defined by 13.3.3.1.1,
3378   //     excluding any Lvalue Transformation; the identity conversion
3379   //     sequence is considered to be a subsequence of any
3380   //     non-identity conversion sequence) or, if not that,
3381   if (ImplicitConversionSequence::CompareKind CK
3382         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3383     return CK;
3384 
3385   //  -- the rank of S1 is better than the rank of S2 (by the rules
3386   //     defined below), or, if not that,
3387   ImplicitConversionRank Rank1 = SCS1.getRank();
3388   ImplicitConversionRank Rank2 = SCS2.getRank();
3389   if (Rank1 < Rank2)
3390     return ImplicitConversionSequence::Better;
3391   else if (Rank2 < Rank1)
3392     return ImplicitConversionSequence::Worse;
3393 
3394   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3395   // are indistinguishable unless one of the following rules
3396   // applies:
3397 
3398   //   A conversion that is not a conversion of a pointer, or
3399   //   pointer to member, to bool is better than another conversion
3400   //   that is such a conversion.
3401   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3402     return SCS2.isPointerConversionToBool()
3403              ? ImplicitConversionSequence::Better
3404              : ImplicitConversionSequence::Worse;
3405 
3406   // C++ [over.ics.rank]p4b2:
3407   //
3408   //   If class B is derived directly or indirectly from class A,
3409   //   conversion of B* to A* is better than conversion of B* to
3410   //   void*, and conversion of A* to void* is better than conversion
3411   //   of B* to void*.
3412   bool SCS1ConvertsToVoid
3413     = SCS1.isPointerConversionToVoidPointer(S.Context);
3414   bool SCS2ConvertsToVoid
3415     = SCS2.isPointerConversionToVoidPointer(S.Context);
3416   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3417     // Exactly one of the conversion sequences is a conversion to
3418     // a void pointer; it's the worse conversion.
3419     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3420                               : ImplicitConversionSequence::Worse;
3421   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3422     // Neither conversion sequence converts to a void pointer; compare
3423     // their derived-to-base conversions.
3424     if (ImplicitConversionSequence::CompareKind DerivedCK
3425           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3426       return DerivedCK;
3427   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3428              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3429     // Both conversion sequences are conversions to void
3430     // pointers. Compare the source types to determine if there's an
3431     // inheritance relationship in their sources.
3432     QualType FromType1 = SCS1.getFromType();
3433     QualType FromType2 = SCS2.getFromType();
3434 
3435     // Adjust the types we're converting from via the array-to-pointer
3436     // conversion, if we need to.
3437     if (SCS1.First == ICK_Array_To_Pointer)
3438       FromType1 = S.Context.getArrayDecayedType(FromType1);
3439     if (SCS2.First == ICK_Array_To_Pointer)
3440       FromType2 = S.Context.getArrayDecayedType(FromType2);
3441 
3442     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3443     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3444 
3445     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3446       return ImplicitConversionSequence::Better;
3447     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3448       return ImplicitConversionSequence::Worse;
3449 
3450     // Objective-C++: If one interface is more specific than the
3451     // other, it is the better one.
3452     const ObjCObjectPointerType* FromObjCPtr1
3453       = FromType1->getAs<ObjCObjectPointerType>();
3454     const ObjCObjectPointerType* FromObjCPtr2
3455       = FromType2->getAs<ObjCObjectPointerType>();
3456     if (FromObjCPtr1 && FromObjCPtr2) {
3457       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3458                                                           FromObjCPtr2);
3459       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3460                                                            FromObjCPtr1);
3461       if (AssignLeft != AssignRight) {
3462         return AssignLeft? ImplicitConversionSequence::Better
3463                          : ImplicitConversionSequence::Worse;
3464       }
3465     }
3466   }
3467 
3468   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3469   // bullet 3).
3470   if (ImplicitConversionSequence::CompareKind QualCK
3471         = CompareQualificationConversions(S, SCS1, SCS2))
3472     return QualCK;
3473 
3474   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3475     // Check for a better reference binding based on the kind of bindings.
3476     if (isBetterReferenceBindingKind(SCS1, SCS2))
3477       return ImplicitConversionSequence::Better;
3478     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3479       return ImplicitConversionSequence::Worse;
3480 
3481     // C++ [over.ics.rank]p3b4:
3482     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3483     //      which the references refer are the same type except for
3484     //      top-level cv-qualifiers, and the type to which the reference
3485     //      initialized by S2 refers is more cv-qualified than the type
3486     //      to which the reference initialized by S1 refers.
3487     QualType T1 = SCS1.getToType(2);
3488     QualType T2 = SCS2.getToType(2);
3489     T1 = S.Context.getCanonicalType(T1);
3490     T2 = S.Context.getCanonicalType(T2);
3491     Qualifiers T1Quals, T2Quals;
3492     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3493     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3494     if (UnqualT1 == UnqualT2) {
3495       // Objective-C++ ARC: If the references refer to objects with different
3496       // lifetimes, prefer bindings that don't change lifetime.
3497       if (SCS1.ObjCLifetimeConversionBinding !=
3498                                           SCS2.ObjCLifetimeConversionBinding) {
3499         return SCS1.ObjCLifetimeConversionBinding
3500                                            ? ImplicitConversionSequence::Worse
3501                                            : ImplicitConversionSequence::Better;
3502       }
3503 
3504       // If the type is an array type, promote the element qualifiers to the
3505       // type for comparison.
3506       if (isa<ArrayType>(T1) && T1Quals)
3507         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3508       if (isa<ArrayType>(T2) && T2Quals)
3509         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3510       if (T2.isMoreQualifiedThan(T1))
3511         return ImplicitConversionSequence::Better;
3512       else if (T1.isMoreQualifiedThan(T2))
3513         return ImplicitConversionSequence::Worse;
3514     }
3515   }
3516 
3517   // In Microsoft mode, prefer an integral conversion to a
3518   // floating-to-integral conversion if the integral conversion
3519   // is between types of the same size.
3520   // For example:
3521   // void f(float);
3522   // void f(int);
3523   // int main {
3524   //    long a;
3525   //    f(a);
3526   // }
3527   // Here, MSVC will call f(int) instead of generating a compile error
3528   // as clang will do in standard mode.
3529   if (S.getLangOpts().MicrosoftMode &&
3530       SCS1.Second == ICK_Integral_Conversion &&
3531       SCS2.Second == ICK_Floating_Integral &&
3532       S.Context.getTypeSize(SCS1.getFromType()) ==
3533       S.Context.getTypeSize(SCS1.getToType(2)))
3534     return ImplicitConversionSequence::Better;
3535 
3536   return ImplicitConversionSequence::Indistinguishable;
3537 }
3538 
3539 /// CompareQualificationConversions - Compares two standard conversion
3540 /// sequences to determine whether they can be ranked based on their
3541 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3542 ImplicitConversionSequence::CompareKind
3543 CompareQualificationConversions(Sema &S,
3544                                 const StandardConversionSequence& SCS1,
3545                                 const StandardConversionSequence& SCS2) {
3546   // C++ 13.3.3.2p3:
3547   //  -- S1 and S2 differ only in their qualification conversion and
3548   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3549   //     cv-qualification signature of type T1 is a proper subset of
3550   //     the cv-qualification signature of type T2, and S1 is not the
3551   //     deprecated string literal array-to-pointer conversion (4.2).
3552   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3553       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3554     return ImplicitConversionSequence::Indistinguishable;
3555 
3556   // FIXME: the example in the standard doesn't use a qualification
3557   // conversion (!)
3558   QualType T1 = SCS1.getToType(2);
3559   QualType T2 = SCS2.getToType(2);
3560   T1 = S.Context.getCanonicalType(T1);
3561   T2 = S.Context.getCanonicalType(T2);
3562   Qualifiers T1Quals, T2Quals;
3563   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3564   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3565 
3566   // If the types are the same, we won't learn anything by unwrapped
3567   // them.
3568   if (UnqualT1 == UnqualT2)
3569     return ImplicitConversionSequence::Indistinguishable;
3570 
3571   // If the type is an array type, promote the element qualifiers to the type
3572   // for comparison.
3573   if (isa<ArrayType>(T1) && T1Quals)
3574     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3575   if (isa<ArrayType>(T2) && T2Quals)
3576     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3577 
3578   ImplicitConversionSequence::CompareKind Result
3579     = ImplicitConversionSequence::Indistinguishable;
3580 
3581   // Objective-C++ ARC:
3582   //   Prefer qualification conversions not involving a change in lifetime
3583   //   to qualification conversions that do not change lifetime.
3584   if (SCS1.QualificationIncludesObjCLifetime !=
3585                                       SCS2.QualificationIncludesObjCLifetime) {
3586     Result = SCS1.QualificationIncludesObjCLifetime
3587                ? ImplicitConversionSequence::Worse
3588                : ImplicitConversionSequence::Better;
3589   }
3590 
3591   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3592     // Within each iteration of the loop, we check the qualifiers to
3593     // determine if this still looks like a qualification
3594     // conversion. Then, if all is well, we unwrap one more level of
3595     // pointers or pointers-to-members and do it all again
3596     // until there are no more pointers or pointers-to-members left
3597     // to unwrap. This essentially mimics what
3598     // IsQualificationConversion does, but here we're checking for a
3599     // strict subset of qualifiers.
3600     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3601       // The qualifiers are the same, so this doesn't tell us anything
3602       // about how the sequences rank.
3603       ;
3604     else if (T2.isMoreQualifiedThan(T1)) {
3605       // T1 has fewer qualifiers, so it could be the better sequence.
3606       if (Result == ImplicitConversionSequence::Worse)
3607         // Neither has qualifiers that are a subset of the other's
3608         // qualifiers.
3609         return ImplicitConversionSequence::Indistinguishable;
3610 
3611       Result = ImplicitConversionSequence::Better;
3612     } else if (T1.isMoreQualifiedThan(T2)) {
3613       // T2 has fewer qualifiers, so it could be the better sequence.
3614       if (Result == ImplicitConversionSequence::Better)
3615         // Neither has qualifiers that are a subset of the other's
3616         // qualifiers.
3617         return ImplicitConversionSequence::Indistinguishable;
3618 
3619       Result = ImplicitConversionSequence::Worse;
3620     } else {
3621       // Qualifiers are disjoint.
3622       return ImplicitConversionSequence::Indistinguishable;
3623     }
3624 
3625     // If the types after this point are equivalent, we're done.
3626     if (S.Context.hasSameUnqualifiedType(T1, T2))
3627       break;
3628   }
3629 
3630   // Check that the winning standard conversion sequence isn't using
3631   // the deprecated string literal array to pointer conversion.
3632   switch (Result) {
3633   case ImplicitConversionSequence::Better:
3634     if (SCS1.DeprecatedStringLiteralToCharPtr)
3635       Result = ImplicitConversionSequence::Indistinguishable;
3636     break;
3637 
3638   case ImplicitConversionSequence::Indistinguishable:
3639     break;
3640 
3641   case ImplicitConversionSequence::Worse:
3642     if (SCS2.DeprecatedStringLiteralToCharPtr)
3643       Result = ImplicitConversionSequence::Indistinguishable;
3644     break;
3645   }
3646 
3647   return Result;
3648 }
3649 
3650 /// CompareDerivedToBaseConversions - Compares two standard conversion
3651 /// sequences to determine whether they can be ranked based on their
3652 /// various kinds of derived-to-base conversions (C++
3653 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3654 /// conversions between Objective-C interface types.
3655 ImplicitConversionSequence::CompareKind
3656 CompareDerivedToBaseConversions(Sema &S,
3657                                 const StandardConversionSequence& SCS1,
3658                                 const StandardConversionSequence& SCS2) {
3659   QualType FromType1 = SCS1.getFromType();
3660   QualType ToType1 = SCS1.getToType(1);
3661   QualType FromType2 = SCS2.getFromType();
3662   QualType ToType2 = SCS2.getToType(1);
3663 
3664   // Adjust the types we're converting from via the array-to-pointer
3665   // conversion, if we need to.
3666   if (SCS1.First == ICK_Array_To_Pointer)
3667     FromType1 = S.Context.getArrayDecayedType(FromType1);
3668   if (SCS2.First == ICK_Array_To_Pointer)
3669     FromType2 = S.Context.getArrayDecayedType(FromType2);
3670 
3671   // Canonicalize all of the types.
3672   FromType1 = S.Context.getCanonicalType(FromType1);
3673   ToType1 = S.Context.getCanonicalType(ToType1);
3674   FromType2 = S.Context.getCanonicalType(FromType2);
3675   ToType2 = S.Context.getCanonicalType(ToType2);
3676 
3677   // C++ [over.ics.rank]p4b3:
3678   //
3679   //   If class B is derived directly or indirectly from class A and
3680   //   class C is derived directly or indirectly from B,
3681   //
3682   // Compare based on pointer conversions.
3683   if (SCS1.Second == ICK_Pointer_Conversion &&
3684       SCS2.Second == ICK_Pointer_Conversion &&
3685       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3686       FromType1->isPointerType() && FromType2->isPointerType() &&
3687       ToType1->isPointerType() && ToType2->isPointerType()) {
3688     QualType FromPointee1
3689       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3690     QualType ToPointee1
3691       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3692     QualType FromPointee2
3693       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3694     QualType ToPointee2
3695       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3696 
3697     //   -- conversion of C* to B* is better than conversion of C* to A*,
3698     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3699       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3700         return ImplicitConversionSequence::Better;
3701       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3702         return ImplicitConversionSequence::Worse;
3703     }
3704 
3705     //   -- conversion of B* to A* is better than conversion of C* to A*,
3706     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3707       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3708         return ImplicitConversionSequence::Better;
3709       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3710         return ImplicitConversionSequence::Worse;
3711     }
3712   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3713              SCS2.Second == ICK_Pointer_Conversion) {
3714     const ObjCObjectPointerType *FromPtr1
3715       = FromType1->getAs<ObjCObjectPointerType>();
3716     const ObjCObjectPointerType *FromPtr2
3717       = FromType2->getAs<ObjCObjectPointerType>();
3718     const ObjCObjectPointerType *ToPtr1
3719       = ToType1->getAs<ObjCObjectPointerType>();
3720     const ObjCObjectPointerType *ToPtr2
3721       = ToType2->getAs<ObjCObjectPointerType>();
3722 
3723     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3724       // Apply the same conversion ranking rules for Objective-C pointer types
3725       // that we do for C++ pointers to class types. However, we employ the
3726       // Objective-C pseudo-subtyping relationship used for assignment of
3727       // Objective-C pointer types.
3728       bool FromAssignLeft
3729         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3730       bool FromAssignRight
3731         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3732       bool ToAssignLeft
3733         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3734       bool ToAssignRight
3735         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3736 
3737       // A conversion to an a non-id object pointer type or qualified 'id'
3738       // type is better than a conversion to 'id'.
3739       if (ToPtr1->isObjCIdType() &&
3740           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3741         return ImplicitConversionSequence::Worse;
3742       if (ToPtr2->isObjCIdType() &&
3743           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3744         return ImplicitConversionSequence::Better;
3745 
3746       // A conversion to a non-id object pointer type is better than a
3747       // conversion to a qualified 'id' type
3748       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3749         return ImplicitConversionSequence::Worse;
3750       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3751         return ImplicitConversionSequence::Better;
3752 
3753       // A conversion to an a non-Class object pointer type or qualified 'Class'
3754       // type is better than a conversion to 'Class'.
3755       if (ToPtr1->isObjCClassType() &&
3756           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3757         return ImplicitConversionSequence::Worse;
3758       if (ToPtr2->isObjCClassType() &&
3759           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3760         return ImplicitConversionSequence::Better;
3761 
3762       // A conversion to a non-Class object pointer type is better than a
3763       // conversion to a qualified 'Class' type.
3764       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3765         return ImplicitConversionSequence::Worse;
3766       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3767         return ImplicitConversionSequence::Better;
3768 
3769       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3770       if (S.Context.hasSameType(FromType1, FromType2) &&
3771           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3772           (ToAssignLeft != ToAssignRight))
3773         return ToAssignLeft? ImplicitConversionSequence::Worse
3774                            : ImplicitConversionSequence::Better;
3775 
3776       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3777       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3778           (FromAssignLeft != FromAssignRight))
3779         return FromAssignLeft? ImplicitConversionSequence::Better
3780         : ImplicitConversionSequence::Worse;
3781     }
3782   }
3783 
3784   // Ranking of member-pointer types.
3785   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3786       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3787       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3788     const MemberPointerType * FromMemPointer1 =
3789                                         FromType1->getAs<MemberPointerType>();
3790     const MemberPointerType * ToMemPointer1 =
3791                                           ToType1->getAs<MemberPointerType>();
3792     const MemberPointerType * FromMemPointer2 =
3793                                           FromType2->getAs<MemberPointerType>();
3794     const MemberPointerType * ToMemPointer2 =
3795                                           ToType2->getAs<MemberPointerType>();
3796     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3797     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3798     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3799     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3800     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3801     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3802     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3803     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3804     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3805     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3806       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3807         return ImplicitConversionSequence::Worse;
3808       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3809         return ImplicitConversionSequence::Better;
3810     }
3811     // conversion of B::* to C::* is better than conversion of A::* to C::*
3812     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3813       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3814         return ImplicitConversionSequence::Better;
3815       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3816         return ImplicitConversionSequence::Worse;
3817     }
3818   }
3819 
3820   if (SCS1.Second == ICK_Derived_To_Base) {
3821     //   -- conversion of C to B is better than conversion of C to A,
3822     //   -- binding of an expression of type C to a reference of type
3823     //      B& is better than binding an expression of type C to a
3824     //      reference of type A&,
3825     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3826         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3827       if (S.IsDerivedFrom(ToType1, ToType2))
3828         return ImplicitConversionSequence::Better;
3829       else if (S.IsDerivedFrom(ToType2, ToType1))
3830         return ImplicitConversionSequence::Worse;
3831     }
3832 
3833     //   -- conversion of B to A is better than conversion of C to A.
3834     //   -- binding of an expression of type B to a reference of type
3835     //      A& is better than binding an expression of type C to a
3836     //      reference of type A&,
3837     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3838         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3839       if (S.IsDerivedFrom(FromType2, FromType1))
3840         return ImplicitConversionSequence::Better;
3841       else if (S.IsDerivedFrom(FromType1, FromType2))
3842         return ImplicitConversionSequence::Worse;
3843     }
3844   }
3845 
3846   return ImplicitConversionSequence::Indistinguishable;
3847 }
3848 
3849 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3850 /// determine whether they are reference-related,
3851 /// reference-compatible, reference-compatible with added
3852 /// qualification, or incompatible, for use in C++ initialization by
3853 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3854 /// type, and the first type (T1) is the pointee type of the reference
3855 /// type being initialized.
3856 Sema::ReferenceCompareResult
3857 Sema::CompareReferenceRelationship(SourceLocation Loc,
3858                                    QualType OrigT1, QualType OrigT2,
3859                                    bool &DerivedToBase,
3860                                    bool &ObjCConversion,
3861                                    bool &ObjCLifetimeConversion) {
3862   assert(!OrigT1->isReferenceType() &&
3863     "T1 must be the pointee type of the reference type");
3864   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3865 
3866   QualType T1 = Context.getCanonicalType(OrigT1);
3867   QualType T2 = Context.getCanonicalType(OrigT2);
3868   Qualifiers T1Quals, T2Quals;
3869   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3870   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3871 
3872   // C++ [dcl.init.ref]p4:
3873   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3874   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3875   //   T1 is a base class of T2.
3876   DerivedToBase = false;
3877   ObjCConversion = false;
3878   ObjCLifetimeConversion = false;
3879   if (UnqualT1 == UnqualT2) {
3880     // Nothing to do.
3881   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3882            IsDerivedFrom(UnqualT2, UnqualT1))
3883     DerivedToBase = true;
3884   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3885            UnqualT2->isObjCObjectOrInterfaceType() &&
3886            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3887     ObjCConversion = true;
3888   else
3889     return Ref_Incompatible;
3890 
3891   // At this point, we know that T1 and T2 are reference-related (at
3892   // least).
3893 
3894   // If the type is an array type, promote the element qualifiers to the type
3895   // for comparison.
3896   if (isa<ArrayType>(T1) && T1Quals)
3897     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3898   if (isa<ArrayType>(T2) && T2Quals)
3899     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3900 
3901   // C++ [dcl.init.ref]p4:
3902   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3903   //   reference-related to T2 and cv1 is the same cv-qualification
3904   //   as, or greater cv-qualification than, cv2. For purposes of
3905   //   overload resolution, cases for which cv1 is greater
3906   //   cv-qualification than cv2 are identified as
3907   //   reference-compatible with added qualification (see 13.3.3.2).
3908   //
3909   // Note that we also require equivalence of Objective-C GC and address-space
3910   // qualifiers when performing these computations, so that e.g., an int in
3911   // address space 1 is not reference-compatible with an int in address
3912   // space 2.
3913   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3914       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3915     T1Quals.removeObjCLifetime();
3916     T2Quals.removeObjCLifetime();
3917     ObjCLifetimeConversion = true;
3918   }
3919 
3920   if (T1Quals == T2Quals)
3921     return Ref_Compatible;
3922   else if (T1Quals.compatiblyIncludes(T2Quals))
3923     return Ref_Compatible_With_Added_Qualification;
3924   else
3925     return Ref_Related;
3926 }
3927 
3928 /// \brief Look for a user-defined conversion to an value reference-compatible
3929 ///        with DeclType. Return true if something definite is found.
3930 static bool
3931 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3932                          QualType DeclType, SourceLocation DeclLoc,
3933                          Expr *Init, QualType T2, bool AllowRvalues,
3934                          bool AllowExplicit) {
3935   assert(T2->isRecordType() && "Can only find conversions of record types.");
3936   CXXRecordDecl *T2RecordDecl
3937     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3938 
3939   OverloadCandidateSet CandidateSet(DeclLoc);
3940   const UnresolvedSetImpl *Conversions
3941     = T2RecordDecl->getVisibleConversionFunctions();
3942   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3943          E = Conversions->end(); I != E; ++I) {
3944     NamedDecl *D = *I;
3945     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3946     if (isa<UsingShadowDecl>(D))
3947       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3948 
3949     FunctionTemplateDecl *ConvTemplate
3950       = dyn_cast<FunctionTemplateDecl>(D);
3951     CXXConversionDecl *Conv;
3952     if (ConvTemplate)
3953       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3954     else
3955       Conv = cast<CXXConversionDecl>(D);
3956 
3957     // If this is an explicit conversion, and we're not allowed to consider
3958     // explicit conversions, skip it.
3959     if (!AllowExplicit && Conv->isExplicit())
3960       continue;
3961 
3962     if (AllowRvalues) {
3963       bool DerivedToBase = false;
3964       bool ObjCConversion = false;
3965       bool ObjCLifetimeConversion = false;
3966 
3967       // If we are initializing an rvalue reference, don't permit conversion
3968       // functions that return lvalues.
3969       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3970         const ReferenceType *RefType
3971           = Conv->getConversionType()->getAs<LValueReferenceType>();
3972         if (RefType && !RefType->getPointeeType()->isFunctionType())
3973           continue;
3974       }
3975 
3976       if (!ConvTemplate &&
3977           S.CompareReferenceRelationship(
3978             DeclLoc,
3979             Conv->getConversionType().getNonReferenceType()
3980               .getUnqualifiedType(),
3981             DeclType.getNonReferenceType().getUnqualifiedType(),
3982             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
3983           Sema::Ref_Incompatible)
3984         continue;
3985     } else {
3986       // If the conversion function doesn't return a reference type,
3987       // it can't be considered for this conversion. An rvalue reference
3988       // is only acceptable if its referencee is a function type.
3989 
3990       const ReferenceType *RefType =
3991         Conv->getConversionType()->getAs<ReferenceType>();
3992       if (!RefType ||
3993           (!RefType->isLValueReferenceType() &&
3994            !RefType->getPointeeType()->isFunctionType()))
3995         continue;
3996     }
3997 
3998     if (ConvTemplate)
3999       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4000                                        Init, DeclType, CandidateSet);
4001     else
4002       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4003                                DeclType, CandidateSet);
4004   }
4005 
4006   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4007 
4008   OverloadCandidateSet::iterator Best;
4009   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4010   case OR_Success:
4011     // C++ [over.ics.ref]p1:
4012     //
4013     //   [...] If the parameter binds directly to the result of
4014     //   applying a conversion function to the argument
4015     //   expression, the implicit conversion sequence is a
4016     //   user-defined conversion sequence (13.3.3.1.2), with the
4017     //   second standard conversion sequence either an identity
4018     //   conversion or, if the conversion function returns an
4019     //   entity of a type that is a derived class of the parameter
4020     //   type, a derived-to-base Conversion.
4021     if (!Best->FinalConversion.DirectBinding)
4022       return false;
4023 
4024     if (Best->Function)
4025       S.MarkFunctionReferenced(DeclLoc, Best->Function);
4026     ICS.setUserDefined();
4027     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4028     ICS.UserDefined.After = Best->FinalConversion;
4029     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4030     ICS.UserDefined.ConversionFunction = Best->Function;
4031     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4032     ICS.UserDefined.EllipsisConversion = false;
4033     assert(ICS.UserDefined.After.ReferenceBinding &&
4034            ICS.UserDefined.After.DirectBinding &&
4035            "Expected a direct reference binding!");
4036     return true;
4037 
4038   case OR_Ambiguous:
4039     ICS.setAmbiguous();
4040     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4041          Cand != CandidateSet.end(); ++Cand)
4042       if (Cand->Viable)
4043         ICS.Ambiguous.addConversion(Cand->Function);
4044     return true;
4045 
4046   case OR_No_Viable_Function:
4047   case OR_Deleted:
4048     // There was no suitable conversion, or we found a deleted
4049     // conversion; continue with other checks.
4050     return false;
4051   }
4052 
4053   llvm_unreachable("Invalid OverloadResult!");
4054 }
4055 
4056 /// \brief Compute an implicit conversion sequence for reference
4057 /// initialization.
4058 static ImplicitConversionSequence
4059 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4060                  SourceLocation DeclLoc,
4061                  bool SuppressUserConversions,
4062                  bool AllowExplicit) {
4063   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4064 
4065   // Most paths end in a failed conversion.
4066   ImplicitConversionSequence ICS;
4067   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4068 
4069   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4070   QualType T2 = Init->getType();
4071 
4072   // If the initializer is the address of an overloaded function, try
4073   // to resolve the overloaded function. If all goes well, T2 is the
4074   // type of the resulting function.
4075   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4076     DeclAccessPair Found;
4077     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4078                                                                 false, Found))
4079       T2 = Fn->getType();
4080   }
4081 
4082   // Compute some basic properties of the types and the initializer.
4083   bool isRValRef = DeclType->isRValueReferenceType();
4084   bool DerivedToBase = false;
4085   bool ObjCConversion = false;
4086   bool ObjCLifetimeConversion = false;
4087   Expr::Classification InitCategory = Init->Classify(S.Context);
4088   Sema::ReferenceCompareResult RefRelationship
4089     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4090                                      ObjCConversion, ObjCLifetimeConversion);
4091 
4092 
4093   // C++0x [dcl.init.ref]p5:
4094   //   A reference to type "cv1 T1" is initialized by an expression
4095   //   of type "cv2 T2" as follows:
4096 
4097   //     -- If reference is an lvalue reference and the initializer expression
4098   if (!isRValRef) {
4099     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4100     //        reference-compatible with "cv2 T2," or
4101     //
4102     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4103     if (InitCategory.isLValue() &&
4104         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4105       // C++ [over.ics.ref]p1:
4106       //   When a parameter of reference type binds directly (8.5.3)
4107       //   to an argument expression, the implicit conversion sequence
4108       //   is the identity conversion, unless the argument expression
4109       //   has a type that is a derived class of the parameter type,
4110       //   in which case the implicit conversion sequence is a
4111       //   derived-to-base Conversion (13.3.3.1).
4112       ICS.setStandard();
4113       ICS.Standard.First = ICK_Identity;
4114       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4115                          : ObjCConversion? ICK_Compatible_Conversion
4116                          : ICK_Identity;
4117       ICS.Standard.Third = ICK_Identity;
4118       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4119       ICS.Standard.setToType(0, T2);
4120       ICS.Standard.setToType(1, T1);
4121       ICS.Standard.setToType(2, T1);
4122       ICS.Standard.ReferenceBinding = true;
4123       ICS.Standard.DirectBinding = true;
4124       ICS.Standard.IsLvalueReference = !isRValRef;
4125       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4126       ICS.Standard.BindsToRvalue = false;
4127       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4128       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4129       ICS.Standard.CopyConstructor = 0;
4130 
4131       // Nothing more to do: the inaccessibility/ambiguity check for
4132       // derived-to-base conversions is suppressed when we're
4133       // computing the implicit conversion sequence (C++
4134       // [over.best.ics]p2).
4135       return ICS;
4136     }
4137 
4138     //       -- has a class type (i.e., T2 is a class type), where T1 is
4139     //          not reference-related to T2, and can be implicitly
4140     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4141     //          is reference-compatible with "cv3 T3" 92) (this
4142     //          conversion is selected by enumerating the applicable
4143     //          conversion functions (13.3.1.6) and choosing the best
4144     //          one through overload resolution (13.3)),
4145     if (!SuppressUserConversions && T2->isRecordType() &&
4146         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4147         RefRelationship == Sema::Ref_Incompatible) {
4148       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4149                                    Init, T2, /*AllowRvalues=*/false,
4150                                    AllowExplicit))
4151         return ICS;
4152     }
4153   }
4154 
4155   //     -- Otherwise, the reference shall be an lvalue reference to a
4156   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4157   //        shall be an rvalue reference.
4158   //
4159   // We actually handle one oddity of C++ [over.ics.ref] at this
4160   // point, which is that, due to p2 (which short-circuits reference
4161   // binding by only attempting a simple conversion for non-direct
4162   // bindings) and p3's strange wording, we allow a const volatile
4163   // reference to bind to an rvalue. Hence the check for the presence
4164   // of "const" rather than checking for "const" being the only
4165   // qualifier.
4166   // This is also the point where rvalue references and lvalue inits no longer
4167   // go together.
4168   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4169     return ICS;
4170 
4171   //       -- If the initializer expression
4172   //
4173   //            -- is an xvalue, class prvalue, array prvalue or function
4174   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4175   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4176       (InitCategory.isXValue() ||
4177       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4178       (InitCategory.isLValue() && T2->isFunctionType()))) {
4179     ICS.setStandard();
4180     ICS.Standard.First = ICK_Identity;
4181     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4182                       : ObjCConversion? ICK_Compatible_Conversion
4183                       : ICK_Identity;
4184     ICS.Standard.Third = ICK_Identity;
4185     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4186     ICS.Standard.setToType(0, T2);
4187     ICS.Standard.setToType(1, T1);
4188     ICS.Standard.setToType(2, T1);
4189     ICS.Standard.ReferenceBinding = true;
4190     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4191     // binding unless we're binding to a class prvalue.
4192     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4193     // allow the use of rvalue references in C++98/03 for the benefit of
4194     // standard library implementors; therefore, we need the xvalue check here.
4195     ICS.Standard.DirectBinding =
4196       S.getLangOpts().CPlusPlus0x ||
4197       (InitCategory.isPRValue() && !T2->isRecordType());
4198     ICS.Standard.IsLvalueReference = !isRValRef;
4199     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4200     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4201     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4202     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4203     ICS.Standard.CopyConstructor = 0;
4204     return ICS;
4205   }
4206 
4207   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4208   //               reference-related to T2, and can be implicitly converted to
4209   //               an xvalue, class prvalue, or function lvalue of type
4210   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4211   //               "cv3 T3",
4212   //
4213   //          then the reference is bound to the value of the initializer
4214   //          expression in the first case and to the result of the conversion
4215   //          in the second case (or, in either case, to an appropriate base
4216   //          class subobject).
4217   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4218       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4219       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4220                                Init, T2, /*AllowRvalues=*/true,
4221                                AllowExplicit)) {
4222     // In the second case, if the reference is an rvalue reference
4223     // and the second standard conversion sequence of the
4224     // user-defined conversion sequence includes an lvalue-to-rvalue
4225     // conversion, the program is ill-formed.
4226     if (ICS.isUserDefined() && isRValRef &&
4227         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4228       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4229 
4230     return ICS;
4231   }
4232 
4233   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4234   //          initialized from the initializer expression using the
4235   //          rules for a non-reference copy initialization (8.5). The
4236   //          reference is then bound to the temporary. If T1 is
4237   //          reference-related to T2, cv1 must be the same
4238   //          cv-qualification as, or greater cv-qualification than,
4239   //          cv2; otherwise, the program is ill-formed.
4240   if (RefRelationship == Sema::Ref_Related) {
4241     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4242     // we would be reference-compatible or reference-compatible with
4243     // added qualification. But that wasn't the case, so the reference
4244     // initialization fails.
4245     //
4246     // Note that we only want to check address spaces and cvr-qualifiers here.
4247     // ObjC GC and lifetime qualifiers aren't important.
4248     Qualifiers T1Quals = T1.getQualifiers();
4249     Qualifiers T2Quals = T2.getQualifiers();
4250     T1Quals.removeObjCGCAttr();
4251     T1Quals.removeObjCLifetime();
4252     T2Quals.removeObjCGCAttr();
4253     T2Quals.removeObjCLifetime();
4254     if (!T1Quals.compatiblyIncludes(T2Quals))
4255       return ICS;
4256   }
4257 
4258   // If at least one of the types is a class type, the types are not
4259   // related, and we aren't allowed any user conversions, the
4260   // reference binding fails. This case is important for breaking
4261   // recursion, since TryImplicitConversion below will attempt to
4262   // create a temporary through the use of a copy constructor.
4263   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4264       (T1->isRecordType() || T2->isRecordType()))
4265     return ICS;
4266 
4267   // If T1 is reference-related to T2 and the reference is an rvalue
4268   // reference, the initializer expression shall not be an lvalue.
4269   if (RefRelationship >= Sema::Ref_Related &&
4270       isRValRef && Init->Classify(S.Context).isLValue())
4271     return ICS;
4272 
4273   // C++ [over.ics.ref]p2:
4274   //   When a parameter of reference type is not bound directly to
4275   //   an argument expression, the conversion sequence is the one
4276   //   required to convert the argument expression to the
4277   //   underlying type of the reference according to
4278   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4279   //   to copy-initializing a temporary of the underlying type with
4280   //   the argument expression. Any difference in top-level
4281   //   cv-qualification is subsumed by the initialization itself
4282   //   and does not constitute a conversion.
4283   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4284                               /*AllowExplicit=*/false,
4285                               /*InOverloadResolution=*/false,
4286                               /*CStyle=*/false,
4287                               /*AllowObjCWritebackConversion=*/false);
4288 
4289   // Of course, that's still a reference binding.
4290   if (ICS.isStandard()) {
4291     ICS.Standard.ReferenceBinding = true;
4292     ICS.Standard.IsLvalueReference = !isRValRef;
4293     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4294     ICS.Standard.BindsToRvalue = true;
4295     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4296     ICS.Standard.ObjCLifetimeConversionBinding = false;
4297   } else if (ICS.isUserDefined()) {
4298     // Don't allow rvalue references to bind to lvalues.
4299     if (DeclType->isRValueReferenceType()) {
4300       if (const ReferenceType *RefType
4301             = ICS.UserDefined.ConversionFunction->getResultType()
4302                 ->getAs<LValueReferenceType>()) {
4303         if (!RefType->getPointeeType()->isFunctionType()) {
4304           ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4305                      DeclType);
4306           return ICS;
4307         }
4308       }
4309     }
4310 
4311     ICS.UserDefined.After.ReferenceBinding = true;
4312     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4313     ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4314     ICS.UserDefined.After.BindsToRvalue = true;
4315     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4316     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4317   }
4318 
4319   return ICS;
4320 }
4321 
4322 static ImplicitConversionSequence
4323 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4324                       bool SuppressUserConversions,
4325                       bool InOverloadResolution,
4326                       bool AllowObjCWritebackConversion,
4327                       bool AllowExplicit = false);
4328 
4329 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4330 /// initializer list From.
4331 static ImplicitConversionSequence
4332 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4333                   bool SuppressUserConversions,
4334                   bool InOverloadResolution,
4335                   bool AllowObjCWritebackConversion) {
4336   // C++11 [over.ics.list]p1:
4337   //   When an argument is an initializer list, it is not an expression and
4338   //   special rules apply for converting it to a parameter type.
4339 
4340   ImplicitConversionSequence Result;
4341   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4342   Result.setListInitializationSequence();
4343 
4344   // We need a complete type for what follows. Incomplete types can never be
4345   // initialized from init lists.
4346   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4347     return Result;
4348 
4349   // C++11 [over.ics.list]p2:
4350   //   If the parameter type is std::initializer_list<X> or "array of X" and
4351   //   all the elements can be implicitly converted to X, the implicit
4352   //   conversion sequence is the worst conversion necessary to convert an
4353   //   element of the list to X.
4354   bool toStdInitializerList = false;
4355   QualType X;
4356   if (ToType->isArrayType())
4357     X = S.Context.getBaseElementType(ToType);
4358   else
4359     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4360   if (!X.isNull()) {
4361     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4362       Expr *Init = From->getInit(i);
4363       ImplicitConversionSequence ICS =
4364           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4365                                 InOverloadResolution,
4366                                 AllowObjCWritebackConversion);
4367       // If a single element isn't convertible, fail.
4368       if (ICS.isBad()) {
4369         Result = ICS;
4370         break;
4371       }
4372       // Otherwise, look for the worst conversion.
4373       if (Result.isBad() ||
4374           CompareImplicitConversionSequences(S, ICS, Result) ==
4375               ImplicitConversionSequence::Worse)
4376         Result = ICS;
4377     }
4378 
4379     // For an empty list, we won't have computed any conversion sequence.
4380     // Introduce the identity conversion sequence.
4381     if (From->getNumInits() == 0) {
4382       Result.setStandard();
4383       Result.Standard.setAsIdentityConversion();
4384       Result.Standard.setFromType(ToType);
4385       Result.Standard.setAllToTypes(ToType);
4386     }
4387 
4388     Result.setListInitializationSequence();
4389     Result.setStdInitializerListElement(toStdInitializerList);
4390     return Result;
4391   }
4392 
4393   // C++11 [over.ics.list]p3:
4394   //   Otherwise, if the parameter is a non-aggregate class X and overload
4395   //   resolution chooses a single best constructor [...] the implicit
4396   //   conversion sequence is a user-defined conversion sequence. If multiple
4397   //   constructors are viable but none is better than the others, the
4398   //   implicit conversion sequence is a user-defined conversion sequence.
4399   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4400     // This function can deal with initializer lists.
4401     Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4402                                       /*AllowExplicit=*/false,
4403                                       InOverloadResolution, /*CStyle=*/false,
4404                                       AllowObjCWritebackConversion);
4405     Result.setListInitializationSequence();
4406     return Result;
4407   }
4408 
4409   // C++11 [over.ics.list]p4:
4410   //   Otherwise, if the parameter has an aggregate type which can be
4411   //   initialized from the initializer list [...] the implicit conversion
4412   //   sequence is a user-defined conversion sequence.
4413   if (ToType->isAggregateType()) {
4414     // Type is an aggregate, argument is an init list. At this point it comes
4415     // down to checking whether the initialization works.
4416     // FIXME: Find out whether this parameter is consumed or not.
4417     InitializedEntity Entity =
4418         InitializedEntity::InitializeParameter(S.Context, ToType,
4419                                                /*Consumed=*/false);
4420     if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4421       Result.setUserDefined();
4422       Result.UserDefined.Before.setAsIdentityConversion();
4423       // Initializer lists don't have a type.
4424       Result.UserDefined.Before.setFromType(QualType());
4425       Result.UserDefined.Before.setAllToTypes(QualType());
4426 
4427       Result.UserDefined.After.setAsIdentityConversion();
4428       Result.UserDefined.After.setFromType(ToType);
4429       Result.UserDefined.After.setAllToTypes(ToType);
4430       Result.UserDefined.ConversionFunction = 0;
4431     }
4432     return Result;
4433   }
4434 
4435   // C++11 [over.ics.list]p5:
4436   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4437   if (ToType->isReferenceType()) {
4438     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4439     // mention initializer lists in any way. So we go by what list-
4440     // initialization would do and try to extrapolate from that.
4441 
4442     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4443 
4444     // If the initializer list has a single element that is reference-related
4445     // to the parameter type, we initialize the reference from that.
4446     if (From->getNumInits() == 1) {
4447       Expr *Init = From->getInit(0);
4448 
4449       QualType T2 = Init->getType();
4450 
4451       // If the initializer is the address of an overloaded function, try
4452       // to resolve the overloaded function. If all goes well, T2 is the
4453       // type of the resulting function.
4454       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4455         DeclAccessPair Found;
4456         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4457                                    Init, ToType, false, Found))
4458           T2 = Fn->getType();
4459       }
4460 
4461       // Compute some basic properties of the types and the initializer.
4462       bool dummy1 = false;
4463       bool dummy2 = false;
4464       bool dummy3 = false;
4465       Sema::ReferenceCompareResult RefRelationship
4466         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4467                                          dummy2, dummy3);
4468 
4469       if (RefRelationship >= Sema::Ref_Related)
4470         return TryReferenceInit(S, Init, ToType,
4471                                 /*FIXME:*/From->getLocStart(),
4472                                 SuppressUserConversions,
4473                                 /*AllowExplicit=*/false);
4474     }
4475 
4476     // Otherwise, we bind the reference to a temporary created from the
4477     // initializer list.
4478     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4479                                InOverloadResolution,
4480                                AllowObjCWritebackConversion);
4481     if (Result.isFailure())
4482       return Result;
4483     assert(!Result.isEllipsis() &&
4484            "Sub-initialization cannot result in ellipsis conversion.");
4485 
4486     // Can we even bind to a temporary?
4487     if (ToType->isRValueReferenceType() ||
4488         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4489       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4490                                             Result.UserDefined.After;
4491       SCS.ReferenceBinding = true;
4492       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4493       SCS.BindsToRvalue = true;
4494       SCS.BindsToFunctionLvalue = false;
4495       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4496       SCS.ObjCLifetimeConversionBinding = false;
4497     } else
4498       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4499                     From, ToType);
4500     return Result;
4501   }
4502 
4503   // C++11 [over.ics.list]p6:
4504   //   Otherwise, if the parameter type is not a class:
4505   if (!ToType->isRecordType()) {
4506     //    - if the initializer list has one element, the implicit conversion
4507     //      sequence is the one required to convert the element to the
4508     //      parameter type.
4509     unsigned NumInits = From->getNumInits();
4510     if (NumInits == 1)
4511       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4512                                      SuppressUserConversions,
4513                                      InOverloadResolution,
4514                                      AllowObjCWritebackConversion);
4515     //    - if the initializer list has no elements, the implicit conversion
4516     //      sequence is the identity conversion.
4517     else if (NumInits == 0) {
4518       Result.setStandard();
4519       Result.Standard.setAsIdentityConversion();
4520       Result.Standard.setFromType(ToType);
4521       Result.Standard.setAllToTypes(ToType);
4522     }
4523     Result.setListInitializationSequence();
4524     return Result;
4525   }
4526 
4527   // C++11 [over.ics.list]p7:
4528   //   In all cases other than those enumerated above, no conversion is possible
4529   return Result;
4530 }
4531 
4532 /// TryCopyInitialization - Try to copy-initialize a value of type
4533 /// ToType from the expression From. Return the implicit conversion
4534 /// sequence required to pass this argument, which may be a bad
4535 /// conversion sequence (meaning that the argument cannot be passed to
4536 /// a parameter of this type). If @p SuppressUserConversions, then we
4537 /// do not permit any user-defined conversion sequences.
4538 static ImplicitConversionSequence
4539 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4540                       bool SuppressUserConversions,
4541                       bool InOverloadResolution,
4542                       bool AllowObjCWritebackConversion,
4543                       bool AllowExplicit) {
4544   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4545     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4546                              InOverloadResolution,AllowObjCWritebackConversion);
4547 
4548   if (ToType->isReferenceType())
4549     return TryReferenceInit(S, From, ToType,
4550                             /*FIXME:*/From->getLocStart(),
4551                             SuppressUserConversions,
4552                             AllowExplicit);
4553 
4554   return TryImplicitConversion(S, From, ToType,
4555                                SuppressUserConversions,
4556                                /*AllowExplicit=*/false,
4557                                InOverloadResolution,
4558                                /*CStyle=*/false,
4559                                AllowObjCWritebackConversion);
4560 }
4561 
4562 static bool TryCopyInitialization(const CanQualType FromQTy,
4563                                   const CanQualType ToQTy,
4564                                   Sema &S,
4565                                   SourceLocation Loc,
4566                                   ExprValueKind FromVK) {
4567   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4568   ImplicitConversionSequence ICS =
4569     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4570 
4571   return !ICS.isBad();
4572 }
4573 
4574 /// TryObjectArgumentInitialization - Try to initialize the object
4575 /// parameter of the given member function (@c Method) from the
4576 /// expression @p From.
4577 static ImplicitConversionSequence
4578 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
4579                                 Expr::Classification FromClassification,
4580                                 CXXMethodDecl *Method,
4581                                 CXXRecordDecl *ActingContext) {
4582   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4583   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4584   //                 const volatile object.
4585   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4586     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4587   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4588 
4589   // Set up the conversion sequence as a "bad" conversion, to allow us
4590   // to exit early.
4591   ImplicitConversionSequence ICS;
4592 
4593   // We need to have an object of class type.
4594   QualType FromType = OrigFromType;
4595   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4596     FromType = PT->getPointeeType();
4597 
4598     // When we had a pointer, it's implicitly dereferenced, so we
4599     // better have an lvalue.
4600     assert(FromClassification.isLValue());
4601   }
4602 
4603   assert(FromType->isRecordType());
4604 
4605   // C++0x [over.match.funcs]p4:
4606   //   For non-static member functions, the type of the implicit object
4607   //   parameter is
4608   //
4609   //     - "lvalue reference to cv X" for functions declared without a
4610   //        ref-qualifier or with the & ref-qualifier
4611   //     - "rvalue reference to cv X" for functions declared with the &&
4612   //        ref-qualifier
4613   //
4614   // where X is the class of which the function is a member and cv is the
4615   // cv-qualification on the member function declaration.
4616   //
4617   // However, when finding an implicit conversion sequence for the argument, we
4618   // are not allowed to create temporaries or perform user-defined conversions
4619   // (C++ [over.match.funcs]p5). We perform a simplified version of
4620   // reference binding here, that allows class rvalues to bind to
4621   // non-constant references.
4622 
4623   // First check the qualifiers.
4624   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4625   if (ImplicitParamType.getCVRQualifiers()
4626                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4627       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4628     ICS.setBad(BadConversionSequence::bad_qualifiers,
4629                OrigFromType, ImplicitParamType);
4630     return ICS;
4631   }
4632 
4633   // Check that we have either the same type or a derived type. It
4634   // affects the conversion rank.
4635   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4636   ImplicitConversionKind SecondKind;
4637   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4638     SecondKind = ICK_Identity;
4639   } else if (S.IsDerivedFrom(FromType, ClassType))
4640     SecondKind = ICK_Derived_To_Base;
4641   else {
4642     ICS.setBad(BadConversionSequence::unrelated_class,
4643                FromType, ImplicitParamType);
4644     return ICS;
4645   }
4646 
4647   // Check the ref-qualifier.
4648   switch (Method->getRefQualifier()) {
4649   case RQ_None:
4650     // Do nothing; we don't care about lvalueness or rvalueness.
4651     break;
4652 
4653   case RQ_LValue:
4654     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4655       // non-const lvalue reference cannot bind to an rvalue
4656       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4657                  ImplicitParamType);
4658       return ICS;
4659     }
4660     break;
4661 
4662   case RQ_RValue:
4663     if (!FromClassification.isRValue()) {
4664       // rvalue reference cannot bind to an lvalue
4665       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4666                  ImplicitParamType);
4667       return ICS;
4668     }
4669     break;
4670   }
4671 
4672   // Success. Mark this as a reference binding.
4673   ICS.setStandard();
4674   ICS.Standard.setAsIdentityConversion();
4675   ICS.Standard.Second = SecondKind;
4676   ICS.Standard.setFromType(FromType);
4677   ICS.Standard.setAllToTypes(ImplicitParamType);
4678   ICS.Standard.ReferenceBinding = true;
4679   ICS.Standard.DirectBinding = true;
4680   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4681   ICS.Standard.BindsToFunctionLvalue = false;
4682   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4683   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4684     = (Method->getRefQualifier() == RQ_None);
4685   return ICS;
4686 }
4687 
4688 /// PerformObjectArgumentInitialization - Perform initialization of
4689 /// the implicit object parameter for the given Method with the given
4690 /// expression.
4691 ExprResult
4692 Sema::PerformObjectArgumentInitialization(Expr *From,
4693                                           NestedNameSpecifier *Qualifier,
4694                                           NamedDecl *FoundDecl,
4695                                           CXXMethodDecl *Method) {
4696   QualType FromRecordType, DestType;
4697   QualType ImplicitParamRecordType  =
4698     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4699 
4700   Expr::Classification FromClassification;
4701   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4702     FromRecordType = PT->getPointeeType();
4703     DestType = Method->getThisType(Context);
4704     FromClassification = Expr::Classification::makeSimpleLValue();
4705   } else {
4706     FromRecordType = From->getType();
4707     DestType = ImplicitParamRecordType;
4708     FromClassification = From->Classify(Context);
4709   }
4710 
4711   // Note that we always use the true parent context when performing
4712   // the actual argument initialization.
4713   ImplicitConversionSequence ICS
4714     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4715                                       Method, Method->getParent());
4716   if (ICS.isBad()) {
4717     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4718       Qualifiers FromQs = FromRecordType.getQualifiers();
4719       Qualifiers ToQs = DestType.getQualifiers();
4720       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4721       if (CVR) {
4722         Diag(From->getLocStart(),
4723              diag::err_member_function_call_bad_cvr)
4724           << Method->getDeclName() << FromRecordType << (CVR - 1)
4725           << From->getSourceRange();
4726         Diag(Method->getLocation(), diag::note_previous_decl)
4727           << Method->getDeclName();
4728         return ExprError();
4729       }
4730     }
4731 
4732     return Diag(From->getLocStart(),
4733                 diag::err_implicit_object_parameter_init)
4734        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4735   }
4736 
4737   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4738     ExprResult FromRes =
4739       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4740     if (FromRes.isInvalid())
4741       return ExprError();
4742     From = FromRes.take();
4743   }
4744 
4745   if (!Context.hasSameType(From->getType(), DestType))
4746     From = ImpCastExprToType(From, DestType, CK_NoOp,
4747                              From->getValueKind()).take();
4748   return Owned(From);
4749 }
4750 
4751 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4752 /// expression From to bool (C++0x [conv]p3).
4753 static ImplicitConversionSequence
4754 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4755   // FIXME: This is pretty broken.
4756   return TryImplicitConversion(S, From, S.Context.BoolTy,
4757                                // FIXME: Are these flags correct?
4758                                /*SuppressUserConversions=*/false,
4759                                /*AllowExplicit=*/true,
4760                                /*InOverloadResolution=*/false,
4761                                /*CStyle=*/false,
4762                                /*AllowObjCWritebackConversion=*/false);
4763 }
4764 
4765 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4766 /// of the expression From to bool (C++0x [conv]p3).
4767 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4768   if (checkPlaceholderForOverload(*this, From))
4769     return ExprError();
4770 
4771   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4772   if (!ICS.isBad())
4773     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4774 
4775   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4776     return Diag(From->getLocStart(),
4777                 diag::err_typecheck_bool_condition)
4778                   << From->getType() << From->getSourceRange();
4779   return ExprError();
4780 }
4781 
4782 /// Check that the specified conversion is permitted in a converted constant
4783 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4784 /// is acceptable.
4785 static bool CheckConvertedConstantConversions(Sema &S,
4786                                               StandardConversionSequence &SCS) {
4787   // Since we know that the target type is an integral or unscoped enumeration
4788   // type, most conversion kinds are impossible. All possible First and Third
4789   // conversions are fine.
4790   switch (SCS.Second) {
4791   case ICK_Identity:
4792   case ICK_Integral_Promotion:
4793   case ICK_Integral_Conversion:
4794     return true;
4795 
4796   case ICK_Boolean_Conversion:
4797     // Conversion from an integral or unscoped enumeration type to bool is
4798     // classified as ICK_Boolean_Conversion, but it's also an integral
4799     // conversion, so it's permitted in a converted constant expression.
4800     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4801            SCS.getToType(2)->isBooleanType();
4802 
4803   case ICK_Floating_Integral:
4804   case ICK_Complex_Real:
4805     return false;
4806 
4807   case ICK_Lvalue_To_Rvalue:
4808   case ICK_Array_To_Pointer:
4809   case ICK_Function_To_Pointer:
4810   case ICK_NoReturn_Adjustment:
4811   case ICK_Qualification:
4812   case ICK_Compatible_Conversion:
4813   case ICK_Vector_Conversion:
4814   case ICK_Vector_Splat:
4815   case ICK_Derived_To_Base:
4816   case ICK_Pointer_Conversion:
4817   case ICK_Pointer_Member:
4818   case ICK_Block_Pointer_Conversion:
4819   case ICK_Writeback_Conversion:
4820   case ICK_Floating_Promotion:
4821   case ICK_Complex_Promotion:
4822   case ICK_Complex_Conversion:
4823   case ICK_Floating_Conversion:
4824   case ICK_TransparentUnionConversion:
4825     llvm_unreachable("unexpected second conversion kind");
4826 
4827   case ICK_Num_Conversion_Kinds:
4828     break;
4829   }
4830 
4831   llvm_unreachable("unknown conversion kind");
4832 }
4833 
4834 /// CheckConvertedConstantExpression - Check that the expression From is a
4835 /// converted constant expression of type T, perform the conversion and produce
4836 /// the converted expression, per C++11 [expr.const]p3.
4837 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4838                                                   llvm::APSInt &Value,
4839                                                   CCEKind CCE) {
4840   assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4841   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4842 
4843   if (checkPlaceholderForOverload(*this, From))
4844     return ExprError();
4845 
4846   // C++11 [expr.const]p3 with proposed wording fixes:
4847   //  A converted constant expression of type T is a core constant expression,
4848   //  implicitly converted to a prvalue of type T, where the converted
4849   //  expression is a literal constant expression and the implicit conversion
4850   //  sequence contains only user-defined conversions, lvalue-to-rvalue
4851   //  conversions, integral promotions, and integral conversions other than
4852   //  narrowing conversions.
4853   ImplicitConversionSequence ICS =
4854     TryImplicitConversion(From, T,
4855                           /*SuppressUserConversions=*/false,
4856                           /*AllowExplicit=*/false,
4857                           /*InOverloadResolution=*/false,
4858                           /*CStyle=*/false,
4859                           /*AllowObjcWritebackConversion=*/false);
4860   StandardConversionSequence *SCS = 0;
4861   switch (ICS.getKind()) {
4862   case ImplicitConversionSequence::StandardConversion:
4863     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4864       return Diag(From->getLocStart(),
4865                   diag::err_typecheck_converted_constant_expression_disallowed)
4866                << From->getType() << From->getSourceRange() << T;
4867     SCS = &ICS.Standard;
4868     break;
4869   case ImplicitConversionSequence::UserDefinedConversion:
4870     // We are converting from class type to an integral or enumeration type, so
4871     // the Before sequence must be trivial.
4872     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4873       return Diag(From->getLocStart(),
4874                   diag::err_typecheck_converted_constant_expression_disallowed)
4875                << From->getType() << From->getSourceRange() << T;
4876     SCS = &ICS.UserDefined.After;
4877     break;
4878   case ImplicitConversionSequence::AmbiguousConversion:
4879   case ImplicitConversionSequence::BadConversion:
4880     if (!DiagnoseMultipleUserDefinedConversion(From, T))
4881       return Diag(From->getLocStart(),
4882                   diag::err_typecheck_converted_constant_expression)
4883                     << From->getType() << From->getSourceRange() << T;
4884     return ExprError();
4885 
4886   case ImplicitConversionSequence::EllipsisConversion:
4887     llvm_unreachable("ellipsis conversion in converted constant expression");
4888   }
4889 
4890   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4891   if (Result.isInvalid())
4892     return Result;
4893 
4894   // Check for a narrowing implicit conversion.
4895   APValue PreNarrowingValue;
4896   QualType PreNarrowingType;
4897   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4898                                 PreNarrowingType)) {
4899   case NK_Variable_Narrowing:
4900     // Implicit conversion to a narrower type, and the value is not a constant
4901     // expression. We'll diagnose this in a moment.
4902   case NK_Not_Narrowing:
4903     break;
4904 
4905   case NK_Constant_Narrowing:
4906     Diag(From->getLocStart(),
4907          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4908                              diag::err_cce_narrowing)
4909       << CCE << /*Constant*/1
4910       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4911     break;
4912 
4913   case NK_Type_Narrowing:
4914     Diag(From->getLocStart(),
4915          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4916                              diag::err_cce_narrowing)
4917       << CCE << /*Constant*/0 << From->getType() << T;
4918     break;
4919   }
4920 
4921   // Check the expression is a constant expression.
4922   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4923   Expr::EvalResult Eval;
4924   Eval.Diag = &Notes;
4925 
4926   if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4927     // The expression can't be folded, so we can't keep it at this position in
4928     // the AST.
4929     Result = ExprError();
4930   } else {
4931     Value = Eval.Val.getInt();
4932 
4933     if (Notes.empty()) {
4934       // It's a constant expression.
4935       return Result;
4936     }
4937   }
4938 
4939   // It's not a constant expression. Produce an appropriate diagnostic.
4940   if (Notes.size() == 1 &&
4941       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4942     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4943   else {
4944     Diag(From->getLocStart(), diag::err_expr_not_cce)
4945       << CCE << From->getSourceRange();
4946     for (unsigned I = 0; I < Notes.size(); ++I)
4947       Diag(Notes[I].first, Notes[I].second);
4948   }
4949   return Result;
4950 }
4951 
4952 /// dropPointerConversions - If the given standard conversion sequence
4953 /// involves any pointer conversions, remove them.  This may change
4954 /// the result type of the conversion sequence.
4955 static void dropPointerConversion(StandardConversionSequence &SCS) {
4956   if (SCS.Second == ICK_Pointer_Conversion) {
4957     SCS.Second = ICK_Identity;
4958     SCS.Third = ICK_Identity;
4959     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4960   }
4961 }
4962 
4963 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
4964 /// convert the expression From to an Objective-C pointer type.
4965 static ImplicitConversionSequence
4966 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4967   // Do an implicit conversion to 'id'.
4968   QualType Ty = S.Context.getObjCIdType();
4969   ImplicitConversionSequence ICS
4970     = TryImplicitConversion(S, From, Ty,
4971                             // FIXME: Are these flags correct?
4972                             /*SuppressUserConversions=*/false,
4973                             /*AllowExplicit=*/true,
4974                             /*InOverloadResolution=*/false,
4975                             /*CStyle=*/false,
4976                             /*AllowObjCWritebackConversion=*/false);
4977 
4978   // Strip off any final conversions to 'id'.
4979   switch (ICS.getKind()) {
4980   case ImplicitConversionSequence::BadConversion:
4981   case ImplicitConversionSequence::AmbiguousConversion:
4982   case ImplicitConversionSequence::EllipsisConversion:
4983     break;
4984 
4985   case ImplicitConversionSequence::UserDefinedConversion:
4986     dropPointerConversion(ICS.UserDefined.After);
4987     break;
4988 
4989   case ImplicitConversionSequence::StandardConversion:
4990     dropPointerConversion(ICS.Standard);
4991     break;
4992   }
4993 
4994   return ICS;
4995 }
4996 
4997 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
4998 /// conversion of the expression From to an Objective-C pointer type.
4999 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5000   if (checkPlaceholderForOverload(*this, From))
5001     return ExprError();
5002 
5003   QualType Ty = Context.getObjCIdType();
5004   ImplicitConversionSequence ICS =
5005     TryContextuallyConvertToObjCPointer(*this, From);
5006   if (!ICS.isBad())
5007     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5008   return ExprError();
5009 }
5010 
5011 /// Determine whether the provided type is an integral type, or an enumeration
5012 /// type of a permitted flavor.
5013 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5014   return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5015                          : T->isIntegralOrUnscopedEnumerationType();
5016 }
5017 
5018 /// \brief Attempt to convert the given expression to an integral or
5019 /// enumeration type.
5020 ///
5021 /// This routine will attempt to convert an expression of class type to an
5022 /// integral or enumeration type, if that class type only has a single
5023 /// conversion to an integral or enumeration type.
5024 ///
5025 /// \param Loc The source location of the construct that requires the
5026 /// conversion.
5027 ///
5028 /// \param From The expression we're converting from.
5029 ///
5030 /// \param Diagnoser Used to output any diagnostics.
5031 ///
5032 /// \param AllowScopedEnumerations Specifies whether conversions to scoped
5033 /// enumerations should be considered.
5034 ///
5035 /// \returns The expression, converted to an integral or enumeration type if
5036 /// successful.
5037 ExprResult
5038 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5039                                          ICEConvertDiagnoser &Diagnoser,
5040                                          bool AllowScopedEnumerations) {
5041   // We can't perform any more checking for type-dependent expressions.
5042   if (From->isTypeDependent())
5043     return Owned(From);
5044 
5045   // Process placeholders immediately.
5046   if (From->hasPlaceholderType()) {
5047     ExprResult result = CheckPlaceholderExpr(From);
5048     if (result.isInvalid()) return result;
5049     From = result.take();
5050   }
5051 
5052   // If the expression already has integral or enumeration type, we're golden.
5053   QualType T = From->getType();
5054   if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5055     return DefaultLvalueConversion(From);
5056 
5057   // FIXME: Check for missing '()' if T is a function type?
5058 
5059   // If we don't have a class type in C++, there's no way we can get an
5060   // expression of integral or enumeration type.
5061   const RecordType *RecordTy = T->getAs<RecordType>();
5062   if (!RecordTy || !getLangOpts().CPlusPlus) {
5063     if (!Diagnoser.Suppress)
5064       Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
5065     return Owned(From);
5066   }
5067 
5068   // We must have a complete class type.
5069   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5070     ICEConvertDiagnoser &Diagnoser;
5071     Expr *From;
5072 
5073     TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5074       : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
5075 
5076     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5077       Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5078     }
5079   } IncompleteDiagnoser(Diagnoser, From);
5080 
5081   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5082     return Owned(From);
5083 
5084   // Look for a conversion to an integral or enumeration type.
5085   UnresolvedSet<4> ViableConversions;
5086   UnresolvedSet<4> ExplicitConversions;
5087   const UnresolvedSetImpl *Conversions
5088     = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5089 
5090   bool HadMultipleCandidates = (Conversions->size() > 1);
5091 
5092   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5093                                    E = Conversions->end();
5094        I != E;
5095        ++I) {
5096     if (CXXConversionDecl *Conversion
5097           = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5098       if (isIntegralOrEnumerationType(
5099             Conversion->getConversionType().getNonReferenceType(),
5100             AllowScopedEnumerations)) {
5101         if (Conversion->isExplicit())
5102           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5103         else
5104           ViableConversions.addDecl(I.getDecl(), I.getAccess());
5105       }
5106     }
5107   }
5108 
5109   switch (ViableConversions.size()) {
5110   case 0:
5111     if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
5112       DeclAccessPair Found = ExplicitConversions[0];
5113       CXXConversionDecl *Conversion
5114         = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5115 
5116       // The user probably meant to invoke the given explicit
5117       // conversion; use it.
5118       QualType ConvTy
5119         = Conversion->getConversionType().getNonReferenceType();
5120       std::string TypeStr;
5121       ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5122 
5123       Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
5124         << FixItHint::CreateInsertion(From->getLocStart(),
5125                                       "static_cast<" + TypeStr + ">(")
5126         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5127                                       ")");
5128       Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
5129 
5130       // If we aren't in a SFINAE context, build a call to the
5131       // explicit conversion function.
5132       if (isSFINAEContext())
5133         return ExprError();
5134 
5135       CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5136       ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5137                                                  HadMultipleCandidates);
5138       if (Result.isInvalid())
5139         return ExprError();
5140       // Record usage of conversion in an implicit cast.
5141       From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5142                                       CK_UserDefinedConversion,
5143                                       Result.get(), 0,
5144                                       Result.get()->getValueKind());
5145     }
5146 
5147     // We'll complain below about a non-integral condition type.
5148     break;
5149 
5150   case 1: {
5151     // Apply this conversion.
5152     DeclAccessPair Found = ViableConversions[0];
5153     CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5154 
5155     CXXConversionDecl *Conversion
5156       = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5157     QualType ConvTy
5158       = Conversion->getConversionType().getNonReferenceType();
5159     if (!Diagnoser.SuppressConversion) {
5160       if (isSFINAEContext())
5161         return ExprError();
5162 
5163       Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5164         << From->getSourceRange();
5165     }
5166 
5167     ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5168                                                HadMultipleCandidates);
5169     if (Result.isInvalid())
5170       return ExprError();
5171     // Record usage of conversion in an implicit cast.
5172     From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5173                                     CK_UserDefinedConversion,
5174                                     Result.get(), 0,
5175                                     Result.get()->getValueKind());
5176     break;
5177   }
5178 
5179   default:
5180     if (Diagnoser.Suppress)
5181       return ExprError();
5182 
5183     Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
5184     for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5185       CXXConversionDecl *Conv
5186         = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5187       QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5188       Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
5189     }
5190     return Owned(From);
5191   }
5192 
5193   if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5194       !Diagnoser.Suppress) {
5195     Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5196       << From->getSourceRange();
5197   }
5198 
5199   return DefaultLvalueConversion(From);
5200 }
5201 
5202 /// AddOverloadCandidate - Adds the given function to the set of
5203 /// candidate functions, using the given function call arguments.  If
5204 /// @p SuppressUserConversions, then don't allow user-defined
5205 /// conversions via constructors or conversion operators.
5206 ///
5207 /// \param PartialOverloading true if we are performing "partial" overloading
5208 /// based on an incomplete set of function arguments. This feature is used by
5209 /// code completion.
5210 void
5211 Sema::AddOverloadCandidate(FunctionDecl *Function,
5212                            DeclAccessPair FoundDecl,
5213                            llvm::ArrayRef<Expr *> Args,
5214                            OverloadCandidateSet& CandidateSet,
5215                            bool SuppressUserConversions,
5216                            bool PartialOverloading,
5217                            bool AllowExplicit) {
5218   const FunctionProtoType* Proto
5219     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5220   assert(Proto && "Functions without a prototype cannot be overloaded");
5221   assert(!Function->getDescribedFunctionTemplate() &&
5222          "Use AddTemplateOverloadCandidate for function templates");
5223 
5224   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5225     if (!isa<CXXConstructorDecl>(Method)) {
5226       // If we get here, it's because we're calling a member function
5227       // that is named without a member access expression (e.g.,
5228       // "this->f") that was either written explicitly or created
5229       // implicitly. This can happen with a qualified call to a member
5230       // function, e.g., X::f(). We use an empty type for the implied
5231       // object argument (C++ [over.call.func]p3), and the acting context
5232       // is irrelevant.
5233       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5234                          QualType(), Expr::Classification::makeSimpleLValue(),
5235                          Args, CandidateSet, SuppressUserConversions);
5236       return;
5237     }
5238     // We treat a constructor like a non-member function, since its object
5239     // argument doesn't participate in overload resolution.
5240   }
5241 
5242   if (!CandidateSet.isNewCandidate(Function))
5243     return;
5244 
5245   // Overload resolution is always an unevaluated context.
5246   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5247 
5248   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5249     // C++ [class.copy]p3:
5250     //   A member function template is never instantiated to perform the copy
5251     //   of a class object to an object of its class type.
5252     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5253     if (Args.size() == 1 &&
5254         Constructor->isSpecializationCopyingObject() &&
5255         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5256          IsDerivedFrom(Args[0]->getType(), ClassType)))
5257       return;
5258   }
5259 
5260   // Add this candidate
5261   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5262   Candidate.FoundDecl = FoundDecl;
5263   Candidate.Function = Function;
5264   Candidate.Viable = true;
5265   Candidate.IsSurrogate = false;
5266   Candidate.IgnoreObjectArgument = false;
5267   Candidate.ExplicitCallArguments = Args.size();
5268 
5269   unsigned NumArgsInProto = Proto->getNumArgs();
5270 
5271   // (C++ 13.3.2p2): A candidate function having fewer than m
5272   // parameters is viable only if it has an ellipsis in its parameter
5273   // list (8.3.5).
5274   if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5275       !Proto->isVariadic()) {
5276     Candidate.Viable = false;
5277     Candidate.FailureKind = ovl_fail_too_many_arguments;
5278     return;
5279   }
5280 
5281   // (C++ 13.3.2p2): A candidate function having more than m parameters
5282   // is viable only if the (m+1)st parameter has a default argument
5283   // (8.3.6). For the purposes of overload resolution, the
5284   // parameter list is truncated on the right, so that there are
5285   // exactly m parameters.
5286   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5287   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5288     // Not enough arguments.
5289     Candidate.Viable = false;
5290     Candidate.FailureKind = ovl_fail_too_few_arguments;
5291     return;
5292   }
5293 
5294   // (CUDA B.1): Check for invalid calls between targets.
5295   if (getLangOpts().CUDA)
5296     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5297       if (CheckCUDATarget(Caller, Function)) {
5298         Candidate.Viable = false;
5299         Candidate.FailureKind = ovl_fail_bad_target;
5300         return;
5301       }
5302 
5303   // Determine the implicit conversion sequences for each of the
5304   // arguments.
5305   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5306     if (ArgIdx < NumArgsInProto) {
5307       // (C++ 13.3.2p3): for F to be a viable function, there shall
5308       // exist for each argument an implicit conversion sequence
5309       // (13.3.3.1) that converts that argument to the corresponding
5310       // parameter of F.
5311       QualType ParamType = Proto->getArgType(ArgIdx);
5312       Candidate.Conversions[ArgIdx]
5313         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5314                                 SuppressUserConversions,
5315                                 /*InOverloadResolution=*/true,
5316                                 /*AllowObjCWritebackConversion=*/
5317                                   getLangOpts().ObjCAutoRefCount,
5318                                 AllowExplicit);
5319       if (Candidate.Conversions[ArgIdx].isBad()) {
5320         Candidate.Viable = false;
5321         Candidate.FailureKind = ovl_fail_bad_conversion;
5322         break;
5323       }
5324     } else {
5325       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5326       // argument for which there is no corresponding parameter is
5327       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5328       Candidate.Conversions[ArgIdx].setEllipsis();
5329     }
5330   }
5331 }
5332 
5333 /// \brief Add all of the function declarations in the given function set to
5334 /// the overload canddiate set.
5335 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5336                                  llvm::ArrayRef<Expr *> Args,
5337                                  OverloadCandidateSet& CandidateSet,
5338                                  bool SuppressUserConversions,
5339                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
5340   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5341     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5342     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5343       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5344         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5345                            cast<CXXMethodDecl>(FD)->getParent(),
5346                            Args[0]->getType(), Args[0]->Classify(Context),
5347                            Args.slice(1), CandidateSet,
5348                            SuppressUserConversions);
5349       else
5350         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5351                              SuppressUserConversions);
5352     } else {
5353       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5354       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5355           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5356         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5357                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5358                                    ExplicitTemplateArgs,
5359                                    Args[0]->getType(),
5360                                    Args[0]->Classify(Context), Args.slice(1),
5361                                    CandidateSet, SuppressUserConversions);
5362       else
5363         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5364                                      ExplicitTemplateArgs, Args,
5365                                      CandidateSet, SuppressUserConversions);
5366     }
5367   }
5368 }
5369 
5370 /// AddMethodCandidate - Adds a named decl (which is some kind of
5371 /// method) as a method candidate to the given overload set.
5372 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5373                               QualType ObjectType,
5374                               Expr::Classification ObjectClassification,
5375                               Expr **Args, unsigned NumArgs,
5376                               OverloadCandidateSet& CandidateSet,
5377                               bool SuppressUserConversions) {
5378   NamedDecl *Decl = FoundDecl.getDecl();
5379   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5380 
5381   if (isa<UsingShadowDecl>(Decl))
5382     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5383 
5384   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5385     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5386            "Expected a member function template");
5387     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5388                                /*ExplicitArgs*/ 0,
5389                                ObjectType, ObjectClassification,
5390                                llvm::makeArrayRef(Args, NumArgs), CandidateSet,
5391                                SuppressUserConversions);
5392   } else {
5393     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5394                        ObjectType, ObjectClassification,
5395                        llvm::makeArrayRef(Args, NumArgs),
5396                        CandidateSet, SuppressUserConversions);
5397   }
5398 }
5399 
5400 /// AddMethodCandidate - Adds the given C++ member function to the set
5401 /// of candidate functions, using the given function call arguments
5402 /// and the object argument (@c Object). For example, in a call
5403 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5404 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5405 /// allow user-defined conversions via constructors or conversion
5406 /// operators.
5407 void
5408 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5409                          CXXRecordDecl *ActingContext, QualType ObjectType,
5410                          Expr::Classification ObjectClassification,
5411                          llvm::ArrayRef<Expr *> Args,
5412                          OverloadCandidateSet& CandidateSet,
5413                          bool SuppressUserConversions) {
5414   const FunctionProtoType* Proto
5415     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5416   assert(Proto && "Methods without a prototype cannot be overloaded");
5417   assert(!isa<CXXConstructorDecl>(Method) &&
5418          "Use AddOverloadCandidate for constructors");
5419 
5420   if (!CandidateSet.isNewCandidate(Method))
5421     return;
5422 
5423   // Overload resolution is always an unevaluated context.
5424   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5425 
5426   // Add this candidate
5427   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5428   Candidate.FoundDecl = FoundDecl;
5429   Candidate.Function = Method;
5430   Candidate.IsSurrogate = false;
5431   Candidate.IgnoreObjectArgument = false;
5432   Candidate.ExplicitCallArguments = Args.size();
5433 
5434   unsigned NumArgsInProto = Proto->getNumArgs();
5435 
5436   // (C++ 13.3.2p2): A candidate function having fewer than m
5437   // parameters is viable only if it has an ellipsis in its parameter
5438   // list (8.3.5).
5439   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5440     Candidate.Viable = false;
5441     Candidate.FailureKind = ovl_fail_too_many_arguments;
5442     return;
5443   }
5444 
5445   // (C++ 13.3.2p2): A candidate function having more than m parameters
5446   // is viable only if the (m+1)st parameter has a default argument
5447   // (8.3.6). For the purposes of overload resolution, the
5448   // parameter list is truncated on the right, so that there are
5449   // exactly m parameters.
5450   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5451   if (Args.size() < MinRequiredArgs) {
5452     // Not enough arguments.
5453     Candidate.Viable = false;
5454     Candidate.FailureKind = ovl_fail_too_few_arguments;
5455     return;
5456   }
5457 
5458   Candidate.Viable = true;
5459 
5460   if (Method->isStatic() || ObjectType.isNull())
5461     // The implicit object argument is ignored.
5462     Candidate.IgnoreObjectArgument = true;
5463   else {
5464     // Determine the implicit conversion sequence for the object
5465     // parameter.
5466     Candidate.Conversions[0]
5467       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5468                                         Method, ActingContext);
5469     if (Candidate.Conversions[0].isBad()) {
5470       Candidate.Viable = false;
5471       Candidate.FailureKind = ovl_fail_bad_conversion;
5472       return;
5473     }
5474   }
5475 
5476   // Determine the implicit conversion sequences for each of the
5477   // arguments.
5478   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5479     if (ArgIdx < NumArgsInProto) {
5480       // (C++ 13.3.2p3): for F to be a viable function, there shall
5481       // exist for each argument an implicit conversion sequence
5482       // (13.3.3.1) that converts that argument to the corresponding
5483       // parameter of F.
5484       QualType ParamType = Proto->getArgType(ArgIdx);
5485       Candidate.Conversions[ArgIdx + 1]
5486         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5487                                 SuppressUserConversions,
5488                                 /*InOverloadResolution=*/true,
5489                                 /*AllowObjCWritebackConversion=*/
5490                                   getLangOpts().ObjCAutoRefCount);
5491       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5492         Candidate.Viable = false;
5493         Candidate.FailureKind = ovl_fail_bad_conversion;
5494         break;
5495       }
5496     } else {
5497       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5498       // argument for which there is no corresponding parameter is
5499       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5500       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5501     }
5502   }
5503 }
5504 
5505 /// \brief Add a C++ member function template as a candidate to the candidate
5506 /// set, using template argument deduction to produce an appropriate member
5507 /// function template specialization.
5508 void
5509 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5510                                  DeclAccessPair FoundDecl,
5511                                  CXXRecordDecl *ActingContext,
5512                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5513                                  QualType ObjectType,
5514                                  Expr::Classification ObjectClassification,
5515                                  llvm::ArrayRef<Expr *> Args,
5516                                  OverloadCandidateSet& CandidateSet,
5517                                  bool SuppressUserConversions) {
5518   if (!CandidateSet.isNewCandidate(MethodTmpl))
5519     return;
5520 
5521   // C++ [over.match.funcs]p7:
5522   //   In each case where a candidate is a function template, candidate
5523   //   function template specializations are generated using template argument
5524   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5525   //   candidate functions in the usual way.113) A given name can refer to one
5526   //   or more function templates and also to a set of overloaded non-template
5527   //   functions. In such a case, the candidate functions generated from each
5528   //   function template are combined with the set of non-template candidate
5529   //   functions.
5530   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5531   FunctionDecl *Specialization = 0;
5532   if (TemplateDeductionResult Result
5533       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5534                                 Specialization, Info)) {
5535     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5536     Candidate.FoundDecl = FoundDecl;
5537     Candidate.Function = MethodTmpl->getTemplatedDecl();
5538     Candidate.Viable = false;
5539     Candidate.FailureKind = ovl_fail_bad_deduction;
5540     Candidate.IsSurrogate = false;
5541     Candidate.IgnoreObjectArgument = false;
5542     Candidate.ExplicitCallArguments = Args.size();
5543     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5544                                                           Info);
5545     return;
5546   }
5547 
5548   // Add the function template specialization produced by template argument
5549   // deduction as a candidate.
5550   assert(Specialization && "Missing member function template specialization?");
5551   assert(isa<CXXMethodDecl>(Specialization) &&
5552          "Specialization is not a member function?");
5553   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5554                      ActingContext, ObjectType, ObjectClassification, Args,
5555                      CandidateSet, SuppressUserConversions);
5556 }
5557 
5558 /// \brief Add a C++ function template specialization as a candidate
5559 /// in the candidate set, using template argument deduction to produce
5560 /// an appropriate function template specialization.
5561 void
5562 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5563                                    DeclAccessPair FoundDecl,
5564                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5565                                    llvm::ArrayRef<Expr *> Args,
5566                                    OverloadCandidateSet& CandidateSet,
5567                                    bool SuppressUserConversions) {
5568   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5569     return;
5570 
5571   // C++ [over.match.funcs]p7:
5572   //   In each case where a candidate is a function template, candidate
5573   //   function template specializations are generated using template argument
5574   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5575   //   candidate functions in the usual way.113) A given name can refer to one
5576   //   or more function templates and also to a set of overloaded non-template
5577   //   functions. In such a case, the candidate functions generated from each
5578   //   function template are combined with the set of non-template candidate
5579   //   functions.
5580   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5581   FunctionDecl *Specialization = 0;
5582   if (TemplateDeductionResult Result
5583         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5584                                   Specialization, Info)) {
5585     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5586     Candidate.FoundDecl = FoundDecl;
5587     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5588     Candidate.Viable = false;
5589     Candidate.FailureKind = ovl_fail_bad_deduction;
5590     Candidate.IsSurrogate = false;
5591     Candidate.IgnoreObjectArgument = false;
5592     Candidate.ExplicitCallArguments = Args.size();
5593     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5594                                                           Info);
5595     return;
5596   }
5597 
5598   // Add the function template specialization produced by template argument
5599   // deduction as a candidate.
5600   assert(Specialization && "Missing function template specialization?");
5601   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5602                        SuppressUserConversions);
5603 }
5604 
5605 /// AddConversionCandidate - Add a C++ conversion function as a
5606 /// candidate in the candidate set (C++ [over.match.conv],
5607 /// C++ [over.match.copy]). From is the expression we're converting from,
5608 /// and ToType is the type that we're eventually trying to convert to
5609 /// (which may or may not be the same type as the type that the
5610 /// conversion function produces).
5611 void
5612 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5613                              DeclAccessPair FoundDecl,
5614                              CXXRecordDecl *ActingContext,
5615                              Expr *From, QualType ToType,
5616                              OverloadCandidateSet& CandidateSet) {
5617   assert(!Conversion->getDescribedFunctionTemplate() &&
5618          "Conversion function templates use AddTemplateConversionCandidate");
5619   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5620   if (!CandidateSet.isNewCandidate(Conversion))
5621     return;
5622 
5623   // Overload resolution is always an unevaluated context.
5624   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5625 
5626   // Add this candidate
5627   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5628   Candidate.FoundDecl = FoundDecl;
5629   Candidate.Function = Conversion;
5630   Candidate.IsSurrogate = false;
5631   Candidate.IgnoreObjectArgument = false;
5632   Candidate.FinalConversion.setAsIdentityConversion();
5633   Candidate.FinalConversion.setFromType(ConvType);
5634   Candidate.FinalConversion.setAllToTypes(ToType);
5635   Candidate.Viable = true;
5636   Candidate.ExplicitCallArguments = 1;
5637 
5638   // C++ [over.match.funcs]p4:
5639   //   For conversion functions, the function is considered to be a member of
5640   //   the class of the implicit implied object argument for the purpose of
5641   //   defining the type of the implicit object parameter.
5642   //
5643   // Determine the implicit conversion sequence for the implicit
5644   // object parameter.
5645   QualType ImplicitParamType = From->getType();
5646   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5647     ImplicitParamType = FromPtrType->getPointeeType();
5648   CXXRecordDecl *ConversionContext
5649     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5650 
5651   Candidate.Conversions[0]
5652     = TryObjectArgumentInitialization(*this, From->getType(),
5653                                       From->Classify(Context),
5654                                       Conversion, ConversionContext);
5655 
5656   if (Candidate.Conversions[0].isBad()) {
5657     Candidate.Viable = false;
5658     Candidate.FailureKind = ovl_fail_bad_conversion;
5659     return;
5660   }
5661 
5662   // We won't go through a user-define type conversion function to convert a
5663   // derived to base as such conversions are given Conversion Rank. They only
5664   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5665   QualType FromCanon
5666     = Context.getCanonicalType(From->getType().getUnqualifiedType());
5667   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5668   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5669     Candidate.Viable = false;
5670     Candidate.FailureKind = ovl_fail_trivial_conversion;
5671     return;
5672   }
5673 
5674   // To determine what the conversion from the result of calling the
5675   // conversion function to the type we're eventually trying to
5676   // convert to (ToType), we need to synthesize a call to the
5677   // conversion function and attempt copy initialization from it. This
5678   // makes sure that we get the right semantics with respect to
5679   // lvalues/rvalues and the type. Fortunately, we can allocate this
5680   // call on the stack and we don't need its arguments to be
5681   // well-formed.
5682   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5683                             VK_LValue, From->getLocStart());
5684   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5685                                 Context.getPointerType(Conversion->getType()),
5686                                 CK_FunctionToPointerDecay,
5687                                 &ConversionRef, VK_RValue);
5688 
5689   QualType ConversionType = Conversion->getConversionType();
5690   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5691     Candidate.Viable = false;
5692     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5693     return;
5694   }
5695 
5696   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5697 
5698   // Note that it is safe to allocate CallExpr on the stack here because
5699   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5700   // allocator).
5701   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5702   CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
5703                 From->getLocStart());
5704   ImplicitConversionSequence ICS =
5705     TryCopyInitialization(*this, &Call, ToType,
5706                           /*SuppressUserConversions=*/true,
5707                           /*InOverloadResolution=*/false,
5708                           /*AllowObjCWritebackConversion=*/false);
5709 
5710   switch (ICS.getKind()) {
5711   case ImplicitConversionSequence::StandardConversion:
5712     Candidate.FinalConversion = ICS.Standard;
5713 
5714     // C++ [over.ics.user]p3:
5715     //   If the user-defined conversion is specified by a specialization of a
5716     //   conversion function template, the second standard conversion sequence
5717     //   shall have exact match rank.
5718     if (Conversion->getPrimaryTemplate() &&
5719         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5720       Candidate.Viable = false;
5721       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5722     }
5723 
5724     // C++0x [dcl.init.ref]p5:
5725     //    In the second case, if the reference is an rvalue reference and
5726     //    the second standard conversion sequence of the user-defined
5727     //    conversion sequence includes an lvalue-to-rvalue conversion, the
5728     //    program is ill-formed.
5729     if (ToType->isRValueReferenceType() &&
5730         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5731       Candidate.Viable = false;
5732       Candidate.FailureKind = ovl_fail_bad_final_conversion;
5733     }
5734     break;
5735 
5736   case ImplicitConversionSequence::BadConversion:
5737     Candidate.Viable = false;
5738     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5739     break;
5740 
5741   default:
5742     llvm_unreachable(
5743            "Can only end up with a standard conversion sequence or failure");
5744   }
5745 }
5746 
5747 /// \brief Adds a conversion function template specialization
5748 /// candidate to the overload set, using template argument deduction
5749 /// to deduce the template arguments of the conversion function
5750 /// template from the type that we are converting to (C++
5751 /// [temp.deduct.conv]).
5752 void
5753 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5754                                      DeclAccessPair FoundDecl,
5755                                      CXXRecordDecl *ActingDC,
5756                                      Expr *From, QualType ToType,
5757                                      OverloadCandidateSet &CandidateSet) {
5758   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5759          "Only conversion function templates permitted here");
5760 
5761   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5762     return;
5763 
5764   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5765   CXXConversionDecl *Specialization = 0;
5766   if (TemplateDeductionResult Result
5767         = DeduceTemplateArguments(FunctionTemplate, ToType,
5768                                   Specialization, Info)) {
5769     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5770     Candidate.FoundDecl = FoundDecl;
5771     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5772     Candidate.Viable = false;
5773     Candidate.FailureKind = ovl_fail_bad_deduction;
5774     Candidate.IsSurrogate = false;
5775     Candidate.IgnoreObjectArgument = false;
5776     Candidate.ExplicitCallArguments = 1;
5777     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5778                                                           Info);
5779     return;
5780   }
5781 
5782   // Add the conversion function template specialization produced by
5783   // template argument deduction as a candidate.
5784   assert(Specialization && "Missing function template specialization?");
5785   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5786                          CandidateSet);
5787 }
5788 
5789 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5790 /// converts the given @c Object to a function pointer via the
5791 /// conversion function @c Conversion, and then attempts to call it
5792 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
5793 /// the type of function that we'll eventually be calling.
5794 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5795                                  DeclAccessPair FoundDecl,
5796                                  CXXRecordDecl *ActingContext,
5797                                  const FunctionProtoType *Proto,
5798                                  Expr *Object,
5799                                  llvm::ArrayRef<Expr *> Args,
5800                                  OverloadCandidateSet& CandidateSet) {
5801   if (!CandidateSet.isNewCandidate(Conversion))
5802     return;
5803 
5804   // Overload resolution is always an unevaluated context.
5805   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5806 
5807   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5808   Candidate.FoundDecl = FoundDecl;
5809   Candidate.Function = 0;
5810   Candidate.Surrogate = Conversion;
5811   Candidate.Viable = true;
5812   Candidate.IsSurrogate = true;
5813   Candidate.IgnoreObjectArgument = false;
5814   Candidate.ExplicitCallArguments = Args.size();
5815 
5816   // Determine the implicit conversion sequence for the implicit
5817   // object parameter.
5818   ImplicitConversionSequence ObjectInit
5819     = TryObjectArgumentInitialization(*this, Object->getType(),
5820                                       Object->Classify(Context),
5821                                       Conversion, ActingContext);
5822   if (ObjectInit.isBad()) {
5823     Candidate.Viable = false;
5824     Candidate.FailureKind = ovl_fail_bad_conversion;
5825     Candidate.Conversions[0] = ObjectInit;
5826     return;
5827   }
5828 
5829   // The first conversion is actually a user-defined conversion whose
5830   // first conversion is ObjectInit's standard conversion (which is
5831   // effectively a reference binding). Record it as such.
5832   Candidate.Conversions[0].setUserDefined();
5833   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5834   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5835   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5836   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5837   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5838   Candidate.Conversions[0].UserDefined.After
5839     = Candidate.Conversions[0].UserDefined.Before;
5840   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5841 
5842   // Find the
5843   unsigned NumArgsInProto = Proto->getNumArgs();
5844 
5845   // (C++ 13.3.2p2): A candidate function having fewer than m
5846   // parameters is viable only if it has an ellipsis in its parameter
5847   // list (8.3.5).
5848   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5849     Candidate.Viable = false;
5850     Candidate.FailureKind = ovl_fail_too_many_arguments;
5851     return;
5852   }
5853 
5854   // Function types don't have any default arguments, so just check if
5855   // we have enough arguments.
5856   if (Args.size() < NumArgsInProto) {
5857     // Not enough arguments.
5858     Candidate.Viable = false;
5859     Candidate.FailureKind = ovl_fail_too_few_arguments;
5860     return;
5861   }
5862 
5863   // Determine the implicit conversion sequences for each of the
5864   // arguments.
5865   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5866     if (ArgIdx < NumArgsInProto) {
5867       // (C++ 13.3.2p3): for F to be a viable function, there shall
5868       // exist for each argument an implicit conversion sequence
5869       // (13.3.3.1) that converts that argument to the corresponding
5870       // parameter of F.
5871       QualType ParamType = Proto->getArgType(ArgIdx);
5872       Candidate.Conversions[ArgIdx + 1]
5873         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5874                                 /*SuppressUserConversions=*/false,
5875                                 /*InOverloadResolution=*/false,
5876                                 /*AllowObjCWritebackConversion=*/
5877                                   getLangOpts().ObjCAutoRefCount);
5878       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5879         Candidate.Viable = false;
5880         Candidate.FailureKind = ovl_fail_bad_conversion;
5881         break;
5882       }
5883     } else {
5884       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5885       // argument for which there is no corresponding parameter is
5886       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5887       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5888     }
5889   }
5890 }
5891 
5892 /// \brief Add overload candidates for overloaded operators that are
5893 /// member functions.
5894 ///
5895 /// Add the overloaded operator candidates that are member functions
5896 /// for the operator Op that was used in an operator expression such
5897 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
5898 /// CandidateSet will store the added overload candidates. (C++
5899 /// [over.match.oper]).
5900 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5901                                        SourceLocation OpLoc,
5902                                        Expr **Args, unsigned NumArgs,
5903                                        OverloadCandidateSet& CandidateSet,
5904                                        SourceRange OpRange) {
5905   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5906 
5907   // C++ [over.match.oper]p3:
5908   //   For a unary operator @ with an operand of a type whose
5909   //   cv-unqualified version is T1, and for a binary operator @ with
5910   //   a left operand of a type whose cv-unqualified version is T1 and
5911   //   a right operand of a type whose cv-unqualified version is T2,
5912   //   three sets of candidate functions, designated member
5913   //   candidates, non-member candidates and built-in candidates, are
5914   //   constructed as follows:
5915   QualType T1 = Args[0]->getType();
5916 
5917   //     -- If T1 is a class type, the set of member candidates is the
5918   //        result of the qualified lookup of T1::operator@
5919   //        (13.3.1.1.1); otherwise, the set of member candidates is
5920   //        empty.
5921   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
5922     // Complete the type if it can be completed. Otherwise, we're done.
5923     if (RequireCompleteType(OpLoc, T1, 0))
5924       return;
5925 
5926     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5927     LookupQualifiedName(Operators, T1Rec->getDecl());
5928     Operators.suppressDiagnostics();
5929 
5930     for (LookupResult::iterator Oper = Operators.begin(),
5931                              OperEnd = Operators.end();
5932          Oper != OperEnd;
5933          ++Oper)
5934       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
5935                          Args[0]->Classify(Context), Args + 1, NumArgs - 1,
5936                          CandidateSet,
5937                          /* SuppressUserConversions = */ false);
5938   }
5939 }
5940 
5941 /// AddBuiltinCandidate - Add a candidate for a built-in
5942 /// operator. ResultTy and ParamTys are the result and parameter types
5943 /// of the built-in candidate, respectively. Args and NumArgs are the
5944 /// arguments being passed to the candidate. IsAssignmentOperator
5945 /// should be true when this built-in candidate is an assignment
5946 /// operator. NumContextualBoolArguments is the number of arguments
5947 /// (at the beginning of the argument list) that will be contextually
5948 /// converted to bool.
5949 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
5950                                Expr **Args, unsigned NumArgs,
5951                                OverloadCandidateSet& CandidateSet,
5952                                bool IsAssignmentOperator,
5953                                unsigned NumContextualBoolArguments) {
5954   // Overload resolution is always an unevaluated context.
5955   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5956 
5957   // Add this candidate
5958   OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
5959   Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
5960   Candidate.Function = 0;
5961   Candidate.IsSurrogate = false;
5962   Candidate.IgnoreObjectArgument = false;
5963   Candidate.BuiltinTypes.ResultTy = ResultTy;
5964   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5965     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5966 
5967   // Determine the implicit conversion sequences for each of the
5968   // arguments.
5969   Candidate.Viable = true;
5970   Candidate.ExplicitCallArguments = NumArgs;
5971   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5972     // C++ [over.match.oper]p4:
5973     //   For the built-in assignment operators, conversions of the
5974     //   left operand are restricted as follows:
5975     //     -- no temporaries are introduced to hold the left operand, and
5976     //     -- no user-defined conversions are applied to the left
5977     //        operand to achieve a type match with the left-most
5978     //        parameter of a built-in candidate.
5979     //
5980     // We block these conversions by turning off user-defined
5981     // conversions, since that is the only way that initialization of
5982     // a reference to a non-class type can occur from something that
5983     // is not of the same type.
5984     if (ArgIdx < NumContextualBoolArguments) {
5985       assert(ParamTys[ArgIdx] == Context.BoolTy &&
5986              "Contextual conversion to bool requires bool type");
5987       Candidate.Conversions[ArgIdx]
5988         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
5989     } else {
5990       Candidate.Conversions[ArgIdx]
5991         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
5992                                 ArgIdx == 0 && IsAssignmentOperator,
5993                                 /*InOverloadResolution=*/false,
5994                                 /*AllowObjCWritebackConversion=*/
5995                                   getLangOpts().ObjCAutoRefCount);
5996     }
5997     if (Candidate.Conversions[ArgIdx].isBad()) {
5998       Candidate.Viable = false;
5999       Candidate.FailureKind = ovl_fail_bad_conversion;
6000       break;
6001     }
6002   }
6003 }
6004 
6005 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6006 /// candidate operator functions for built-in operators (C++
6007 /// [over.built]). The types are separated into pointer types and
6008 /// enumeration types.
6009 class BuiltinCandidateTypeSet  {
6010   /// TypeSet - A set of types.
6011   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6012 
6013   /// PointerTypes - The set of pointer types that will be used in the
6014   /// built-in candidates.
6015   TypeSet PointerTypes;
6016 
6017   /// MemberPointerTypes - The set of member pointer types that will be
6018   /// used in the built-in candidates.
6019   TypeSet MemberPointerTypes;
6020 
6021   /// EnumerationTypes - The set of enumeration types that will be
6022   /// used in the built-in candidates.
6023   TypeSet EnumerationTypes;
6024 
6025   /// \brief The set of vector types that will be used in the built-in
6026   /// candidates.
6027   TypeSet VectorTypes;
6028 
6029   /// \brief A flag indicating non-record types are viable candidates
6030   bool HasNonRecordTypes;
6031 
6032   /// \brief A flag indicating whether either arithmetic or enumeration types
6033   /// were present in the candidate set.
6034   bool HasArithmeticOrEnumeralTypes;
6035 
6036   /// \brief A flag indicating whether the nullptr type was present in the
6037   /// candidate set.
6038   bool HasNullPtrType;
6039 
6040   /// Sema - The semantic analysis instance where we are building the
6041   /// candidate type set.
6042   Sema &SemaRef;
6043 
6044   /// Context - The AST context in which we will build the type sets.
6045   ASTContext &Context;
6046 
6047   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6048                                                const Qualifiers &VisibleQuals);
6049   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6050 
6051 public:
6052   /// iterator - Iterates through the types that are part of the set.
6053   typedef TypeSet::iterator iterator;
6054 
6055   BuiltinCandidateTypeSet(Sema &SemaRef)
6056     : HasNonRecordTypes(false),
6057       HasArithmeticOrEnumeralTypes(false),
6058       HasNullPtrType(false),
6059       SemaRef(SemaRef),
6060       Context(SemaRef.Context) { }
6061 
6062   void AddTypesConvertedFrom(QualType Ty,
6063                              SourceLocation Loc,
6064                              bool AllowUserConversions,
6065                              bool AllowExplicitConversions,
6066                              const Qualifiers &VisibleTypeConversionsQuals);
6067 
6068   /// pointer_begin - First pointer type found;
6069   iterator pointer_begin() { return PointerTypes.begin(); }
6070 
6071   /// pointer_end - Past the last pointer type found;
6072   iterator pointer_end() { return PointerTypes.end(); }
6073 
6074   /// member_pointer_begin - First member pointer type found;
6075   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6076 
6077   /// member_pointer_end - Past the last member pointer type found;
6078   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6079 
6080   /// enumeration_begin - First enumeration type found;
6081   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6082 
6083   /// enumeration_end - Past the last enumeration type found;
6084   iterator enumeration_end() { return EnumerationTypes.end(); }
6085 
6086   iterator vector_begin() { return VectorTypes.begin(); }
6087   iterator vector_end() { return VectorTypes.end(); }
6088 
6089   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6090   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6091   bool hasNullPtrType() const { return HasNullPtrType; }
6092 };
6093 
6094 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6095 /// the set of pointer types along with any more-qualified variants of
6096 /// that type. For example, if @p Ty is "int const *", this routine
6097 /// will add "int const *", "int const volatile *", "int const
6098 /// restrict *", and "int const volatile restrict *" to the set of
6099 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6100 /// false otherwise.
6101 ///
6102 /// FIXME: what to do about extended qualifiers?
6103 bool
6104 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6105                                              const Qualifiers &VisibleQuals) {
6106 
6107   // Insert this type.
6108   if (!PointerTypes.insert(Ty))
6109     return false;
6110 
6111   QualType PointeeTy;
6112   const PointerType *PointerTy = Ty->getAs<PointerType>();
6113   bool buildObjCPtr = false;
6114   if (!PointerTy) {
6115     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6116     PointeeTy = PTy->getPointeeType();
6117     buildObjCPtr = true;
6118   } else {
6119     PointeeTy = PointerTy->getPointeeType();
6120   }
6121 
6122   // Don't add qualified variants of arrays. For one, they're not allowed
6123   // (the qualifier would sink to the element type), and for another, the
6124   // only overload situation where it matters is subscript or pointer +- int,
6125   // and those shouldn't have qualifier variants anyway.
6126   if (PointeeTy->isArrayType())
6127     return true;
6128 
6129   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6130   bool hasVolatile = VisibleQuals.hasVolatile();
6131   bool hasRestrict = VisibleQuals.hasRestrict();
6132 
6133   // Iterate through all strict supersets of BaseCVR.
6134   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6135     if ((CVR | BaseCVR) != CVR) continue;
6136     // Skip over volatile if no volatile found anywhere in the types.
6137     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6138 
6139     // Skip over restrict if no restrict found anywhere in the types, or if
6140     // the type cannot be restrict-qualified.
6141     if ((CVR & Qualifiers::Restrict) &&
6142         (!hasRestrict ||
6143          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6144       continue;
6145 
6146     // Build qualified pointee type.
6147     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6148 
6149     // Build qualified pointer type.
6150     QualType QPointerTy;
6151     if (!buildObjCPtr)
6152       QPointerTy = Context.getPointerType(QPointeeTy);
6153     else
6154       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6155 
6156     // Insert qualified pointer type.
6157     PointerTypes.insert(QPointerTy);
6158   }
6159 
6160   return true;
6161 }
6162 
6163 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6164 /// to the set of pointer types along with any more-qualified variants of
6165 /// that type. For example, if @p Ty is "int const *", this routine
6166 /// will add "int const *", "int const volatile *", "int const
6167 /// restrict *", and "int const volatile restrict *" to the set of
6168 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6169 /// false otherwise.
6170 ///
6171 /// FIXME: what to do about extended qualifiers?
6172 bool
6173 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6174     QualType Ty) {
6175   // Insert this type.
6176   if (!MemberPointerTypes.insert(Ty))
6177     return false;
6178 
6179   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6180   assert(PointerTy && "type was not a member pointer type!");
6181 
6182   QualType PointeeTy = PointerTy->getPointeeType();
6183   // Don't add qualified variants of arrays. For one, they're not allowed
6184   // (the qualifier would sink to the element type), and for another, the
6185   // only overload situation where it matters is subscript or pointer +- int,
6186   // and those shouldn't have qualifier variants anyway.
6187   if (PointeeTy->isArrayType())
6188     return true;
6189   const Type *ClassTy = PointerTy->getClass();
6190 
6191   // Iterate through all strict supersets of the pointee type's CVR
6192   // qualifiers.
6193   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6194   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6195     if ((CVR | BaseCVR) != CVR) continue;
6196 
6197     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6198     MemberPointerTypes.insert(
6199       Context.getMemberPointerType(QPointeeTy, ClassTy));
6200   }
6201 
6202   return true;
6203 }
6204 
6205 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6206 /// Ty can be implicit converted to the given set of @p Types. We're
6207 /// primarily interested in pointer types and enumeration types. We also
6208 /// take member pointer types, for the conditional operator.
6209 /// AllowUserConversions is true if we should look at the conversion
6210 /// functions of a class type, and AllowExplicitConversions if we
6211 /// should also include the explicit conversion functions of a class
6212 /// type.
6213 void
6214 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6215                                                SourceLocation Loc,
6216                                                bool AllowUserConversions,
6217                                                bool AllowExplicitConversions,
6218                                                const Qualifiers &VisibleQuals) {
6219   // Only deal with canonical types.
6220   Ty = Context.getCanonicalType(Ty);
6221 
6222   // Look through reference types; they aren't part of the type of an
6223   // expression for the purposes of conversions.
6224   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6225     Ty = RefTy->getPointeeType();
6226 
6227   // If we're dealing with an array type, decay to the pointer.
6228   if (Ty->isArrayType())
6229     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6230 
6231   // Otherwise, we don't care about qualifiers on the type.
6232   Ty = Ty.getLocalUnqualifiedType();
6233 
6234   // Flag if we ever add a non-record type.
6235   const RecordType *TyRec = Ty->getAs<RecordType>();
6236   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6237 
6238   // Flag if we encounter an arithmetic type.
6239   HasArithmeticOrEnumeralTypes =
6240     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6241 
6242   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6243     PointerTypes.insert(Ty);
6244   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6245     // Insert our type, and its more-qualified variants, into the set
6246     // of types.
6247     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6248       return;
6249   } else if (Ty->isMemberPointerType()) {
6250     // Member pointers are far easier, since the pointee can't be converted.
6251     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6252       return;
6253   } else if (Ty->isEnumeralType()) {
6254     HasArithmeticOrEnumeralTypes = true;
6255     EnumerationTypes.insert(Ty);
6256   } else if (Ty->isVectorType()) {
6257     // We treat vector types as arithmetic types in many contexts as an
6258     // extension.
6259     HasArithmeticOrEnumeralTypes = true;
6260     VectorTypes.insert(Ty);
6261   } else if (Ty->isNullPtrType()) {
6262     HasNullPtrType = true;
6263   } else if (AllowUserConversions && TyRec) {
6264     // No conversion functions in incomplete types.
6265     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6266       return;
6267 
6268     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6269     const UnresolvedSetImpl *Conversions
6270       = ClassDecl->getVisibleConversionFunctions();
6271     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6272            E = Conversions->end(); I != E; ++I) {
6273       NamedDecl *D = I.getDecl();
6274       if (isa<UsingShadowDecl>(D))
6275         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6276 
6277       // Skip conversion function templates; they don't tell us anything
6278       // about which builtin types we can convert to.
6279       if (isa<FunctionTemplateDecl>(D))
6280         continue;
6281 
6282       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6283       if (AllowExplicitConversions || !Conv->isExplicit()) {
6284         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6285                               VisibleQuals);
6286       }
6287     }
6288   }
6289 }
6290 
6291 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6292 /// the volatile- and non-volatile-qualified assignment operators for the
6293 /// given type to the candidate set.
6294 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6295                                                    QualType T,
6296                                                    Expr **Args,
6297                                                    unsigned NumArgs,
6298                                     OverloadCandidateSet &CandidateSet) {
6299   QualType ParamTypes[2];
6300 
6301   // T& operator=(T&, T)
6302   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6303   ParamTypes[1] = T;
6304   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6305                         /*IsAssignmentOperator=*/true);
6306 
6307   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6308     // volatile T& operator=(volatile T&, T)
6309     ParamTypes[0]
6310       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6311     ParamTypes[1] = T;
6312     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6313                           /*IsAssignmentOperator=*/true);
6314   }
6315 }
6316 
6317 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6318 /// if any, found in visible type conversion functions found in ArgExpr's type.
6319 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6320     Qualifiers VRQuals;
6321     const RecordType *TyRec;
6322     if (const MemberPointerType *RHSMPType =
6323         ArgExpr->getType()->getAs<MemberPointerType>())
6324       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6325     else
6326       TyRec = ArgExpr->getType()->getAs<RecordType>();
6327     if (!TyRec) {
6328       // Just to be safe, assume the worst case.
6329       VRQuals.addVolatile();
6330       VRQuals.addRestrict();
6331       return VRQuals;
6332     }
6333 
6334     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6335     if (!ClassDecl->hasDefinition())
6336       return VRQuals;
6337 
6338     const UnresolvedSetImpl *Conversions =
6339       ClassDecl->getVisibleConversionFunctions();
6340 
6341     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6342            E = Conversions->end(); I != E; ++I) {
6343       NamedDecl *D = I.getDecl();
6344       if (isa<UsingShadowDecl>(D))
6345         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6346       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6347         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6348         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6349           CanTy = ResTypeRef->getPointeeType();
6350         // Need to go down the pointer/mempointer chain and add qualifiers
6351         // as see them.
6352         bool done = false;
6353         while (!done) {
6354           if (CanTy.isRestrictQualified())
6355             VRQuals.addRestrict();
6356           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6357             CanTy = ResTypePtr->getPointeeType();
6358           else if (const MemberPointerType *ResTypeMPtr =
6359                 CanTy->getAs<MemberPointerType>())
6360             CanTy = ResTypeMPtr->getPointeeType();
6361           else
6362             done = true;
6363           if (CanTy.isVolatileQualified())
6364             VRQuals.addVolatile();
6365           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6366             return VRQuals;
6367         }
6368       }
6369     }
6370     return VRQuals;
6371 }
6372 
6373 namespace {
6374 
6375 /// \brief Helper class to manage the addition of builtin operator overload
6376 /// candidates. It provides shared state and utility methods used throughout
6377 /// the process, as well as a helper method to add each group of builtin
6378 /// operator overloads from the standard to a candidate set.
6379 class BuiltinOperatorOverloadBuilder {
6380   // Common instance state available to all overload candidate addition methods.
6381   Sema &S;
6382   Expr **Args;
6383   unsigned NumArgs;
6384   Qualifiers VisibleTypeConversionsQuals;
6385   bool HasArithmeticOrEnumeralCandidateType;
6386   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6387   OverloadCandidateSet &CandidateSet;
6388 
6389   // Define some constants used to index and iterate over the arithemetic types
6390   // provided via the getArithmeticType() method below.
6391   // The "promoted arithmetic types" are the arithmetic
6392   // types are that preserved by promotion (C++ [over.built]p2).
6393   static const unsigned FirstIntegralType = 3;
6394   static const unsigned LastIntegralType = 20;
6395   static const unsigned FirstPromotedIntegralType = 3,
6396                         LastPromotedIntegralType = 11;
6397   static const unsigned FirstPromotedArithmeticType = 0,
6398                         LastPromotedArithmeticType = 11;
6399   static const unsigned NumArithmeticTypes = 20;
6400 
6401   /// \brief Get the canonical type for a given arithmetic type index.
6402   CanQualType getArithmeticType(unsigned index) {
6403     assert(index < NumArithmeticTypes);
6404     static CanQualType ASTContext::* const
6405       ArithmeticTypes[NumArithmeticTypes] = {
6406       // Start of promoted types.
6407       &ASTContext::FloatTy,
6408       &ASTContext::DoubleTy,
6409       &ASTContext::LongDoubleTy,
6410 
6411       // Start of integral types.
6412       &ASTContext::IntTy,
6413       &ASTContext::LongTy,
6414       &ASTContext::LongLongTy,
6415       &ASTContext::Int128Ty,
6416       &ASTContext::UnsignedIntTy,
6417       &ASTContext::UnsignedLongTy,
6418       &ASTContext::UnsignedLongLongTy,
6419       &ASTContext::UnsignedInt128Ty,
6420       // End of promoted types.
6421 
6422       &ASTContext::BoolTy,
6423       &ASTContext::CharTy,
6424       &ASTContext::WCharTy,
6425       &ASTContext::Char16Ty,
6426       &ASTContext::Char32Ty,
6427       &ASTContext::SignedCharTy,
6428       &ASTContext::ShortTy,
6429       &ASTContext::UnsignedCharTy,
6430       &ASTContext::UnsignedShortTy,
6431       // End of integral types.
6432       // FIXME: What about complex? What about half?
6433     };
6434     return S.Context.*ArithmeticTypes[index];
6435   }
6436 
6437   /// \brief Gets the canonical type resulting from the usual arithemetic
6438   /// converions for the given arithmetic types.
6439   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6440     // Accelerator table for performing the usual arithmetic conversions.
6441     // The rules are basically:
6442     //   - if either is floating-point, use the wider floating-point
6443     //   - if same signedness, use the higher rank
6444     //   - if same size, use unsigned of the higher rank
6445     //   - use the larger type
6446     // These rules, together with the axiom that higher ranks are
6447     // never smaller, are sufficient to precompute all of these results
6448     // *except* when dealing with signed types of higher rank.
6449     // (we could precompute SLL x UI for all known platforms, but it's
6450     // better not to make any assumptions).
6451     // We assume that int128 has a higher rank than long long on all platforms.
6452     enum PromotedType {
6453             Dep=-1,
6454             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6455     };
6456     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6457                                         [LastPromotedArithmeticType] = {
6458 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6459 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6460 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6461 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6462 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6463 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6464 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6465 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6466 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6467 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6468 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6469     };
6470 
6471     assert(L < LastPromotedArithmeticType);
6472     assert(R < LastPromotedArithmeticType);
6473     int Idx = ConversionsTable[L][R];
6474 
6475     // Fast path: the table gives us a concrete answer.
6476     if (Idx != Dep) return getArithmeticType(Idx);
6477 
6478     // Slow path: we need to compare widths.
6479     // An invariant is that the signed type has higher rank.
6480     CanQualType LT = getArithmeticType(L),
6481                 RT = getArithmeticType(R);
6482     unsigned LW = S.Context.getIntWidth(LT),
6483              RW = S.Context.getIntWidth(RT);
6484 
6485     // If they're different widths, use the signed type.
6486     if (LW > RW) return LT;
6487     else if (LW < RW) return RT;
6488 
6489     // Otherwise, use the unsigned type of the signed type's rank.
6490     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6491     assert(L == SLL || R == SLL);
6492     return S.Context.UnsignedLongLongTy;
6493   }
6494 
6495   /// \brief Helper method to factor out the common pattern of adding overloads
6496   /// for '++' and '--' builtin operators.
6497   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6498                                            bool HasVolatile,
6499                                            bool HasRestrict) {
6500     QualType ParamTypes[2] = {
6501       S.Context.getLValueReferenceType(CandidateTy),
6502       S.Context.IntTy
6503     };
6504 
6505     // Non-volatile version.
6506     if (NumArgs == 1)
6507       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6508     else
6509       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6510 
6511     // Use a heuristic to reduce number of builtin candidates in the set:
6512     // add volatile version only if there are conversions to a volatile type.
6513     if (HasVolatile) {
6514       ParamTypes[0] =
6515         S.Context.getLValueReferenceType(
6516           S.Context.getVolatileType(CandidateTy));
6517       if (NumArgs == 1)
6518         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6519       else
6520         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6521     }
6522 
6523     // Add restrict version only if there are conversions to a restrict type
6524     // and our candidate type is a non-restrict-qualified pointer.
6525     if (HasRestrict && CandidateTy->isAnyPointerType() &&
6526         !CandidateTy.isRestrictQualified()) {
6527       ParamTypes[0]
6528         = S.Context.getLValueReferenceType(
6529             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6530       if (NumArgs == 1)
6531         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6532       else
6533         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6534 
6535       if (HasVolatile) {
6536         ParamTypes[0]
6537           = S.Context.getLValueReferenceType(
6538               S.Context.getCVRQualifiedType(CandidateTy,
6539                                             (Qualifiers::Volatile |
6540                                              Qualifiers::Restrict)));
6541         if (NumArgs == 1)
6542           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6543                                 CandidateSet);
6544         else
6545           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6546       }
6547     }
6548 
6549   }
6550 
6551 public:
6552   BuiltinOperatorOverloadBuilder(
6553     Sema &S, Expr **Args, unsigned NumArgs,
6554     Qualifiers VisibleTypeConversionsQuals,
6555     bool HasArithmeticOrEnumeralCandidateType,
6556     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6557     OverloadCandidateSet &CandidateSet)
6558     : S(S), Args(Args), NumArgs(NumArgs),
6559       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6560       HasArithmeticOrEnumeralCandidateType(
6561         HasArithmeticOrEnumeralCandidateType),
6562       CandidateTypes(CandidateTypes),
6563       CandidateSet(CandidateSet) {
6564     // Validate some of our static helper constants in debug builds.
6565     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6566            "Invalid first promoted integral type");
6567     assert(getArithmeticType(LastPromotedIntegralType - 1)
6568              == S.Context.UnsignedInt128Ty &&
6569            "Invalid last promoted integral type");
6570     assert(getArithmeticType(FirstPromotedArithmeticType)
6571              == S.Context.FloatTy &&
6572            "Invalid first promoted arithmetic type");
6573     assert(getArithmeticType(LastPromotedArithmeticType - 1)
6574              == S.Context.UnsignedInt128Ty &&
6575            "Invalid last promoted arithmetic type");
6576   }
6577 
6578   // C++ [over.built]p3:
6579   //
6580   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6581   //   is either volatile or empty, there exist candidate operator
6582   //   functions of the form
6583   //
6584   //       VQ T&      operator++(VQ T&);
6585   //       T          operator++(VQ T&, int);
6586   //
6587   // C++ [over.built]p4:
6588   //
6589   //   For every pair (T, VQ), where T is an arithmetic type other
6590   //   than bool, and VQ is either volatile or empty, there exist
6591   //   candidate operator functions of the form
6592   //
6593   //       VQ T&      operator--(VQ T&);
6594   //       T          operator--(VQ T&, int);
6595   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6596     if (!HasArithmeticOrEnumeralCandidateType)
6597       return;
6598 
6599     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6600          Arith < NumArithmeticTypes; ++Arith) {
6601       addPlusPlusMinusMinusStyleOverloads(
6602         getArithmeticType(Arith),
6603         VisibleTypeConversionsQuals.hasVolatile(),
6604         VisibleTypeConversionsQuals.hasRestrict());
6605     }
6606   }
6607 
6608   // C++ [over.built]p5:
6609   //
6610   //   For every pair (T, VQ), where T is a cv-qualified or
6611   //   cv-unqualified object type, and VQ is either volatile or
6612   //   empty, there exist candidate operator functions of the form
6613   //
6614   //       T*VQ&      operator++(T*VQ&);
6615   //       T*VQ&      operator--(T*VQ&);
6616   //       T*         operator++(T*VQ&, int);
6617   //       T*         operator--(T*VQ&, int);
6618   void addPlusPlusMinusMinusPointerOverloads() {
6619     for (BuiltinCandidateTypeSet::iterator
6620               Ptr = CandidateTypes[0].pointer_begin(),
6621            PtrEnd = CandidateTypes[0].pointer_end();
6622          Ptr != PtrEnd; ++Ptr) {
6623       // Skip pointer types that aren't pointers to object types.
6624       if (!(*Ptr)->getPointeeType()->isObjectType())
6625         continue;
6626 
6627       addPlusPlusMinusMinusStyleOverloads(*Ptr,
6628         (!(*Ptr).isVolatileQualified() &&
6629          VisibleTypeConversionsQuals.hasVolatile()),
6630         (!(*Ptr).isRestrictQualified() &&
6631          VisibleTypeConversionsQuals.hasRestrict()));
6632     }
6633   }
6634 
6635   // C++ [over.built]p6:
6636   //   For every cv-qualified or cv-unqualified object type T, there
6637   //   exist candidate operator functions of the form
6638   //
6639   //       T&         operator*(T*);
6640   //
6641   // C++ [over.built]p7:
6642   //   For every function type T that does not have cv-qualifiers or a
6643   //   ref-qualifier, there exist candidate operator functions of the form
6644   //       T&         operator*(T*);
6645   void addUnaryStarPointerOverloads() {
6646     for (BuiltinCandidateTypeSet::iterator
6647               Ptr = CandidateTypes[0].pointer_begin(),
6648            PtrEnd = CandidateTypes[0].pointer_end();
6649          Ptr != PtrEnd; ++Ptr) {
6650       QualType ParamTy = *Ptr;
6651       QualType PointeeTy = ParamTy->getPointeeType();
6652       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6653         continue;
6654 
6655       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6656         if (Proto->getTypeQuals() || Proto->getRefQualifier())
6657           continue;
6658 
6659       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6660                             &ParamTy, Args, 1, CandidateSet);
6661     }
6662   }
6663 
6664   // C++ [over.built]p9:
6665   //  For every promoted arithmetic type T, there exist candidate
6666   //  operator functions of the form
6667   //
6668   //       T         operator+(T);
6669   //       T         operator-(T);
6670   void addUnaryPlusOrMinusArithmeticOverloads() {
6671     if (!HasArithmeticOrEnumeralCandidateType)
6672       return;
6673 
6674     for (unsigned Arith = FirstPromotedArithmeticType;
6675          Arith < LastPromotedArithmeticType; ++Arith) {
6676       QualType ArithTy = getArithmeticType(Arith);
6677       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6678     }
6679 
6680     // Extension: We also add these operators for vector types.
6681     for (BuiltinCandidateTypeSet::iterator
6682               Vec = CandidateTypes[0].vector_begin(),
6683            VecEnd = CandidateTypes[0].vector_end();
6684          Vec != VecEnd; ++Vec) {
6685       QualType VecTy = *Vec;
6686       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6687     }
6688   }
6689 
6690   // C++ [over.built]p8:
6691   //   For every type T, there exist candidate operator functions of
6692   //   the form
6693   //
6694   //       T*         operator+(T*);
6695   void addUnaryPlusPointerOverloads() {
6696     for (BuiltinCandidateTypeSet::iterator
6697               Ptr = CandidateTypes[0].pointer_begin(),
6698            PtrEnd = CandidateTypes[0].pointer_end();
6699          Ptr != PtrEnd; ++Ptr) {
6700       QualType ParamTy = *Ptr;
6701       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6702     }
6703   }
6704 
6705   // C++ [over.built]p10:
6706   //   For every promoted integral type T, there exist candidate
6707   //   operator functions of the form
6708   //
6709   //        T         operator~(T);
6710   void addUnaryTildePromotedIntegralOverloads() {
6711     if (!HasArithmeticOrEnumeralCandidateType)
6712       return;
6713 
6714     for (unsigned Int = FirstPromotedIntegralType;
6715          Int < LastPromotedIntegralType; ++Int) {
6716       QualType IntTy = getArithmeticType(Int);
6717       S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6718     }
6719 
6720     // Extension: We also add this operator for vector types.
6721     for (BuiltinCandidateTypeSet::iterator
6722               Vec = CandidateTypes[0].vector_begin(),
6723            VecEnd = CandidateTypes[0].vector_end();
6724          Vec != VecEnd; ++Vec) {
6725       QualType VecTy = *Vec;
6726       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6727     }
6728   }
6729 
6730   // C++ [over.match.oper]p16:
6731   //   For every pointer to member type T, there exist candidate operator
6732   //   functions of the form
6733   //
6734   //        bool operator==(T,T);
6735   //        bool operator!=(T,T);
6736   void addEqualEqualOrNotEqualMemberPointerOverloads() {
6737     /// Set of (canonical) types that we've already handled.
6738     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6739 
6740     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6741       for (BuiltinCandidateTypeSet::iterator
6742                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6743              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6744            MemPtr != MemPtrEnd;
6745            ++MemPtr) {
6746         // Don't add the same builtin candidate twice.
6747         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6748           continue;
6749 
6750         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6751         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6752                               CandidateSet);
6753       }
6754     }
6755   }
6756 
6757   // C++ [over.built]p15:
6758   //
6759   //   For every T, where T is an enumeration type, a pointer type, or
6760   //   std::nullptr_t, there exist candidate operator functions of the form
6761   //
6762   //        bool       operator<(T, T);
6763   //        bool       operator>(T, T);
6764   //        bool       operator<=(T, T);
6765   //        bool       operator>=(T, T);
6766   //        bool       operator==(T, T);
6767   //        bool       operator!=(T, T);
6768   void addRelationalPointerOrEnumeralOverloads() {
6769     // C++ [over.built]p1:
6770     //   If there is a user-written candidate with the same name and parameter
6771     //   types as a built-in candidate operator function, the built-in operator
6772     //   function is hidden and is not included in the set of candidate
6773     //   functions.
6774     //
6775     // The text is actually in a note, but if we don't implement it then we end
6776     // up with ambiguities when the user provides an overloaded operator for
6777     // an enumeration type. Note that only enumeration types have this problem,
6778     // so we track which enumeration types we've seen operators for. Also, the
6779     // only other overloaded operator with enumeration argumenst, operator=,
6780     // cannot be overloaded for enumeration types, so this is the only place
6781     // where we must suppress candidates like this.
6782     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6783       UserDefinedBinaryOperators;
6784 
6785     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6786       if (CandidateTypes[ArgIdx].enumeration_begin() !=
6787           CandidateTypes[ArgIdx].enumeration_end()) {
6788         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6789                                          CEnd = CandidateSet.end();
6790              C != CEnd; ++C) {
6791           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6792             continue;
6793 
6794           QualType FirstParamType =
6795             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6796           QualType SecondParamType =
6797             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6798 
6799           // Skip if either parameter isn't of enumeral type.
6800           if (!FirstParamType->isEnumeralType() ||
6801               !SecondParamType->isEnumeralType())
6802             continue;
6803 
6804           // Add this operator to the set of known user-defined operators.
6805           UserDefinedBinaryOperators.insert(
6806             std::make_pair(S.Context.getCanonicalType(FirstParamType),
6807                            S.Context.getCanonicalType(SecondParamType)));
6808         }
6809       }
6810     }
6811 
6812     /// Set of (canonical) types that we've already handled.
6813     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6814 
6815     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6816       for (BuiltinCandidateTypeSet::iterator
6817                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6818              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6819            Ptr != PtrEnd; ++Ptr) {
6820         // Don't add the same builtin candidate twice.
6821         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6822           continue;
6823 
6824         QualType ParamTypes[2] = { *Ptr, *Ptr };
6825         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6826                               CandidateSet);
6827       }
6828       for (BuiltinCandidateTypeSet::iterator
6829                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6830              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6831            Enum != EnumEnd; ++Enum) {
6832         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6833 
6834         // Don't add the same builtin candidate twice, or if a user defined
6835         // candidate exists.
6836         if (!AddedTypes.insert(CanonType) ||
6837             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6838                                                             CanonType)))
6839           continue;
6840 
6841         QualType ParamTypes[2] = { *Enum, *Enum };
6842         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6843                               CandidateSet);
6844       }
6845 
6846       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6847         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6848         if (AddedTypes.insert(NullPtrTy) &&
6849             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6850                                                              NullPtrTy))) {
6851           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6852           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6853                                 CandidateSet);
6854         }
6855       }
6856     }
6857   }
6858 
6859   // C++ [over.built]p13:
6860   //
6861   //   For every cv-qualified or cv-unqualified object type T
6862   //   there exist candidate operator functions of the form
6863   //
6864   //      T*         operator+(T*, ptrdiff_t);
6865   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6866   //      T*         operator-(T*, ptrdiff_t);
6867   //      T*         operator+(ptrdiff_t, T*);
6868   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6869   //
6870   // C++ [over.built]p14:
6871   //
6872   //   For every T, where T is a pointer to object type, there
6873   //   exist candidate operator functions of the form
6874   //
6875   //      ptrdiff_t  operator-(T, T);
6876   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6877     /// Set of (canonical) types that we've already handled.
6878     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6879 
6880     for (int Arg = 0; Arg < 2; ++Arg) {
6881       QualType AsymetricParamTypes[2] = {
6882         S.Context.getPointerDiffType(),
6883         S.Context.getPointerDiffType(),
6884       };
6885       for (BuiltinCandidateTypeSet::iterator
6886                 Ptr = CandidateTypes[Arg].pointer_begin(),
6887              PtrEnd = CandidateTypes[Arg].pointer_end();
6888            Ptr != PtrEnd; ++Ptr) {
6889         QualType PointeeTy = (*Ptr)->getPointeeType();
6890         if (!PointeeTy->isObjectType())
6891           continue;
6892 
6893         AsymetricParamTypes[Arg] = *Ptr;
6894         if (Arg == 0 || Op == OO_Plus) {
6895           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6896           // T* operator+(ptrdiff_t, T*);
6897           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6898                                 CandidateSet);
6899         }
6900         if (Op == OO_Minus) {
6901           // ptrdiff_t operator-(T, T);
6902           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6903             continue;
6904 
6905           QualType ParamTypes[2] = { *Ptr, *Ptr };
6906           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6907                                 Args, 2, CandidateSet);
6908         }
6909       }
6910     }
6911   }
6912 
6913   // C++ [over.built]p12:
6914   //
6915   //   For every pair of promoted arithmetic types L and R, there
6916   //   exist candidate operator functions of the form
6917   //
6918   //        LR         operator*(L, R);
6919   //        LR         operator/(L, R);
6920   //        LR         operator+(L, R);
6921   //        LR         operator-(L, R);
6922   //        bool       operator<(L, R);
6923   //        bool       operator>(L, R);
6924   //        bool       operator<=(L, R);
6925   //        bool       operator>=(L, R);
6926   //        bool       operator==(L, R);
6927   //        bool       operator!=(L, R);
6928   //
6929   //   where LR is the result of the usual arithmetic conversions
6930   //   between types L and R.
6931   //
6932   // C++ [over.built]p24:
6933   //
6934   //   For every pair of promoted arithmetic types L and R, there exist
6935   //   candidate operator functions of the form
6936   //
6937   //        LR       operator?(bool, L, R);
6938   //
6939   //   where LR is the result of the usual arithmetic conversions
6940   //   between types L and R.
6941   // Our candidates ignore the first parameter.
6942   void addGenericBinaryArithmeticOverloads(bool isComparison) {
6943     if (!HasArithmeticOrEnumeralCandidateType)
6944       return;
6945 
6946     for (unsigned Left = FirstPromotedArithmeticType;
6947          Left < LastPromotedArithmeticType; ++Left) {
6948       for (unsigned Right = FirstPromotedArithmeticType;
6949            Right < LastPromotedArithmeticType; ++Right) {
6950         QualType LandR[2] = { getArithmeticType(Left),
6951                               getArithmeticType(Right) };
6952         QualType Result =
6953           isComparison ? S.Context.BoolTy
6954                        : getUsualArithmeticConversions(Left, Right);
6955         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6956       }
6957     }
6958 
6959     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6960     // conditional operator for vector types.
6961     for (BuiltinCandidateTypeSet::iterator
6962               Vec1 = CandidateTypes[0].vector_begin(),
6963            Vec1End = CandidateTypes[0].vector_end();
6964          Vec1 != Vec1End; ++Vec1) {
6965       for (BuiltinCandidateTypeSet::iterator
6966                 Vec2 = CandidateTypes[1].vector_begin(),
6967              Vec2End = CandidateTypes[1].vector_end();
6968            Vec2 != Vec2End; ++Vec2) {
6969         QualType LandR[2] = { *Vec1, *Vec2 };
6970         QualType Result = S.Context.BoolTy;
6971         if (!isComparison) {
6972           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6973             Result = *Vec1;
6974           else
6975             Result = *Vec2;
6976         }
6977 
6978         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6979       }
6980     }
6981   }
6982 
6983   // C++ [over.built]p17:
6984   //
6985   //   For every pair of promoted integral types L and R, there
6986   //   exist candidate operator functions of the form
6987   //
6988   //      LR         operator%(L, R);
6989   //      LR         operator&(L, R);
6990   //      LR         operator^(L, R);
6991   //      LR         operator|(L, R);
6992   //      L          operator<<(L, R);
6993   //      L          operator>>(L, R);
6994   //
6995   //   where LR is the result of the usual arithmetic conversions
6996   //   between types L and R.
6997   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
6998     if (!HasArithmeticOrEnumeralCandidateType)
6999       return;
7000 
7001     for (unsigned Left = FirstPromotedIntegralType;
7002          Left < LastPromotedIntegralType; ++Left) {
7003       for (unsigned Right = FirstPromotedIntegralType;
7004            Right < LastPromotedIntegralType; ++Right) {
7005         QualType LandR[2] = { getArithmeticType(Left),
7006                               getArithmeticType(Right) };
7007         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7008             ? LandR[0]
7009             : getUsualArithmeticConversions(Left, Right);
7010         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7011       }
7012     }
7013   }
7014 
7015   // C++ [over.built]p20:
7016   //
7017   //   For every pair (T, VQ), where T is an enumeration or
7018   //   pointer to member type and VQ is either volatile or
7019   //   empty, there exist candidate operator functions of the form
7020   //
7021   //        VQ T&      operator=(VQ T&, T);
7022   void addAssignmentMemberPointerOrEnumeralOverloads() {
7023     /// Set of (canonical) types that we've already handled.
7024     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7025 
7026     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7027       for (BuiltinCandidateTypeSet::iterator
7028                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7029              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7030            Enum != EnumEnd; ++Enum) {
7031         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7032           continue;
7033 
7034         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7035                                                CandidateSet);
7036       }
7037 
7038       for (BuiltinCandidateTypeSet::iterator
7039                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7040              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7041            MemPtr != MemPtrEnd; ++MemPtr) {
7042         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7043           continue;
7044 
7045         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7046                                                CandidateSet);
7047       }
7048     }
7049   }
7050 
7051   // C++ [over.built]p19:
7052   //
7053   //   For every pair (T, VQ), where T is any type and VQ is either
7054   //   volatile or empty, there exist candidate operator functions
7055   //   of the form
7056   //
7057   //        T*VQ&      operator=(T*VQ&, T*);
7058   //
7059   // C++ [over.built]p21:
7060   //
7061   //   For every pair (T, VQ), where T is a cv-qualified or
7062   //   cv-unqualified object type and VQ is either volatile or
7063   //   empty, there exist candidate operator functions of the form
7064   //
7065   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7066   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7067   void addAssignmentPointerOverloads(bool isEqualOp) {
7068     /// Set of (canonical) types that we've already handled.
7069     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7070 
7071     for (BuiltinCandidateTypeSet::iterator
7072               Ptr = CandidateTypes[0].pointer_begin(),
7073            PtrEnd = CandidateTypes[0].pointer_end();
7074          Ptr != PtrEnd; ++Ptr) {
7075       // If this is operator=, keep track of the builtin candidates we added.
7076       if (isEqualOp)
7077         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7078       else if (!(*Ptr)->getPointeeType()->isObjectType())
7079         continue;
7080 
7081       // non-volatile version
7082       QualType ParamTypes[2] = {
7083         S.Context.getLValueReferenceType(*Ptr),
7084         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7085       };
7086       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7087                             /*IsAssigmentOperator=*/ isEqualOp);
7088 
7089       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7090                           VisibleTypeConversionsQuals.hasVolatile();
7091       if (NeedVolatile) {
7092         // volatile version
7093         ParamTypes[0] =
7094           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7095         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7096                               /*IsAssigmentOperator=*/isEqualOp);
7097       }
7098 
7099       if (!(*Ptr).isRestrictQualified() &&
7100           VisibleTypeConversionsQuals.hasRestrict()) {
7101         // restrict version
7102         ParamTypes[0]
7103           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7104         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7105                               /*IsAssigmentOperator=*/isEqualOp);
7106 
7107         if (NeedVolatile) {
7108           // volatile restrict version
7109           ParamTypes[0]
7110             = S.Context.getLValueReferenceType(
7111                 S.Context.getCVRQualifiedType(*Ptr,
7112                                               (Qualifiers::Volatile |
7113                                                Qualifiers::Restrict)));
7114           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7115                                 CandidateSet,
7116                                 /*IsAssigmentOperator=*/isEqualOp);
7117         }
7118       }
7119     }
7120 
7121     if (isEqualOp) {
7122       for (BuiltinCandidateTypeSet::iterator
7123                 Ptr = CandidateTypes[1].pointer_begin(),
7124              PtrEnd = CandidateTypes[1].pointer_end();
7125            Ptr != PtrEnd; ++Ptr) {
7126         // Make sure we don't add the same candidate twice.
7127         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7128           continue;
7129 
7130         QualType ParamTypes[2] = {
7131           S.Context.getLValueReferenceType(*Ptr),
7132           *Ptr,
7133         };
7134 
7135         // non-volatile version
7136         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7137                               /*IsAssigmentOperator=*/true);
7138 
7139         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7140                            VisibleTypeConversionsQuals.hasVolatile();
7141         if (NeedVolatile) {
7142           // volatile version
7143           ParamTypes[0] =
7144             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7145           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7146                                 CandidateSet, /*IsAssigmentOperator=*/true);
7147         }
7148 
7149         if (!(*Ptr).isRestrictQualified() &&
7150             VisibleTypeConversionsQuals.hasRestrict()) {
7151           // restrict version
7152           ParamTypes[0]
7153             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7154           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7155                                 CandidateSet, /*IsAssigmentOperator=*/true);
7156 
7157           if (NeedVolatile) {
7158             // volatile restrict version
7159             ParamTypes[0]
7160               = S.Context.getLValueReferenceType(
7161                   S.Context.getCVRQualifiedType(*Ptr,
7162                                                 (Qualifiers::Volatile |
7163                                                  Qualifiers::Restrict)));
7164             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7165                                   CandidateSet, /*IsAssigmentOperator=*/true);
7166 
7167           }
7168         }
7169       }
7170     }
7171   }
7172 
7173   // C++ [over.built]p18:
7174   //
7175   //   For every triple (L, VQ, R), where L is an arithmetic type,
7176   //   VQ is either volatile or empty, and R is a promoted
7177   //   arithmetic type, there exist candidate operator functions of
7178   //   the form
7179   //
7180   //        VQ L&      operator=(VQ L&, R);
7181   //        VQ L&      operator*=(VQ L&, R);
7182   //        VQ L&      operator/=(VQ L&, R);
7183   //        VQ L&      operator+=(VQ L&, R);
7184   //        VQ L&      operator-=(VQ L&, R);
7185   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7186     if (!HasArithmeticOrEnumeralCandidateType)
7187       return;
7188 
7189     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7190       for (unsigned Right = FirstPromotedArithmeticType;
7191            Right < LastPromotedArithmeticType; ++Right) {
7192         QualType ParamTypes[2];
7193         ParamTypes[1] = getArithmeticType(Right);
7194 
7195         // Add this built-in operator as a candidate (VQ is empty).
7196         ParamTypes[0] =
7197           S.Context.getLValueReferenceType(getArithmeticType(Left));
7198         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7199                               /*IsAssigmentOperator=*/isEqualOp);
7200 
7201         // Add this built-in operator as a candidate (VQ is 'volatile').
7202         if (VisibleTypeConversionsQuals.hasVolatile()) {
7203           ParamTypes[0] =
7204             S.Context.getVolatileType(getArithmeticType(Left));
7205           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7206           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7207                                 CandidateSet,
7208                                 /*IsAssigmentOperator=*/isEqualOp);
7209         }
7210       }
7211     }
7212 
7213     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7214     for (BuiltinCandidateTypeSet::iterator
7215               Vec1 = CandidateTypes[0].vector_begin(),
7216            Vec1End = CandidateTypes[0].vector_end();
7217          Vec1 != Vec1End; ++Vec1) {
7218       for (BuiltinCandidateTypeSet::iterator
7219                 Vec2 = CandidateTypes[1].vector_begin(),
7220              Vec2End = CandidateTypes[1].vector_end();
7221            Vec2 != Vec2End; ++Vec2) {
7222         QualType ParamTypes[2];
7223         ParamTypes[1] = *Vec2;
7224         // Add this built-in operator as a candidate (VQ is empty).
7225         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7226         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7227                               /*IsAssigmentOperator=*/isEqualOp);
7228 
7229         // Add this built-in operator as a candidate (VQ is 'volatile').
7230         if (VisibleTypeConversionsQuals.hasVolatile()) {
7231           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7232           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7233           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7234                                 CandidateSet,
7235                                 /*IsAssigmentOperator=*/isEqualOp);
7236         }
7237       }
7238     }
7239   }
7240 
7241   // C++ [over.built]p22:
7242   //
7243   //   For every triple (L, VQ, R), where L is an integral type, VQ
7244   //   is either volatile or empty, and R is a promoted integral
7245   //   type, there exist candidate operator functions of the form
7246   //
7247   //        VQ L&       operator%=(VQ L&, R);
7248   //        VQ L&       operator<<=(VQ L&, R);
7249   //        VQ L&       operator>>=(VQ L&, R);
7250   //        VQ L&       operator&=(VQ L&, R);
7251   //        VQ L&       operator^=(VQ L&, R);
7252   //        VQ L&       operator|=(VQ L&, R);
7253   void addAssignmentIntegralOverloads() {
7254     if (!HasArithmeticOrEnumeralCandidateType)
7255       return;
7256 
7257     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7258       for (unsigned Right = FirstPromotedIntegralType;
7259            Right < LastPromotedIntegralType; ++Right) {
7260         QualType ParamTypes[2];
7261         ParamTypes[1] = getArithmeticType(Right);
7262 
7263         // Add this built-in operator as a candidate (VQ is empty).
7264         ParamTypes[0] =
7265           S.Context.getLValueReferenceType(getArithmeticType(Left));
7266         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7267         if (VisibleTypeConversionsQuals.hasVolatile()) {
7268           // Add this built-in operator as a candidate (VQ is 'volatile').
7269           ParamTypes[0] = getArithmeticType(Left);
7270           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7271           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7272           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7273                                 CandidateSet);
7274         }
7275       }
7276     }
7277   }
7278 
7279   // C++ [over.operator]p23:
7280   //
7281   //   There also exist candidate operator functions of the form
7282   //
7283   //        bool        operator!(bool);
7284   //        bool        operator&&(bool, bool);
7285   //        bool        operator||(bool, bool);
7286   void addExclaimOverload() {
7287     QualType ParamTy = S.Context.BoolTy;
7288     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7289                           /*IsAssignmentOperator=*/false,
7290                           /*NumContextualBoolArguments=*/1);
7291   }
7292   void addAmpAmpOrPipePipeOverload() {
7293     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7294     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7295                           /*IsAssignmentOperator=*/false,
7296                           /*NumContextualBoolArguments=*/2);
7297   }
7298 
7299   // C++ [over.built]p13:
7300   //
7301   //   For every cv-qualified or cv-unqualified object type T there
7302   //   exist candidate operator functions of the form
7303   //
7304   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7305   //        T&         operator[](T*, ptrdiff_t);
7306   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7307   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7308   //        T&         operator[](ptrdiff_t, T*);
7309   void addSubscriptOverloads() {
7310     for (BuiltinCandidateTypeSet::iterator
7311               Ptr = CandidateTypes[0].pointer_begin(),
7312            PtrEnd = CandidateTypes[0].pointer_end();
7313          Ptr != PtrEnd; ++Ptr) {
7314       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7315       QualType PointeeType = (*Ptr)->getPointeeType();
7316       if (!PointeeType->isObjectType())
7317         continue;
7318 
7319       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7320 
7321       // T& operator[](T*, ptrdiff_t)
7322       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7323     }
7324 
7325     for (BuiltinCandidateTypeSet::iterator
7326               Ptr = CandidateTypes[1].pointer_begin(),
7327            PtrEnd = CandidateTypes[1].pointer_end();
7328          Ptr != PtrEnd; ++Ptr) {
7329       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7330       QualType PointeeType = (*Ptr)->getPointeeType();
7331       if (!PointeeType->isObjectType())
7332         continue;
7333 
7334       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7335 
7336       // T& operator[](ptrdiff_t, T*)
7337       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7338     }
7339   }
7340 
7341   // C++ [over.built]p11:
7342   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7343   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7344   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7345   //    there exist candidate operator functions of the form
7346   //
7347   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7348   //
7349   //    where CV12 is the union of CV1 and CV2.
7350   void addArrowStarOverloads() {
7351     for (BuiltinCandidateTypeSet::iterator
7352              Ptr = CandidateTypes[0].pointer_begin(),
7353            PtrEnd = CandidateTypes[0].pointer_end();
7354          Ptr != PtrEnd; ++Ptr) {
7355       QualType C1Ty = (*Ptr);
7356       QualType C1;
7357       QualifierCollector Q1;
7358       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7359       if (!isa<RecordType>(C1))
7360         continue;
7361       // heuristic to reduce number of builtin candidates in the set.
7362       // Add volatile/restrict version only if there are conversions to a
7363       // volatile/restrict type.
7364       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7365         continue;
7366       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7367         continue;
7368       for (BuiltinCandidateTypeSet::iterator
7369                 MemPtr = CandidateTypes[1].member_pointer_begin(),
7370              MemPtrEnd = CandidateTypes[1].member_pointer_end();
7371            MemPtr != MemPtrEnd; ++MemPtr) {
7372         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7373         QualType C2 = QualType(mptr->getClass(), 0);
7374         C2 = C2.getUnqualifiedType();
7375         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7376           break;
7377         QualType ParamTypes[2] = { *Ptr, *MemPtr };
7378         // build CV12 T&
7379         QualType T = mptr->getPointeeType();
7380         if (!VisibleTypeConversionsQuals.hasVolatile() &&
7381             T.isVolatileQualified())
7382           continue;
7383         if (!VisibleTypeConversionsQuals.hasRestrict() &&
7384             T.isRestrictQualified())
7385           continue;
7386         T = Q1.apply(S.Context, T);
7387         QualType ResultTy = S.Context.getLValueReferenceType(T);
7388         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7389       }
7390     }
7391   }
7392 
7393   // Note that we don't consider the first argument, since it has been
7394   // contextually converted to bool long ago. The candidates below are
7395   // therefore added as binary.
7396   //
7397   // C++ [over.built]p25:
7398   //   For every type T, where T is a pointer, pointer-to-member, or scoped
7399   //   enumeration type, there exist candidate operator functions of the form
7400   //
7401   //        T        operator?(bool, T, T);
7402   //
7403   void addConditionalOperatorOverloads() {
7404     /// Set of (canonical) types that we've already handled.
7405     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7406 
7407     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7408       for (BuiltinCandidateTypeSet::iterator
7409                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7410              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7411            Ptr != PtrEnd; ++Ptr) {
7412         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7413           continue;
7414 
7415         QualType ParamTypes[2] = { *Ptr, *Ptr };
7416         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7417       }
7418 
7419       for (BuiltinCandidateTypeSet::iterator
7420                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7421              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7422            MemPtr != MemPtrEnd; ++MemPtr) {
7423         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7424           continue;
7425 
7426         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7427         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7428       }
7429 
7430       if (S.getLangOpts().CPlusPlus0x) {
7431         for (BuiltinCandidateTypeSet::iterator
7432                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7433                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7434              Enum != EnumEnd; ++Enum) {
7435           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7436             continue;
7437 
7438           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7439             continue;
7440 
7441           QualType ParamTypes[2] = { *Enum, *Enum };
7442           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7443         }
7444       }
7445     }
7446   }
7447 };
7448 
7449 } // end anonymous namespace
7450 
7451 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
7452 /// operator overloads to the candidate set (C++ [over.built]), based
7453 /// on the operator @p Op and the arguments given. For example, if the
7454 /// operator is a binary '+', this routine might add "int
7455 /// operator+(int, int)" to cover integer addition.
7456 void
7457 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7458                                    SourceLocation OpLoc,
7459                                    Expr **Args, unsigned NumArgs,
7460                                    OverloadCandidateSet& CandidateSet) {
7461   // Find all of the types that the arguments can convert to, but only
7462   // if the operator we're looking at has built-in operator candidates
7463   // that make use of these types. Also record whether we encounter non-record
7464   // candidate types or either arithmetic or enumeral candidate types.
7465   Qualifiers VisibleTypeConversionsQuals;
7466   VisibleTypeConversionsQuals.addConst();
7467   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7468     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7469 
7470   bool HasNonRecordCandidateType = false;
7471   bool HasArithmeticOrEnumeralCandidateType = false;
7472   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7473   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7474     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7475     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7476                                                  OpLoc,
7477                                                  true,
7478                                                  (Op == OO_Exclaim ||
7479                                                   Op == OO_AmpAmp ||
7480                                                   Op == OO_PipePipe),
7481                                                  VisibleTypeConversionsQuals);
7482     HasNonRecordCandidateType = HasNonRecordCandidateType ||
7483         CandidateTypes[ArgIdx].hasNonRecordTypes();
7484     HasArithmeticOrEnumeralCandidateType =
7485         HasArithmeticOrEnumeralCandidateType ||
7486         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7487   }
7488 
7489   // Exit early when no non-record types have been added to the candidate set
7490   // for any of the arguments to the operator.
7491   //
7492   // We can't exit early for !, ||, or &&, since there we have always have
7493   // 'bool' overloads.
7494   if (!HasNonRecordCandidateType &&
7495       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7496     return;
7497 
7498   // Setup an object to manage the common state for building overloads.
7499   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7500                                            VisibleTypeConversionsQuals,
7501                                            HasArithmeticOrEnumeralCandidateType,
7502                                            CandidateTypes, CandidateSet);
7503 
7504   // Dispatch over the operation to add in only those overloads which apply.
7505   switch (Op) {
7506   case OO_None:
7507   case NUM_OVERLOADED_OPERATORS:
7508     llvm_unreachable("Expected an overloaded operator");
7509 
7510   case OO_New:
7511   case OO_Delete:
7512   case OO_Array_New:
7513   case OO_Array_Delete:
7514   case OO_Call:
7515     llvm_unreachable(
7516                     "Special operators don't use AddBuiltinOperatorCandidates");
7517 
7518   case OO_Comma:
7519   case OO_Arrow:
7520     // C++ [over.match.oper]p3:
7521     //   -- For the operator ',', the unary operator '&', or the
7522     //      operator '->', the built-in candidates set is empty.
7523     break;
7524 
7525   case OO_Plus: // '+' is either unary or binary
7526     if (NumArgs == 1)
7527       OpBuilder.addUnaryPlusPointerOverloads();
7528     // Fall through.
7529 
7530   case OO_Minus: // '-' is either unary or binary
7531     if (NumArgs == 1) {
7532       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7533     } else {
7534       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7535       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7536     }
7537     break;
7538 
7539   case OO_Star: // '*' is either unary or binary
7540     if (NumArgs == 1)
7541       OpBuilder.addUnaryStarPointerOverloads();
7542     else
7543       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7544     break;
7545 
7546   case OO_Slash:
7547     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7548     break;
7549 
7550   case OO_PlusPlus:
7551   case OO_MinusMinus:
7552     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7553     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7554     break;
7555 
7556   case OO_EqualEqual:
7557   case OO_ExclaimEqual:
7558     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7559     // Fall through.
7560 
7561   case OO_Less:
7562   case OO_Greater:
7563   case OO_LessEqual:
7564   case OO_GreaterEqual:
7565     OpBuilder.addRelationalPointerOrEnumeralOverloads();
7566     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7567     break;
7568 
7569   case OO_Percent:
7570   case OO_Caret:
7571   case OO_Pipe:
7572   case OO_LessLess:
7573   case OO_GreaterGreater:
7574     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7575     break;
7576 
7577   case OO_Amp: // '&' is either unary or binary
7578     if (NumArgs == 1)
7579       // C++ [over.match.oper]p3:
7580       //   -- For the operator ',', the unary operator '&', or the
7581       //      operator '->', the built-in candidates set is empty.
7582       break;
7583 
7584     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7585     break;
7586 
7587   case OO_Tilde:
7588     OpBuilder.addUnaryTildePromotedIntegralOverloads();
7589     break;
7590 
7591   case OO_Equal:
7592     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7593     // Fall through.
7594 
7595   case OO_PlusEqual:
7596   case OO_MinusEqual:
7597     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7598     // Fall through.
7599 
7600   case OO_StarEqual:
7601   case OO_SlashEqual:
7602     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7603     break;
7604 
7605   case OO_PercentEqual:
7606   case OO_LessLessEqual:
7607   case OO_GreaterGreaterEqual:
7608   case OO_AmpEqual:
7609   case OO_CaretEqual:
7610   case OO_PipeEqual:
7611     OpBuilder.addAssignmentIntegralOverloads();
7612     break;
7613 
7614   case OO_Exclaim:
7615     OpBuilder.addExclaimOverload();
7616     break;
7617 
7618   case OO_AmpAmp:
7619   case OO_PipePipe:
7620     OpBuilder.addAmpAmpOrPipePipeOverload();
7621     break;
7622 
7623   case OO_Subscript:
7624     OpBuilder.addSubscriptOverloads();
7625     break;
7626 
7627   case OO_ArrowStar:
7628     OpBuilder.addArrowStarOverloads();
7629     break;
7630 
7631   case OO_Conditional:
7632     OpBuilder.addConditionalOperatorOverloads();
7633     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7634     break;
7635   }
7636 }
7637 
7638 /// \brief Add function candidates found via argument-dependent lookup
7639 /// to the set of overloading candidates.
7640 ///
7641 /// This routine performs argument-dependent name lookup based on the
7642 /// given function name (which may also be an operator name) and adds
7643 /// all of the overload candidates found by ADL to the overload
7644 /// candidate set (C++ [basic.lookup.argdep]).
7645 void
7646 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7647                                            bool Operator, SourceLocation Loc,
7648                                            llvm::ArrayRef<Expr *> Args,
7649                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7650                                            OverloadCandidateSet& CandidateSet,
7651                                            bool PartialOverloading,
7652                                            bool StdNamespaceIsAssociated) {
7653   ADLResult Fns;
7654 
7655   // FIXME: This approach for uniquing ADL results (and removing
7656   // redundant candidates from the set) relies on pointer-equality,
7657   // which means we need to key off the canonical decl.  However,
7658   // always going back to the canonical decl might not get us the
7659   // right set of default arguments.  What default arguments are
7660   // we supposed to consider on ADL candidates, anyway?
7661 
7662   // FIXME: Pass in the explicit template arguments?
7663   ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
7664                           StdNamespaceIsAssociated);
7665 
7666   // Erase all of the candidates we already knew about.
7667   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7668                                    CandEnd = CandidateSet.end();
7669        Cand != CandEnd; ++Cand)
7670     if (Cand->Function) {
7671       Fns.erase(Cand->Function);
7672       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7673         Fns.erase(FunTmpl);
7674     }
7675 
7676   // For each of the ADL candidates we found, add it to the overload
7677   // set.
7678   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7679     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7680     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7681       if (ExplicitTemplateArgs)
7682         continue;
7683 
7684       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7685                            PartialOverloading);
7686     } else
7687       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7688                                    FoundDecl, ExplicitTemplateArgs,
7689                                    Args, CandidateSet);
7690   }
7691 }
7692 
7693 /// isBetterOverloadCandidate - Determines whether the first overload
7694 /// candidate is a better candidate than the second (C++ 13.3.3p1).
7695 bool
7696 isBetterOverloadCandidate(Sema &S,
7697                           const OverloadCandidate &Cand1,
7698                           const OverloadCandidate &Cand2,
7699                           SourceLocation Loc,
7700                           bool UserDefinedConversion) {
7701   // Define viable functions to be better candidates than non-viable
7702   // functions.
7703   if (!Cand2.Viable)
7704     return Cand1.Viable;
7705   else if (!Cand1.Viable)
7706     return false;
7707 
7708   // C++ [over.match.best]p1:
7709   //
7710   //   -- if F is a static member function, ICS1(F) is defined such
7711   //      that ICS1(F) is neither better nor worse than ICS1(G) for
7712   //      any function G, and, symmetrically, ICS1(G) is neither
7713   //      better nor worse than ICS1(F).
7714   unsigned StartArg = 0;
7715   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7716     StartArg = 1;
7717 
7718   // C++ [over.match.best]p1:
7719   //   A viable function F1 is defined to be a better function than another
7720   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7721   //   conversion sequence than ICSi(F2), and then...
7722   unsigned NumArgs = Cand1.NumConversions;
7723   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7724   bool HasBetterConversion = false;
7725   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7726     switch (CompareImplicitConversionSequences(S,
7727                                                Cand1.Conversions[ArgIdx],
7728                                                Cand2.Conversions[ArgIdx])) {
7729     case ImplicitConversionSequence::Better:
7730       // Cand1 has a better conversion sequence.
7731       HasBetterConversion = true;
7732       break;
7733 
7734     case ImplicitConversionSequence::Worse:
7735       // Cand1 can't be better than Cand2.
7736       return false;
7737 
7738     case ImplicitConversionSequence::Indistinguishable:
7739       // Do nothing.
7740       break;
7741     }
7742   }
7743 
7744   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7745   //       ICSj(F2), or, if not that,
7746   if (HasBetterConversion)
7747     return true;
7748 
7749   //     - F1 is a non-template function and F2 is a function template
7750   //       specialization, or, if not that,
7751   if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7752       Cand2.Function && Cand2.Function->getPrimaryTemplate())
7753     return true;
7754 
7755   //   -- F1 and F2 are function template specializations, and the function
7756   //      template for F1 is more specialized than the template for F2
7757   //      according to the partial ordering rules described in 14.5.5.2, or,
7758   //      if not that,
7759   if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7760       Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7761     if (FunctionTemplateDecl *BetterTemplate
7762           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7763                                          Cand2.Function->getPrimaryTemplate(),
7764                                          Loc,
7765                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7766                                                              : TPOC_Call,
7767                                          Cand1.ExplicitCallArguments))
7768       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7769   }
7770 
7771   //   -- the context is an initialization by user-defined conversion
7772   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7773   //      from the return type of F1 to the destination type (i.e.,
7774   //      the type of the entity being initialized) is a better
7775   //      conversion sequence than the standard conversion sequence
7776   //      from the return type of F2 to the destination type.
7777   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7778       isa<CXXConversionDecl>(Cand1.Function) &&
7779       isa<CXXConversionDecl>(Cand2.Function)) {
7780     // First check whether we prefer one of the conversion functions over the
7781     // other. This only distinguishes the results in non-standard, extension
7782     // cases such as the conversion from a lambda closure type to a function
7783     // pointer or block.
7784     ImplicitConversionSequence::CompareKind FuncResult
7785       = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7786     if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7787       return FuncResult;
7788 
7789     switch (CompareStandardConversionSequences(S,
7790                                                Cand1.FinalConversion,
7791                                                Cand2.FinalConversion)) {
7792     case ImplicitConversionSequence::Better:
7793       // Cand1 has a better conversion sequence.
7794       return true;
7795 
7796     case ImplicitConversionSequence::Worse:
7797       // Cand1 can't be better than Cand2.
7798       return false;
7799 
7800     case ImplicitConversionSequence::Indistinguishable:
7801       // Do nothing
7802       break;
7803     }
7804   }
7805 
7806   return false;
7807 }
7808 
7809 /// \brief Computes the best viable function (C++ 13.3.3)
7810 /// within an overload candidate set.
7811 ///
7812 /// \param Loc The location of the function name (or operator symbol) for
7813 /// which overload resolution occurs.
7814 ///
7815 /// \param Best If overload resolution was successful or found a deleted
7816 /// function, \p Best points to the candidate function found.
7817 ///
7818 /// \returns The result of overload resolution.
7819 OverloadingResult
7820 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7821                                          iterator &Best,
7822                                          bool UserDefinedConversion) {
7823   // Find the best viable function.
7824   Best = end();
7825   for (iterator Cand = begin(); Cand != end(); ++Cand) {
7826     if (Cand->Viable)
7827       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7828                                                      UserDefinedConversion))
7829         Best = Cand;
7830   }
7831 
7832   // If we didn't find any viable functions, abort.
7833   if (Best == end())
7834     return OR_No_Viable_Function;
7835 
7836   // Make sure that this function is better than every other viable
7837   // function. If not, we have an ambiguity.
7838   for (iterator Cand = begin(); Cand != end(); ++Cand) {
7839     if (Cand->Viable &&
7840         Cand != Best &&
7841         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7842                                    UserDefinedConversion)) {
7843       Best = end();
7844       return OR_Ambiguous;
7845     }
7846   }
7847 
7848   // Best is the best viable function.
7849   if (Best->Function &&
7850       (Best->Function->isDeleted() ||
7851        S.isFunctionConsideredUnavailable(Best->Function)))
7852     return OR_Deleted;
7853 
7854   return OR_Success;
7855 }
7856 
7857 namespace {
7858 
7859 enum OverloadCandidateKind {
7860   oc_function,
7861   oc_method,
7862   oc_constructor,
7863   oc_function_template,
7864   oc_method_template,
7865   oc_constructor_template,
7866   oc_implicit_default_constructor,
7867   oc_implicit_copy_constructor,
7868   oc_implicit_move_constructor,
7869   oc_implicit_copy_assignment,
7870   oc_implicit_move_assignment,
7871   oc_implicit_inherited_constructor
7872 };
7873 
7874 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7875                                                 FunctionDecl *Fn,
7876                                                 std::string &Description) {
7877   bool isTemplate = false;
7878 
7879   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7880     isTemplate = true;
7881     Description = S.getTemplateArgumentBindingsText(
7882       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7883   }
7884 
7885   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7886     if (!Ctor->isImplicit())
7887       return isTemplate ? oc_constructor_template : oc_constructor;
7888 
7889     if (Ctor->getInheritedConstructor())
7890       return oc_implicit_inherited_constructor;
7891 
7892     if (Ctor->isDefaultConstructor())
7893       return oc_implicit_default_constructor;
7894 
7895     if (Ctor->isMoveConstructor())
7896       return oc_implicit_move_constructor;
7897 
7898     assert(Ctor->isCopyConstructor() &&
7899            "unexpected sort of implicit constructor");
7900     return oc_implicit_copy_constructor;
7901   }
7902 
7903   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7904     // This actually gets spelled 'candidate function' for now, but
7905     // it doesn't hurt to split it out.
7906     if (!Meth->isImplicit())
7907       return isTemplate ? oc_method_template : oc_method;
7908 
7909     if (Meth->isMoveAssignmentOperator())
7910       return oc_implicit_move_assignment;
7911 
7912     if (Meth->isCopyAssignmentOperator())
7913       return oc_implicit_copy_assignment;
7914 
7915     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7916     return oc_method;
7917   }
7918 
7919   return isTemplate ? oc_function_template : oc_function;
7920 }
7921 
7922 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7923   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7924   if (!Ctor) return;
7925 
7926   Ctor = Ctor->getInheritedConstructor();
7927   if (!Ctor) return;
7928 
7929   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7930 }
7931 
7932 } // end anonymous namespace
7933 
7934 // Notes the location of an overload candidate.
7935 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
7936   std::string FnDesc;
7937   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
7938   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7939                              << (unsigned) K << FnDesc;
7940   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7941   Diag(Fn->getLocation(), PD);
7942   MaybeEmitInheritedConstructorNote(*this, Fn);
7943 }
7944 
7945 //Notes the location of all overload candidates designated through
7946 // OverloadedExpr
7947 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
7948   assert(OverloadedExpr->getType() == Context.OverloadTy);
7949 
7950   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7951   OverloadExpr *OvlExpr = Ovl.Expression;
7952 
7953   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7954                             IEnd = OvlExpr->decls_end();
7955        I != IEnd; ++I) {
7956     if (FunctionTemplateDecl *FunTmpl =
7957                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7958       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
7959     } else if (FunctionDecl *Fun
7960                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7961       NoteOverloadCandidate(Fun, DestType);
7962     }
7963   }
7964 }
7965 
7966 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
7967 /// "lead" diagnostic; it will be given two arguments, the source and
7968 /// target types of the conversion.
7969 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7970                                  Sema &S,
7971                                  SourceLocation CaretLoc,
7972                                  const PartialDiagnostic &PDiag) const {
7973   S.Diag(CaretLoc, PDiag)
7974     << Ambiguous.getFromType() << Ambiguous.getToType();
7975   for (AmbiguousConversionSequence::const_iterator
7976          I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7977     S.NoteOverloadCandidate(*I);
7978   }
7979 }
7980 
7981 namespace {
7982 
7983 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7984   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7985   assert(Conv.isBad());
7986   assert(Cand->Function && "for now, candidate must be a function");
7987   FunctionDecl *Fn = Cand->Function;
7988 
7989   // There's a conversion slot for the object argument if this is a
7990   // non-constructor method.  Note that 'I' corresponds the
7991   // conversion-slot index.
7992   bool isObjectArgument = false;
7993   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
7994     if (I == 0)
7995       isObjectArgument = true;
7996     else
7997       I--;
7998   }
7999 
8000   std::string FnDesc;
8001   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8002 
8003   Expr *FromExpr = Conv.Bad.FromExpr;
8004   QualType FromTy = Conv.Bad.getFromType();
8005   QualType ToTy = Conv.Bad.getToType();
8006 
8007   if (FromTy == S.Context.OverloadTy) {
8008     assert(FromExpr && "overload set argument came from implicit argument?");
8009     Expr *E = FromExpr->IgnoreParens();
8010     if (isa<UnaryOperator>(E))
8011       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8012     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8013 
8014     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8015       << (unsigned) FnKind << FnDesc
8016       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8017       << ToTy << Name << I+1;
8018     MaybeEmitInheritedConstructorNote(S, Fn);
8019     return;
8020   }
8021 
8022   // Do some hand-waving analysis to see if the non-viability is due
8023   // to a qualifier mismatch.
8024   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8025   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8026   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8027     CToTy = RT->getPointeeType();
8028   else {
8029     // TODO: detect and diagnose the full richness of const mismatches.
8030     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8031       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8032         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8033   }
8034 
8035   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8036       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8037     Qualifiers FromQs = CFromTy.getQualifiers();
8038     Qualifiers ToQs = CToTy.getQualifiers();
8039 
8040     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8041       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8042         << (unsigned) FnKind << FnDesc
8043         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8044         << FromTy
8045         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8046         << (unsigned) isObjectArgument << I+1;
8047       MaybeEmitInheritedConstructorNote(S, Fn);
8048       return;
8049     }
8050 
8051     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8052       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8053         << (unsigned) FnKind << FnDesc
8054         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8055         << FromTy
8056         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8057         << (unsigned) isObjectArgument << I+1;
8058       MaybeEmitInheritedConstructorNote(S, Fn);
8059       return;
8060     }
8061 
8062     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8063       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8064       << (unsigned) FnKind << FnDesc
8065       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8066       << FromTy
8067       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8068       << (unsigned) isObjectArgument << I+1;
8069       MaybeEmitInheritedConstructorNote(S, Fn);
8070       return;
8071     }
8072 
8073     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8074     assert(CVR && "unexpected qualifiers mismatch");
8075 
8076     if (isObjectArgument) {
8077       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8078         << (unsigned) FnKind << FnDesc
8079         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8080         << FromTy << (CVR - 1);
8081     } else {
8082       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8083         << (unsigned) FnKind << FnDesc
8084         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8085         << FromTy << (CVR - 1) << I+1;
8086     }
8087     MaybeEmitInheritedConstructorNote(S, Fn);
8088     return;
8089   }
8090 
8091   // Special diagnostic for failure to convert an initializer list, since
8092   // telling the user that it has type void is not useful.
8093   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8094     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8095       << (unsigned) FnKind << FnDesc
8096       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8097       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8098     MaybeEmitInheritedConstructorNote(S, Fn);
8099     return;
8100   }
8101 
8102   // Diagnose references or pointers to incomplete types differently,
8103   // since it's far from impossible that the incompleteness triggered
8104   // the failure.
8105   QualType TempFromTy = FromTy.getNonReferenceType();
8106   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8107     TempFromTy = PTy->getPointeeType();
8108   if (TempFromTy->isIncompleteType()) {
8109     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8110       << (unsigned) FnKind << FnDesc
8111       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8112       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8113     MaybeEmitInheritedConstructorNote(S, Fn);
8114     return;
8115   }
8116 
8117   // Diagnose base -> derived pointer conversions.
8118   unsigned BaseToDerivedConversion = 0;
8119   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8120     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8121       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8122                                                FromPtrTy->getPointeeType()) &&
8123           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8124           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8125           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8126                           FromPtrTy->getPointeeType()))
8127         BaseToDerivedConversion = 1;
8128     }
8129   } else if (const ObjCObjectPointerType *FromPtrTy
8130                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8131     if (const ObjCObjectPointerType *ToPtrTy
8132                                         = ToTy->getAs<ObjCObjectPointerType>())
8133       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8134         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8135           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8136                                                 FromPtrTy->getPointeeType()) &&
8137               FromIface->isSuperClassOf(ToIface))
8138             BaseToDerivedConversion = 2;
8139   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8140     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8141         !FromTy->isIncompleteType() &&
8142         !ToRefTy->getPointeeType()->isIncompleteType() &&
8143         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8144       BaseToDerivedConversion = 3;
8145     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8146                ToTy.getNonReferenceType().getCanonicalType() ==
8147                FromTy.getNonReferenceType().getCanonicalType()) {
8148       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8149         << (unsigned) FnKind << FnDesc
8150         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8151         << (unsigned) isObjectArgument << I + 1;
8152       MaybeEmitInheritedConstructorNote(S, Fn);
8153       return;
8154     }
8155   }
8156 
8157   if (BaseToDerivedConversion) {
8158     S.Diag(Fn->getLocation(),
8159            diag::note_ovl_candidate_bad_base_to_derived_conv)
8160       << (unsigned) FnKind << FnDesc
8161       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8162       << (BaseToDerivedConversion - 1)
8163       << FromTy << ToTy << I+1;
8164     MaybeEmitInheritedConstructorNote(S, Fn);
8165     return;
8166   }
8167 
8168   if (isa<ObjCObjectPointerType>(CFromTy) &&
8169       isa<PointerType>(CToTy)) {
8170       Qualifiers FromQs = CFromTy.getQualifiers();
8171       Qualifiers ToQs = CToTy.getQualifiers();
8172       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8173         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8174         << (unsigned) FnKind << FnDesc
8175         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8176         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8177         MaybeEmitInheritedConstructorNote(S, Fn);
8178         return;
8179       }
8180   }
8181 
8182   // Emit the generic diagnostic and, optionally, add the hints to it.
8183   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8184   FDiag << (unsigned) FnKind << FnDesc
8185     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8186     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8187     << (unsigned) (Cand->Fix.Kind);
8188 
8189   // If we can fix the conversion, suggest the FixIts.
8190   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8191        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8192     FDiag << *HI;
8193   S.Diag(Fn->getLocation(), FDiag);
8194 
8195   MaybeEmitInheritedConstructorNote(S, Fn);
8196 }
8197 
8198 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8199                            unsigned NumFormalArgs) {
8200   // TODO: treat calls to a missing default constructor as a special case
8201 
8202   FunctionDecl *Fn = Cand->Function;
8203   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8204 
8205   unsigned MinParams = Fn->getMinRequiredArguments();
8206 
8207   // With invalid overloaded operators, it's possible that we think we
8208   // have an arity mismatch when it fact it looks like we have the
8209   // right number of arguments, because only overloaded operators have
8210   // the weird behavior of overloading member and non-member functions.
8211   // Just don't report anything.
8212   if (Fn->isInvalidDecl() &&
8213       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8214     return;
8215 
8216   // at least / at most / exactly
8217   unsigned mode, modeCount;
8218   if (NumFormalArgs < MinParams) {
8219     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8220            (Cand->FailureKind == ovl_fail_bad_deduction &&
8221             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8222     if (MinParams != FnTy->getNumArgs() ||
8223         FnTy->isVariadic() || FnTy->isTemplateVariadic())
8224       mode = 0; // "at least"
8225     else
8226       mode = 2; // "exactly"
8227     modeCount = MinParams;
8228   } else {
8229     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8230            (Cand->FailureKind == ovl_fail_bad_deduction &&
8231             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8232     if (MinParams != FnTy->getNumArgs())
8233       mode = 1; // "at most"
8234     else
8235       mode = 2; // "exactly"
8236     modeCount = FnTy->getNumArgs();
8237   }
8238 
8239   std::string Description;
8240   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8241 
8242   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8243     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8244       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8245       << Fn->getParamDecl(0) << NumFormalArgs;
8246   else
8247     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8248       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8249       << modeCount << NumFormalArgs;
8250   MaybeEmitInheritedConstructorNote(S, Fn);
8251 }
8252 
8253 /// Diagnose a failed template-argument deduction.
8254 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8255                           unsigned NumArgs) {
8256   FunctionDecl *Fn = Cand->Function; // pattern
8257 
8258   TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8259   NamedDecl *ParamD;
8260   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8261   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8262   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8263   switch (Cand->DeductionFailure.Result) {
8264   case Sema::TDK_Success:
8265     llvm_unreachable("TDK_success while diagnosing bad deduction");
8266 
8267   case Sema::TDK_Incomplete: {
8268     assert(ParamD && "no parameter found for incomplete deduction result");
8269     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8270       << ParamD->getDeclName();
8271     MaybeEmitInheritedConstructorNote(S, Fn);
8272     return;
8273   }
8274 
8275   case Sema::TDK_Underqualified: {
8276     assert(ParamD && "no parameter found for bad qualifiers deduction result");
8277     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8278 
8279     QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8280 
8281     // Param will have been canonicalized, but it should just be a
8282     // qualified version of ParamD, so move the qualifiers to that.
8283     QualifierCollector Qs;
8284     Qs.strip(Param);
8285     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8286     assert(S.Context.hasSameType(Param, NonCanonParam));
8287 
8288     // Arg has also been canonicalized, but there's nothing we can do
8289     // about that.  It also doesn't matter as much, because it won't
8290     // have any template parameters in it (because deduction isn't
8291     // done on dependent types).
8292     QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8293 
8294     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8295       << ParamD->getDeclName() << Arg << NonCanonParam;
8296     MaybeEmitInheritedConstructorNote(S, Fn);
8297     return;
8298   }
8299 
8300   case Sema::TDK_Inconsistent: {
8301     assert(ParamD && "no parameter found for inconsistent deduction result");
8302     int which = 0;
8303     if (isa<TemplateTypeParmDecl>(ParamD))
8304       which = 0;
8305     else if (isa<NonTypeTemplateParmDecl>(ParamD))
8306       which = 1;
8307     else {
8308       which = 2;
8309     }
8310 
8311     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8312       << which << ParamD->getDeclName()
8313       << *Cand->DeductionFailure.getFirstArg()
8314       << *Cand->DeductionFailure.getSecondArg();
8315     MaybeEmitInheritedConstructorNote(S, Fn);
8316     return;
8317   }
8318 
8319   case Sema::TDK_InvalidExplicitArguments:
8320     assert(ParamD && "no parameter found for invalid explicit arguments");
8321     if (ParamD->getDeclName())
8322       S.Diag(Fn->getLocation(),
8323              diag::note_ovl_candidate_explicit_arg_mismatch_named)
8324         << ParamD->getDeclName();
8325     else {
8326       int index = 0;
8327       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8328         index = TTP->getIndex();
8329       else if (NonTypeTemplateParmDecl *NTTP
8330                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8331         index = NTTP->getIndex();
8332       else
8333         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8334       S.Diag(Fn->getLocation(),
8335              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8336         << (index + 1);
8337     }
8338     MaybeEmitInheritedConstructorNote(S, Fn);
8339     return;
8340 
8341   case Sema::TDK_TooManyArguments:
8342   case Sema::TDK_TooFewArguments:
8343     DiagnoseArityMismatch(S, Cand, NumArgs);
8344     return;
8345 
8346   case Sema::TDK_InstantiationDepth:
8347     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8348     MaybeEmitInheritedConstructorNote(S, Fn);
8349     return;
8350 
8351   case Sema::TDK_SubstitutionFailure: {
8352     // Format the template argument list into the argument string.
8353     llvm::SmallString<128> TemplateArgString;
8354     if (TemplateArgumentList *Args =
8355           Cand->DeductionFailure.getTemplateArgumentList()) {
8356       TemplateArgString = " ";
8357       TemplateArgString += S.getTemplateArgumentBindingsText(
8358           Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8359     }
8360 
8361     // If this candidate was disabled by enable_if, say so.
8362     PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8363     if (PDiag && PDiag->second.getDiagID() ==
8364           diag::err_typename_nested_not_found_enable_if) {
8365       // FIXME: Use the source range of the condition, and the fully-qualified
8366       //        name of the enable_if template. These are both present in PDiag.
8367       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8368         << "'enable_if'" << TemplateArgString;
8369       return;
8370     }
8371 
8372     // Format the SFINAE diagnostic into the argument string.
8373     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8374     //        formatted message in another diagnostic.
8375     llvm::SmallString<128> SFINAEArgString;
8376     SourceRange R;
8377     if (PDiag) {
8378       SFINAEArgString = ": ";
8379       R = SourceRange(PDiag->first, PDiag->first);
8380       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8381     }
8382 
8383     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8384       << TemplateArgString << SFINAEArgString << R;
8385     MaybeEmitInheritedConstructorNote(S, Fn);
8386     return;
8387   }
8388 
8389   // TODO: diagnose these individually, then kill off
8390   // note_ovl_candidate_bad_deduction, which is uselessly vague.
8391   case Sema::TDK_NonDeducedMismatch:
8392   case Sema::TDK_FailedOverloadResolution:
8393     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8394     MaybeEmitInheritedConstructorNote(S, Fn);
8395     return;
8396   }
8397 }
8398 
8399 /// CUDA: diagnose an invalid call across targets.
8400 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8401   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8402   FunctionDecl *Callee = Cand->Function;
8403 
8404   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8405                            CalleeTarget = S.IdentifyCUDATarget(Callee);
8406 
8407   std::string FnDesc;
8408   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8409 
8410   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8411       << (unsigned) FnKind << CalleeTarget << CallerTarget;
8412 }
8413 
8414 /// Generates a 'note' diagnostic for an overload candidate.  We've
8415 /// already generated a primary error at the call site.
8416 ///
8417 /// It really does need to be a single diagnostic with its caret
8418 /// pointed at the candidate declaration.  Yes, this creates some
8419 /// major challenges of technical writing.  Yes, this makes pointing
8420 /// out problems with specific arguments quite awkward.  It's still
8421 /// better than generating twenty screens of text for every failed
8422 /// overload.
8423 ///
8424 /// It would be great to be able to express per-candidate problems
8425 /// more richly for those diagnostic clients that cared, but we'd
8426 /// still have to be just as careful with the default diagnostics.
8427 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8428                            unsigned NumArgs) {
8429   FunctionDecl *Fn = Cand->Function;
8430 
8431   // Note deleted candidates, but only if they're viable.
8432   if (Cand->Viable && (Fn->isDeleted() ||
8433       S.isFunctionConsideredUnavailable(Fn))) {
8434     std::string FnDesc;
8435     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8436 
8437     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8438       << FnKind << FnDesc
8439       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8440     MaybeEmitInheritedConstructorNote(S, Fn);
8441     return;
8442   }
8443 
8444   // We don't really have anything else to say about viable candidates.
8445   if (Cand->Viable) {
8446     S.NoteOverloadCandidate(Fn);
8447     return;
8448   }
8449 
8450   switch (Cand->FailureKind) {
8451   case ovl_fail_too_many_arguments:
8452   case ovl_fail_too_few_arguments:
8453     return DiagnoseArityMismatch(S, Cand, NumArgs);
8454 
8455   case ovl_fail_bad_deduction:
8456     return DiagnoseBadDeduction(S, Cand, NumArgs);
8457 
8458   case ovl_fail_trivial_conversion:
8459   case ovl_fail_bad_final_conversion:
8460   case ovl_fail_final_conversion_not_exact:
8461     return S.NoteOverloadCandidate(Fn);
8462 
8463   case ovl_fail_bad_conversion: {
8464     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8465     for (unsigned N = Cand->NumConversions; I != N; ++I)
8466       if (Cand->Conversions[I].isBad())
8467         return DiagnoseBadConversion(S, Cand, I);
8468 
8469     // FIXME: this currently happens when we're called from SemaInit
8470     // when user-conversion overload fails.  Figure out how to handle
8471     // those conditions and diagnose them well.
8472     return S.NoteOverloadCandidate(Fn);
8473   }
8474 
8475   case ovl_fail_bad_target:
8476     return DiagnoseBadTarget(S, Cand);
8477   }
8478 }
8479 
8480 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8481   // Desugar the type of the surrogate down to a function type,
8482   // retaining as many typedefs as possible while still showing
8483   // the function type (and, therefore, its parameter types).
8484   QualType FnType = Cand->Surrogate->getConversionType();
8485   bool isLValueReference = false;
8486   bool isRValueReference = false;
8487   bool isPointer = false;
8488   if (const LValueReferenceType *FnTypeRef =
8489         FnType->getAs<LValueReferenceType>()) {
8490     FnType = FnTypeRef->getPointeeType();
8491     isLValueReference = true;
8492   } else if (const RValueReferenceType *FnTypeRef =
8493                FnType->getAs<RValueReferenceType>()) {
8494     FnType = FnTypeRef->getPointeeType();
8495     isRValueReference = true;
8496   }
8497   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8498     FnType = FnTypePtr->getPointeeType();
8499     isPointer = true;
8500   }
8501   // Desugar down to a function type.
8502   FnType = QualType(FnType->getAs<FunctionType>(), 0);
8503   // Reconstruct the pointer/reference as appropriate.
8504   if (isPointer) FnType = S.Context.getPointerType(FnType);
8505   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8506   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8507 
8508   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8509     << FnType;
8510   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8511 }
8512 
8513 void NoteBuiltinOperatorCandidate(Sema &S,
8514                                   const char *Opc,
8515                                   SourceLocation OpLoc,
8516                                   OverloadCandidate *Cand) {
8517   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8518   std::string TypeStr("operator");
8519   TypeStr += Opc;
8520   TypeStr += "(";
8521   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8522   if (Cand->NumConversions == 1) {
8523     TypeStr += ")";
8524     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8525   } else {
8526     TypeStr += ", ";
8527     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8528     TypeStr += ")";
8529     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8530   }
8531 }
8532 
8533 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8534                                   OverloadCandidate *Cand) {
8535   unsigned NoOperands = Cand->NumConversions;
8536   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8537     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8538     if (ICS.isBad()) break; // all meaningless after first invalid
8539     if (!ICS.isAmbiguous()) continue;
8540 
8541     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8542                               S.PDiag(diag::note_ambiguous_type_conversion));
8543   }
8544 }
8545 
8546 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8547   if (Cand->Function)
8548     return Cand->Function->getLocation();
8549   if (Cand->IsSurrogate)
8550     return Cand->Surrogate->getLocation();
8551   return SourceLocation();
8552 }
8553 
8554 static unsigned
8555 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8556   switch ((Sema::TemplateDeductionResult)DFI.Result) {
8557   case Sema::TDK_Success:
8558     llvm_unreachable("TDK_success while diagnosing bad deduction");
8559 
8560   case Sema::TDK_Incomplete:
8561     return 1;
8562 
8563   case Sema::TDK_Underqualified:
8564   case Sema::TDK_Inconsistent:
8565     return 2;
8566 
8567   case Sema::TDK_SubstitutionFailure:
8568   case Sema::TDK_NonDeducedMismatch:
8569     return 3;
8570 
8571   case Sema::TDK_InstantiationDepth:
8572   case Sema::TDK_FailedOverloadResolution:
8573     return 4;
8574 
8575   case Sema::TDK_InvalidExplicitArguments:
8576     return 5;
8577 
8578   case Sema::TDK_TooManyArguments:
8579   case Sema::TDK_TooFewArguments:
8580     return 6;
8581   }
8582   llvm_unreachable("Unhandled deduction result");
8583 }
8584 
8585 struct CompareOverloadCandidatesForDisplay {
8586   Sema &S;
8587   CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8588 
8589   bool operator()(const OverloadCandidate *L,
8590                   const OverloadCandidate *R) {
8591     // Fast-path this check.
8592     if (L == R) return false;
8593 
8594     // Order first by viability.
8595     if (L->Viable) {
8596       if (!R->Viable) return true;
8597 
8598       // TODO: introduce a tri-valued comparison for overload
8599       // candidates.  Would be more worthwhile if we had a sort
8600       // that could exploit it.
8601       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8602       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8603     } else if (R->Viable)
8604       return false;
8605 
8606     assert(L->Viable == R->Viable);
8607 
8608     // Criteria by which we can sort non-viable candidates:
8609     if (!L->Viable) {
8610       // 1. Arity mismatches come after other candidates.
8611       if (L->FailureKind == ovl_fail_too_many_arguments ||
8612           L->FailureKind == ovl_fail_too_few_arguments)
8613         return false;
8614       if (R->FailureKind == ovl_fail_too_many_arguments ||
8615           R->FailureKind == ovl_fail_too_few_arguments)
8616         return true;
8617 
8618       // 2. Bad conversions come first and are ordered by the number
8619       // of bad conversions and quality of good conversions.
8620       if (L->FailureKind == ovl_fail_bad_conversion) {
8621         if (R->FailureKind != ovl_fail_bad_conversion)
8622           return true;
8623 
8624         // The conversion that can be fixed with a smaller number of changes,
8625         // comes first.
8626         unsigned numLFixes = L->Fix.NumConversionsFixed;
8627         unsigned numRFixes = R->Fix.NumConversionsFixed;
8628         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8629         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8630         if (numLFixes != numRFixes) {
8631           if (numLFixes < numRFixes)
8632             return true;
8633           else
8634             return false;
8635         }
8636 
8637         // If there's any ordering between the defined conversions...
8638         // FIXME: this might not be transitive.
8639         assert(L->NumConversions == R->NumConversions);
8640 
8641         int leftBetter = 0;
8642         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8643         for (unsigned E = L->NumConversions; I != E; ++I) {
8644           switch (CompareImplicitConversionSequences(S,
8645                                                      L->Conversions[I],
8646                                                      R->Conversions[I])) {
8647           case ImplicitConversionSequence::Better:
8648             leftBetter++;
8649             break;
8650 
8651           case ImplicitConversionSequence::Worse:
8652             leftBetter--;
8653             break;
8654 
8655           case ImplicitConversionSequence::Indistinguishable:
8656             break;
8657           }
8658         }
8659         if (leftBetter > 0) return true;
8660         if (leftBetter < 0) return false;
8661 
8662       } else if (R->FailureKind == ovl_fail_bad_conversion)
8663         return false;
8664 
8665       if (L->FailureKind == ovl_fail_bad_deduction) {
8666         if (R->FailureKind != ovl_fail_bad_deduction)
8667           return true;
8668 
8669         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8670           return RankDeductionFailure(L->DeductionFailure)
8671                < RankDeductionFailure(R->DeductionFailure);
8672       } else if (R->FailureKind == ovl_fail_bad_deduction)
8673         return false;
8674 
8675       // TODO: others?
8676     }
8677 
8678     // Sort everything else by location.
8679     SourceLocation LLoc = GetLocationForCandidate(L);
8680     SourceLocation RLoc = GetLocationForCandidate(R);
8681 
8682     // Put candidates without locations (e.g. builtins) at the end.
8683     if (LLoc.isInvalid()) return false;
8684     if (RLoc.isInvalid()) return true;
8685 
8686     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8687   }
8688 };
8689 
8690 /// CompleteNonViableCandidate - Normally, overload resolution only
8691 /// computes up to the first. Produces the FixIt set if possible.
8692 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8693                                 llvm::ArrayRef<Expr *> Args) {
8694   assert(!Cand->Viable);
8695 
8696   // Don't do anything on failures other than bad conversion.
8697   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8698 
8699   // We only want the FixIts if all the arguments can be corrected.
8700   bool Unfixable = false;
8701   // Use a implicit copy initialization to check conversion fixes.
8702   Cand->Fix.setConversionChecker(TryCopyInitialization);
8703 
8704   // Skip forward to the first bad conversion.
8705   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8706   unsigned ConvCount = Cand->NumConversions;
8707   while (true) {
8708     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8709     ConvIdx++;
8710     if (Cand->Conversions[ConvIdx - 1].isBad()) {
8711       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8712       break;
8713     }
8714   }
8715 
8716   if (ConvIdx == ConvCount)
8717     return;
8718 
8719   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8720          "remaining conversion is initialized?");
8721 
8722   // FIXME: this should probably be preserved from the overload
8723   // operation somehow.
8724   bool SuppressUserConversions = false;
8725 
8726   const FunctionProtoType* Proto;
8727   unsigned ArgIdx = ConvIdx;
8728 
8729   if (Cand->IsSurrogate) {
8730     QualType ConvType
8731       = Cand->Surrogate->getConversionType().getNonReferenceType();
8732     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8733       ConvType = ConvPtrType->getPointeeType();
8734     Proto = ConvType->getAs<FunctionProtoType>();
8735     ArgIdx--;
8736   } else if (Cand->Function) {
8737     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8738     if (isa<CXXMethodDecl>(Cand->Function) &&
8739         !isa<CXXConstructorDecl>(Cand->Function))
8740       ArgIdx--;
8741   } else {
8742     // Builtin binary operator with a bad first conversion.
8743     assert(ConvCount <= 3);
8744     for (; ConvIdx != ConvCount; ++ConvIdx)
8745       Cand->Conversions[ConvIdx]
8746         = TryCopyInitialization(S, Args[ConvIdx],
8747                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
8748                                 SuppressUserConversions,
8749                                 /*InOverloadResolution*/ true,
8750                                 /*AllowObjCWritebackConversion=*/
8751                                   S.getLangOpts().ObjCAutoRefCount);
8752     return;
8753   }
8754 
8755   // Fill in the rest of the conversions.
8756   unsigned NumArgsInProto = Proto->getNumArgs();
8757   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8758     if (ArgIdx < NumArgsInProto) {
8759       Cand->Conversions[ConvIdx]
8760         = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8761                                 SuppressUserConversions,
8762                                 /*InOverloadResolution=*/true,
8763                                 /*AllowObjCWritebackConversion=*/
8764                                   S.getLangOpts().ObjCAutoRefCount);
8765       // Store the FixIt in the candidate if it exists.
8766       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8767         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8768     }
8769     else
8770       Cand->Conversions[ConvIdx].setEllipsis();
8771   }
8772 }
8773 
8774 } // end anonymous namespace
8775 
8776 /// PrintOverloadCandidates - When overload resolution fails, prints
8777 /// diagnostic messages containing the candidates in the candidate
8778 /// set.
8779 void OverloadCandidateSet::NoteCandidates(Sema &S,
8780                                           OverloadCandidateDisplayKind OCD,
8781                                           llvm::ArrayRef<Expr *> Args,
8782                                           const char *Opc,
8783                                           SourceLocation OpLoc) {
8784   // Sort the candidates by viability and position.  Sorting directly would
8785   // be prohibitive, so we make a set of pointers and sort those.
8786   SmallVector<OverloadCandidate*, 32> Cands;
8787   if (OCD == OCD_AllCandidates) Cands.reserve(size());
8788   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8789     if (Cand->Viable)
8790       Cands.push_back(Cand);
8791     else if (OCD == OCD_AllCandidates) {
8792       CompleteNonViableCandidate(S, Cand, Args);
8793       if (Cand->Function || Cand->IsSurrogate)
8794         Cands.push_back(Cand);
8795       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8796       // want to list every possible builtin candidate.
8797     }
8798   }
8799 
8800   std::sort(Cands.begin(), Cands.end(),
8801             CompareOverloadCandidatesForDisplay(S));
8802 
8803   bool ReportedAmbiguousConversions = false;
8804 
8805   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8806   const DiagnosticsEngine::OverloadsShown ShowOverloads =
8807       S.Diags.getShowOverloads();
8808   unsigned CandsShown = 0;
8809   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8810     OverloadCandidate *Cand = *I;
8811 
8812     // Set an arbitrary limit on the number of candidate functions we'll spam
8813     // the user with.  FIXME: This limit should depend on details of the
8814     // candidate list.
8815     if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
8816       break;
8817     }
8818     ++CandsShown;
8819 
8820     if (Cand->Function)
8821       NoteFunctionCandidate(S, Cand, Args.size());
8822     else if (Cand->IsSurrogate)
8823       NoteSurrogateCandidate(S, Cand);
8824     else {
8825       assert(Cand->Viable &&
8826              "Non-viable built-in candidates are not added to Cands.");
8827       // Generally we only see ambiguities including viable builtin
8828       // operators if overload resolution got screwed up by an
8829       // ambiguous user-defined conversion.
8830       //
8831       // FIXME: It's quite possible for different conversions to see
8832       // different ambiguities, though.
8833       if (!ReportedAmbiguousConversions) {
8834         NoteAmbiguousUserConversions(S, OpLoc, Cand);
8835         ReportedAmbiguousConversions = true;
8836       }
8837 
8838       // If this is a viable builtin, print it.
8839       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8840     }
8841   }
8842 
8843   if (I != E)
8844     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8845 }
8846 
8847 // [PossiblyAFunctionType]  -->   [Return]
8848 // NonFunctionType --> NonFunctionType
8849 // R (A) --> R(A)
8850 // R (*)(A) --> R (A)
8851 // R (&)(A) --> R (A)
8852 // R (S::*)(A) --> R (A)
8853 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8854   QualType Ret = PossiblyAFunctionType;
8855   if (const PointerType *ToTypePtr =
8856     PossiblyAFunctionType->getAs<PointerType>())
8857     Ret = ToTypePtr->getPointeeType();
8858   else if (const ReferenceType *ToTypeRef =
8859     PossiblyAFunctionType->getAs<ReferenceType>())
8860     Ret = ToTypeRef->getPointeeType();
8861   else if (const MemberPointerType *MemTypePtr =
8862     PossiblyAFunctionType->getAs<MemberPointerType>())
8863     Ret = MemTypePtr->getPointeeType();
8864   Ret =
8865     Context.getCanonicalType(Ret).getUnqualifiedType();
8866   return Ret;
8867 }
8868 
8869 // A helper class to help with address of function resolution
8870 // - allows us to avoid passing around all those ugly parameters
8871 class AddressOfFunctionResolver
8872 {
8873   Sema& S;
8874   Expr* SourceExpr;
8875   const QualType& TargetType;
8876   QualType TargetFunctionType; // Extracted function type from target type
8877 
8878   bool Complain;
8879   //DeclAccessPair& ResultFunctionAccessPair;
8880   ASTContext& Context;
8881 
8882   bool TargetTypeIsNonStaticMemberFunction;
8883   bool FoundNonTemplateFunction;
8884 
8885   OverloadExpr::FindResult OvlExprInfo;
8886   OverloadExpr *OvlExpr;
8887   TemplateArgumentListInfo OvlExplicitTemplateArgs;
8888   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
8889 
8890 public:
8891   AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8892                             const QualType& TargetType, bool Complain)
8893     : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8894       Complain(Complain), Context(S.getASTContext()),
8895       TargetTypeIsNonStaticMemberFunction(
8896                                     !!TargetType->getAs<MemberPointerType>()),
8897       FoundNonTemplateFunction(false),
8898       OvlExprInfo(OverloadExpr::find(SourceExpr)),
8899       OvlExpr(OvlExprInfo.Expression)
8900   {
8901     ExtractUnqualifiedFunctionTypeFromTargetType();
8902 
8903     if (!TargetFunctionType->isFunctionType()) {
8904       if (OvlExpr->hasExplicitTemplateArgs()) {
8905         DeclAccessPair dap;
8906         if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
8907                                             OvlExpr, false, &dap) ) {
8908 
8909           if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8910             if (!Method->isStatic()) {
8911               // If the target type is a non-function type and the function
8912               // found is a non-static member function, pretend as if that was
8913               // the target, it's the only possible type to end up with.
8914               TargetTypeIsNonStaticMemberFunction = true;
8915 
8916               // And skip adding the function if its not in the proper form.
8917               // We'll diagnose this due to an empty set of functions.
8918               if (!OvlExprInfo.HasFormOfMemberPointer)
8919                 return;
8920             }
8921           }
8922 
8923           Matches.push_back(std::make_pair(dap,Fn));
8924         }
8925       }
8926       return;
8927     }
8928 
8929     if (OvlExpr->hasExplicitTemplateArgs())
8930       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
8931 
8932     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8933       // C++ [over.over]p4:
8934       //   If more than one function is selected, [...]
8935       if (Matches.size() > 1) {
8936         if (FoundNonTemplateFunction)
8937           EliminateAllTemplateMatches();
8938         else
8939           EliminateAllExceptMostSpecializedTemplate();
8940       }
8941     }
8942   }
8943 
8944 private:
8945   bool isTargetTypeAFunction() const {
8946     return TargetFunctionType->isFunctionType();
8947   }
8948 
8949   // [ToType]     [Return]
8950 
8951   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8952   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8953   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8954   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8955     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8956   }
8957 
8958   // return true if any matching specializations were found
8959   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8960                                    const DeclAccessPair& CurAccessFunPair) {
8961     if (CXXMethodDecl *Method
8962               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8963       // Skip non-static function templates when converting to pointer, and
8964       // static when converting to member pointer.
8965       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8966         return false;
8967     }
8968     else if (TargetTypeIsNonStaticMemberFunction)
8969       return false;
8970 
8971     // C++ [over.over]p2:
8972     //   If the name is a function template, template argument deduction is
8973     //   done (14.8.2.2), and if the argument deduction succeeds, the
8974     //   resulting template argument list is used to generate a single
8975     //   function template specialization, which is added to the set of
8976     //   overloaded functions considered.
8977     FunctionDecl *Specialization = 0;
8978     TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8979     if (Sema::TemplateDeductionResult Result
8980           = S.DeduceTemplateArguments(FunctionTemplate,
8981                                       &OvlExplicitTemplateArgs,
8982                                       TargetFunctionType, Specialization,
8983                                       Info)) {
8984       // FIXME: make a note of the failed deduction for diagnostics.
8985       (void)Result;
8986       return false;
8987     }
8988 
8989     // Template argument deduction ensures that we have an exact match.
8990     // This function template specicalization works.
8991     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8992     assert(TargetFunctionType
8993                       == Context.getCanonicalType(Specialization->getType()));
8994     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8995     return true;
8996   }
8997 
8998   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8999                                       const DeclAccessPair& CurAccessFunPair) {
9000     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9001       // Skip non-static functions when converting to pointer, and static
9002       // when converting to member pointer.
9003       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9004         return false;
9005     }
9006     else if (TargetTypeIsNonStaticMemberFunction)
9007       return false;
9008 
9009     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9010       if (S.getLangOpts().CUDA)
9011         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9012           if (S.CheckCUDATarget(Caller, FunDecl))
9013             return false;
9014 
9015       QualType ResultTy;
9016       if (Context.hasSameUnqualifiedType(TargetFunctionType,
9017                                          FunDecl->getType()) ||
9018           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9019                                  ResultTy)) {
9020         Matches.push_back(std::make_pair(CurAccessFunPair,
9021           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9022         FoundNonTemplateFunction = true;
9023         return true;
9024       }
9025     }
9026 
9027     return false;
9028   }
9029 
9030   bool FindAllFunctionsThatMatchTargetTypeExactly() {
9031     bool Ret = false;
9032 
9033     // If the overload expression doesn't have the form of a pointer to
9034     // member, don't try to convert it to a pointer-to-member type.
9035     if (IsInvalidFormOfPointerToMemberFunction())
9036       return false;
9037 
9038     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9039                                E = OvlExpr->decls_end();
9040          I != E; ++I) {
9041       // Look through any using declarations to find the underlying function.
9042       NamedDecl *Fn = (*I)->getUnderlyingDecl();
9043 
9044       // C++ [over.over]p3:
9045       //   Non-member functions and static member functions match
9046       //   targets of type "pointer-to-function" or "reference-to-function."
9047       //   Nonstatic member functions match targets of
9048       //   type "pointer-to-member-function."
9049       // Note that according to DR 247, the containing class does not matter.
9050       if (FunctionTemplateDecl *FunctionTemplate
9051                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
9052         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9053           Ret = true;
9054       }
9055       // If we have explicit template arguments supplied, skip non-templates.
9056       else if (!OvlExpr->hasExplicitTemplateArgs() &&
9057                AddMatchingNonTemplateFunction(Fn, I.getPair()))
9058         Ret = true;
9059     }
9060     assert(Ret || Matches.empty());
9061     return Ret;
9062   }
9063 
9064   void EliminateAllExceptMostSpecializedTemplate() {
9065     //   [...] and any given function template specialization F1 is
9066     //   eliminated if the set contains a second function template
9067     //   specialization whose function template is more specialized
9068     //   than the function template of F1 according to the partial
9069     //   ordering rules of 14.5.5.2.
9070 
9071     // The algorithm specified above is quadratic. We instead use a
9072     // two-pass algorithm (similar to the one used to identify the
9073     // best viable function in an overload set) that identifies the
9074     // best function template (if it exists).
9075 
9076     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9077     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9078       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9079 
9080     UnresolvedSetIterator Result =
9081       S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9082                            TPOC_Other, 0, SourceExpr->getLocStart(),
9083                            S.PDiag(),
9084                            S.PDiag(diag::err_addr_ovl_ambiguous)
9085                              << Matches[0].second->getDeclName(),
9086                            S.PDiag(diag::note_ovl_candidate)
9087                              << (unsigned) oc_function_template,
9088                            Complain, TargetFunctionType);
9089 
9090     if (Result != MatchesCopy.end()) {
9091       // Make it the first and only element
9092       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9093       Matches[0].second = cast<FunctionDecl>(*Result);
9094       Matches.resize(1);
9095     }
9096   }
9097 
9098   void EliminateAllTemplateMatches() {
9099     //   [...] any function template specializations in the set are
9100     //   eliminated if the set also contains a non-template function, [...]
9101     for (unsigned I = 0, N = Matches.size(); I != N; ) {
9102       if (Matches[I].second->getPrimaryTemplate() == 0)
9103         ++I;
9104       else {
9105         Matches[I] = Matches[--N];
9106         Matches.set_size(N);
9107       }
9108     }
9109   }
9110 
9111 public:
9112   void ComplainNoMatchesFound() const {
9113     assert(Matches.empty());
9114     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9115         << OvlExpr->getName() << TargetFunctionType
9116         << OvlExpr->getSourceRange();
9117     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9118   }
9119 
9120   bool IsInvalidFormOfPointerToMemberFunction() const {
9121     return TargetTypeIsNonStaticMemberFunction &&
9122       !OvlExprInfo.HasFormOfMemberPointer;
9123   }
9124 
9125   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9126       // TODO: Should we condition this on whether any functions might
9127       // have matched, or is it more appropriate to do that in callers?
9128       // TODO: a fixit wouldn't hurt.
9129       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9130         << TargetType << OvlExpr->getSourceRange();
9131   }
9132 
9133   void ComplainOfInvalidConversion() const {
9134     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9135       << OvlExpr->getName() << TargetType;
9136   }
9137 
9138   void ComplainMultipleMatchesFound() const {
9139     assert(Matches.size() > 1);
9140     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9141       << OvlExpr->getName()
9142       << OvlExpr->getSourceRange();
9143     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9144   }
9145 
9146   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9147 
9148   int getNumMatches() const { return Matches.size(); }
9149 
9150   FunctionDecl* getMatchingFunctionDecl() const {
9151     if (Matches.size() != 1) return 0;
9152     return Matches[0].second;
9153   }
9154 
9155   const DeclAccessPair* getMatchingFunctionAccessPair() const {
9156     if (Matches.size() != 1) return 0;
9157     return &Matches[0].first;
9158   }
9159 };
9160 
9161 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9162 /// an overloaded function (C++ [over.over]), where @p From is an
9163 /// expression with overloaded function type and @p ToType is the type
9164 /// we're trying to resolve to. For example:
9165 ///
9166 /// @code
9167 /// int f(double);
9168 /// int f(int);
9169 ///
9170 /// int (*pfd)(double) = f; // selects f(double)
9171 /// @endcode
9172 ///
9173 /// This routine returns the resulting FunctionDecl if it could be
9174 /// resolved, and NULL otherwise. When @p Complain is true, this
9175 /// routine will emit diagnostics if there is an error.
9176 FunctionDecl *
9177 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9178                                          QualType TargetType,
9179                                          bool Complain,
9180                                          DeclAccessPair &FoundResult,
9181                                          bool *pHadMultipleCandidates) {
9182   assert(AddressOfExpr->getType() == Context.OverloadTy);
9183 
9184   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9185                                      Complain);
9186   int NumMatches = Resolver.getNumMatches();
9187   FunctionDecl* Fn = 0;
9188   if (NumMatches == 0 && Complain) {
9189     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9190       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9191     else
9192       Resolver.ComplainNoMatchesFound();
9193   }
9194   else if (NumMatches > 1 && Complain)
9195     Resolver.ComplainMultipleMatchesFound();
9196   else if (NumMatches == 1) {
9197     Fn = Resolver.getMatchingFunctionDecl();
9198     assert(Fn);
9199     FoundResult = *Resolver.getMatchingFunctionAccessPair();
9200     MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
9201     if (Complain)
9202       CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9203   }
9204 
9205   if (pHadMultipleCandidates)
9206     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9207   return Fn;
9208 }
9209 
9210 /// \brief Given an expression that refers to an overloaded function, try to
9211 /// resolve that overloaded function expression down to a single function.
9212 ///
9213 /// This routine can only resolve template-ids that refer to a single function
9214 /// template, where that template-id refers to a single template whose template
9215 /// arguments are either provided by the template-id or have defaults,
9216 /// as described in C++0x [temp.arg.explicit]p3.
9217 FunctionDecl *
9218 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9219                                                   bool Complain,
9220                                                   DeclAccessPair *FoundResult) {
9221   // C++ [over.over]p1:
9222   //   [...] [Note: any redundant set of parentheses surrounding the
9223   //   overloaded function name is ignored (5.1). ]
9224   // C++ [over.over]p1:
9225   //   [...] The overloaded function name can be preceded by the &
9226   //   operator.
9227 
9228   // If we didn't actually find any template-ids, we're done.
9229   if (!ovl->hasExplicitTemplateArgs())
9230     return 0;
9231 
9232   TemplateArgumentListInfo ExplicitTemplateArgs;
9233   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9234 
9235   // Look through all of the overloaded functions, searching for one
9236   // whose type matches exactly.
9237   FunctionDecl *Matched = 0;
9238   for (UnresolvedSetIterator I = ovl->decls_begin(),
9239          E = ovl->decls_end(); I != E; ++I) {
9240     // C++0x [temp.arg.explicit]p3:
9241     //   [...] In contexts where deduction is done and fails, or in contexts
9242     //   where deduction is not done, if a template argument list is
9243     //   specified and it, along with any default template arguments,
9244     //   identifies a single function template specialization, then the
9245     //   template-id is an lvalue for the function template specialization.
9246     FunctionTemplateDecl *FunctionTemplate
9247       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9248 
9249     // C++ [over.over]p2:
9250     //   If the name is a function template, template argument deduction is
9251     //   done (14.8.2.2), and if the argument deduction succeeds, the
9252     //   resulting template argument list is used to generate a single
9253     //   function template specialization, which is added to the set of
9254     //   overloaded functions considered.
9255     FunctionDecl *Specialization = 0;
9256     TemplateDeductionInfo Info(Context, ovl->getNameLoc());
9257     if (TemplateDeductionResult Result
9258           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9259                                     Specialization, Info)) {
9260       // FIXME: make a note of the failed deduction for diagnostics.
9261       (void)Result;
9262       continue;
9263     }
9264 
9265     assert(Specialization && "no specialization and no error?");
9266 
9267     // Multiple matches; we can't resolve to a single declaration.
9268     if (Matched) {
9269       if (Complain) {
9270         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9271           << ovl->getName();
9272         NoteAllOverloadCandidates(ovl);
9273       }
9274       return 0;
9275     }
9276 
9277     Matched = Specialization;
9278     if (FoundResult) *FoundResult = I.getPair();
9279   }
9280 
9281   return Matched;
9282 }
9283 
9284 
9285 
9286 
9287 // Resolve and fix an overloaded expression that can be resolved
9288 // because it identifies a single function template specialization.
9289 //
9290 // Last three arguments should only be supplied if Complain = true
9291 //
9292 // Return true if it was logically possible to so resolve the
9293 // expression, regardless of whether or not it succeeded.  Always
9294 // returns true if 'complain' is set.
9295 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9296                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
9297                    bool complain, const SourceRange& OpRangeForComplaining,
9298                                            QualType DestTypeForComplaining,
9299                                             unsigned DiagIDForComplaining) {
9300   assert(SrcExpr.get()->getType() == Context.OverloadTy);
9301 
9302   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9303 
9304   DeclAccessPair found;
9305   ExprResult SingleFunctionExpression;
9306   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9307                            ovl.Expression, /*complain*/ false, &found)) {
9308     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9309       SrcExpr = ExprError();
9310       return true;
9311     }
9312 
9313     // It is only correct to resolve to an instance method if we're
9314     // resolving a form that's permitted to be a pointer to member.
9315     // Otherwise we'll end up making a bound member expression, which
9316     // is illegal in all the contexts we resolve like this.
9317     if (!ovl.HasFormOfMemberPointer &&
9318         isa<CXXMethodDecl>(fn) &&
9319         cast<CXXMethodDecl>(fn)->isInstance()) {
9320       if (!complain) return false;
9321 
9322       Diag(ovl.Expression->getExprLoc(),
9323            diag::err_bound_member_function)
9324         << 0 << ovl.Expression->getSourceRange();
9325 
9326       // TODO: I believe we only end up here if there's a mix of
9327       // static and non-static candidates (otherwise the expression
9328       // would have 'bound member' type, not 'overload' type).
9329       // Ideally we would note which candidate was chosen and why
9330       // the static candidates were rejected.
9331       SrcExpr = ExprError();
9332       return true;
9333     }
9334 
9335     // Fix the expression to refer to 'fn'.
9336     SingleFunctionExpression =
9337       Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9338 
9339     // If desired, do function-to-pointer decay.
9340     if (doFunctionPointerConverion) {
9341       SingleFunctionExpression =
9342         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9343       if (SingleFunctionExpression.isInvalid()) {
9344         SrcExpr = ExprError();
9345         return true;
9346       }
9347     }
9348   }
9349 
9350   if (!SingleFunctionExpression.isUsable()) {
9351     if (complain) {
9352       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9353         << ovl.Expression->getName()
9354         << DestTypeForComplaining
9355         << OpRangeForComplaining
9356         << ovl.Expression->getQualifierLoc().getSourceRange();
9357       NoteAllOverloadCandidates(SrcExpr.get());
9358 
9359       SrcExpr = ExprError();
9360       return true;
9361     }
9362 
9363     return false;
9364   }
9365 
9366   SrcExpr = SingleFunctionExpression;
9367   return true;
9368 }
9369 
9370 /// \brief Add a single candidate to the overload set.
9371 static void AddOverloadedCallCandidate(Sema &S,
9372                                        DeclAccessPair FoundDecl,
9373                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9374                                        llvm::ArrayRef<Expr *> Args,
9375                                        OverloadCandidateSet &CandidateSet,
9376                                        bool PartialOverloading,
9377                                        bool KnownValid) {
9378   NamedDecl *Callee = FoundDecl.getDecl();
9379   if (isa<UsingShadowDecl>(Callee))
9380     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9381 
9382   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9383     if (ExplicitTemplateArgs) {
9384       assert(!KnownValid && "Explicit template arguments?");
9385       return;
9386     }
9387     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9388                            PartialOverloading);
9389     return;
9390   }
9391 
9392   if (FunctionTemplateDecl *FuncTemplate
9393       = dyn_cast<FunctionTemplateDecl>(Callee)) {
9394     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9395                                    ExplicitTemplateArgs, Args, CandidateSet);
9396     return;
9397   }
9398 
9399   assert(!KnownValid && "unhandled case in overloaded call candidate");
9400 }
9401 
9402 /// \brief Add the overload candidates named by callee and/or found by argument
9403 /// dependent lookup to the given overload set.
9404 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9405                                        llvm::ArrayRef<Expr *> Args,
9406                                        OverloadCandidateSet &CandidateSet,
9407                                        bool PartialOverloading) {
9408 
9409 #ifndef NDEBUG
9410   // Verify that ArgumentDependentLookup is consistent with the rules
9411   // in C++0x [basic.lookup.argdep]p3:
9412   //
9413   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9414   //   and let Y be the lookup set produced by argument dependent
9415   //   lookup (defined as follows). If X contains
9416   //
9417   //     -- a declaration of a class member, or
9418   //
9419   //     -- a block-scope function declaration that is not a
9420   //        using-declaration, or
9421   //
9422   //     -- a declaration that is neither a function or a function
9423   //        template
9424   //
9425   //   then Y is empty.
9426 
9427   if (ULE->requiresADL()) {
9428     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9429            E = ULE->decls_end(); I != E; ++I) {
9430       assert(!(*I)->getDeclContext()->isRecord());
9431       assert(isa<UsingShadowDecl>(*I) ||
9432              !(*I)->getDeclContext()->isFunctionOrMethod());
9433       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9434     }
9435   }
9436 #endif
9437 
9438   // It would be nice to avoid this copy.
9439   TemplateArgumentListInfo TABuffer;
9440   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9441   if (ULE->hasExplicitTemplateArgs()) {
9442     ULE->copyTemplateArgumentsInto(TABuffer);
9443     ExplicitTemplateArgs = &TABuffer;
9444   }
9445 
9446   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9447          E = ULE->decls_end(); I != E; ++I)
9448     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9449                                CandidateSet, PartialOverloading,
9450                                /*KnownValid*/ true);
9451 
9452   if (ULE->requiresADL())
9453     AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9454                                          ULE->getExprLoc(),
9455                                          Args, ExplicitTemplateArgs,
9456                                          CandidateSet, PartialOverloading,
9457                                          ULE->isStdAssociatedNamespace());
9458 }
9459 
9460 /// Attempt to recover from an ill-formed use of a non-dependent name in a
9461 /// template, where the non-dependent name was declared after the template
9462 /// was defined. This is common in code written for a compilers which do not
9463 /// correctly implement two-stage name lookup.
9464 ///
9465 /// Returns true if a viable candidate was found and a diagnostic was issued.
9466 static bool
9467 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9468                        const CXXScopeSpec &SS, LookupResult &R,
9469                        TemplateArgumentListInfo *ExplicitTemplateArgs,
9470                        llvm::ArrayRef<Expr *> Args) {
9471   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9472     return false;
9473 
9474   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9475     if (DC->isTransparentContext())
9476       continue;
9477 
9478     SemaRef.LookupQualifiedName(R, DC);
9479 
9480     if (!R.empty()) {
9481       R.suppressDiagnostics();
9482 
9483       if (isa<CXXRecordDecl>(DC)) {
9484         // Don't diagnose names we find in classes; we get much better
9485         // diagnostics for these from DiagnoseEmptyLookup.
9486         R.clear();
9487         return false;
9488       }
9489 
9490       OverloadCandidateSet Candidates(FnLoc);
9491       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9492         AddOverloadedCallCandidate(SemaRef, I.getPair(),
9493                                    ExplicitTemplateArgs, Args,
9494                                    Candidates, false, /*KnownValid*/ false);
9495 
9496       OverloadCandidateSet::iterator Best;
9497       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9498         // No viable functions. Don't bother the user with notes for functions
9499         // which don't work and shouldn't be found anyway.
9500         R.clear();
9501         return false;
9502       }
9503 
9504       // Find the namespaces where ADL would have looked, and suggest
9505       // declaring the function there instead.
9506       Sema::AssociatedNamespaceSet AssociatedNamespaces;
9507       Sema::AssociatedClassSet AssociatedClasses;
9508       SemaRef.FindAssociatedClassesAndNamespaces(Args,
9509                                                  AssociatedNamespaces,
9510                                                  AssociatedClasses);
9511       // Never suggest declaring a function within namespace 'std'.
9512       Sema::AssociatedNamespaceSet SuggestedNamespaces;
9513       if (DeclContext *Std = SemaRef.getStdNamespace()) {
9514         for (Sema::AssociatedNamespaceSet::iterator
9515                it = AssociatedNamespaces.begin(),
9516                end = AssociatedNamespaces.end(); it != end; ++it) {
9517           if (!Std->Encloses(*it))
9518             SuggestedNamespaces.insert(*it);
9519         }
9520       } else {
9521         // Lacking the 'std::' namespace, use all of the associated namespaces.
9522         SuggestedNamespaces = AssociatedNamespaces;
9523       }
9524 
9525       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9526         << R.getLookupName();
9527       if (SuggestedNamespaces.empty()) {
9528         SemaRef.Diag(Best->Function->getLocation(),
9529                      diag::note_not_found_by_two_phase_lookup)
9530           << R.getLookupName() << 0;
9531       } else if (SuggestedNamespaces.size() == 1) {
9532         SemaRef.Diag(Best->Function->getLocation(),
9533                      diag::note_not_found_by_two_phase_lookup)
9534           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9535       } else {
9536         // FIXME: It would be useful to list the associated namespaces here,
9537         // but the diagnostics infrastructure doesn't provide a way to produce
9538         // a localized representation of a list of items.
9539         SemaRef.Diag(Best->Function->getLocation(),
9540                      diag::note_not_found_by_two_phase_lookup)
9541           << R.getLookupName() << 2;
9542       }
9543 
9544       // Try to recover by calling this function.
9545       return true;
9546     }
9547 
9548     R.clear();
9549   }
9550 
9551   return false;
9552 }
9553 
9554 /// Attempt to recover from ill-formed use of a non-dependent operator in a
9555 /// template, where the non-dependent operator was declared after the template
9556 /// was defined.
9557 ///
9558 /// Returns true if a viable candidate was found and a diagnostic was issued.
9559 static bool
9560 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9561                                SourceLocation OpLoc,
9562                                llvm::ArrayRef<Expr *> Args) {
9563   DeclarationName OpName =
9564     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9565   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9566   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9567                                 /*ExplicitTemplateArgs=*/0, Args);
9568 }
9569 
9570 namespace {
9571 // Callback to limit the allowed keywords and to only accept typo corrections
9572 // that are keywords or whose decls refer to functions (or template functions)
9573 // that accept the given number of arguments.
9574 class RecoveryCallCCC : public CorrectionCandidateCallback {
9575  public:
9576   RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9577       : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9578     WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9579     WantRemainingKeywords = false;
9580   }
9581 
9582   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9583     if (!candidate.getCorrectionDecl())
9584       return candidate.isKeyword();
9585 
9586     for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9587            DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9588       FunctionDecl *FD = 0;
9589       NamedDecl *ND = (*DI)->getUnderlyingDecl();
9590       if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9591         FD = FTD->getTemplatedDecl();
9592       if (!HasExplicitTemplateArgs && !FD) {
9593         if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9594           // If the Decl is neither a function nor a template function,
9595           // determine if it is a pointer or reference to a function. If so,
9596           // check against the number of arguments expected for the pointee.
9597           QualType ValType = cast<ValueDecl>(ND)->getType();
9598           if (ValType->isAnyPointerType() || ValType->isReferenceType())
9599             ValType = ValType->getPointeeType();
9600           if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9601             if (FPT->getNumArgs() == NumArgs)
9602               return true;
9603         }
9604       }
9605       if (FD && FD->getNumParams() >= NumArgs &&
9606           FD->getMinRequiredArguments() <= NumArgs)
9607         return true;
9608     }
9609     return false;
9610   }
9611 
9612  private:
9613   unsigned NumArgs;
9614   bool HasExplicitTemplateArgs;
9615 };
9616 
9617 // Callback that effectively disabled typo correction
9618 class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9619  public:
9620   NoTypoCorrectionCCC() {
9621     WantTypeSpecifiers = false;
9622     WantExpressionKeywords = false;
9623     WantCXXNamedCasts = false;
9624     WantRemainingKeywords = false;
9625   }
9626 
9627   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9628     return false;
9629   }
9630 };
9631 }
9632 
9633 /// Attempts to recover from a call where no functions were found.
9634 ///
9635 /// Returns true if new candidates were found.
9636 static ExprResult
9637 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9638                       UnresolvedLookupExpr *ULE,
9639                       SourceLocation LParenLoc,
9640                       llvm::MutableArrayRef<Expr *> Args,
9641                       SourceLocation RParenLoc,
9642                       bool EmptyLookup, bool AllowTypoCorrection) {
9643 
9644   CXXScopeSpec SS;
9645   SS.Adopt(ULE->getQualifierLoc());
9646   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9647 
9648   TemplateArgumentListInfo TABuffer;
9649   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9650   if (ULE->hasExplicitTemplateArgs()) {
9651     ULE->copyTemplateArgumentsInto(TABuffer);
9652     ExplicitTemplateArgs = &TABuffer;
9653   }
9654 
9655   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9656                  Sema::LookupOrdinaryName);
9657   RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9658   NoTypoCorrectionCCC RejectAll;
9659   CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9660       (CorrectionCandidateCallback*)&Validator :
9661       (CorrectionCandidateCallback*)&RejectAll;
9662   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9663                               ExplicitTemplateArgs, Args) &&
9664       (!EmptyLookup ||
9665        SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9666                                    ExplicitTemplateArgs, Args)))
9667     return ExprError();
9668 
9669   assert(!R.empty() && "lookup results empty despite recovery");
9670 
9671   // Build an implicit member call if appropriate.  Just drop the
9672   // casts and such from the call, we don't really care.
9673   ExprResult NewFn = ExprError();
9674   if ((*R.begin())->isCXXClassMember())
9675     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9676                                                     R, ExplicitTemplateArgs);
9677   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9678     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9679                                         ExplicitTemplateArgs);
9680   else
9681     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9682 
9683   if (NewFn.isInvalid())
9684     return ExprError();
9685 
9686   // This shouldn't cause an infinite loop because we're giving it
9687   // an expression with viable lookup results, which should never
9688   // end up here.
9689   return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9690                                MultiExprArg(Args.data(), Args.size()),
9691                                RParenLoc);
9692 }
9693 
9694 /// ResolveOverloadedCallFn - Given the call expression that calls Fn
9695 /// (which eventually refers to the declaration Func) and the call
9696 /// arguments Args/NumArgs, attempt to resolve the function call down
9697 /// to a specific function. If overload resolution succeeds, returns
9698 /// the function declaration produced by overload
9699 /// resolution. Otherwise, emits diagnostics, deletes all of the
9700 /// arguments and Fn, and returns NULL.
9701 ExprResult
9702 Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
9703                               SourceLocation LParenLoc,
9704                               Expr **Args, unsigned NumArgs,
9705                               SourceLocation RParenLoc,
9706                               Expr *ExecConfig,
9707                               bool AllowTypoCorrection) {
9708 #ifndef NDEBUG
9709   if (ULE->requiresADL()) {
9710     // To do ADL, we must have found an unqualified name.
9711     assert(!ULE->getQualifier() && "qualified name with ADL");
9712 
9713     // We don't perform ADL for implicit declarations of builtins.
9714     // Verify that this was correctly set up.
9715     FunctionDecl *F;
9716     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9717         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9718         F->getBuiltinID() && F->isImplicit())
9719       llvm_unreachable("performing ADL for builtin");
9720 
9721     // We don't perform ADL in C.
9722     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9723   } else
9724     assert(!ULE->isStdAssociatedNamespace() &&
9725            "std is associated namespace but not doing ADL");
9726 #endif
9727 
9728   UnbridgedCastsSet UnbridgedCasts;
9729   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9730     return ExprError();
9731 
9732   OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9733 
9734   // Add the functions denoted by the callee to the set of candidate
9735   // functions, including those from argument-dependent lookup.
9736   AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9737                               CandidateSet);
9738 
9739   // If we found nothing, try to recover.
9740   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9741   // out if it fails.
9742   if (CandidateSet.empty()) {
9743     // In Microsoft mode, if we are inside a template class member function then
9744     // create a type dependent CallExpr. The goal is to postpone name lookup
9745     // to instantiation time to be able to search into type dependent base
9746     // classes.
9747     if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9748         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9749       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9750                                           Context.DependentTy, VK_RValue,
9751                                           RParenLoc);
9752       CE->setTypeDependent(true);
9753       return Owned(CE);
9754     }
9755     return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9756                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9757                                  RParenLoc, /*EmptyLookup=*/true,
9758                                  AllowTypoCorrection);
9759   }
9760 
9761   UnbridgedCasts.restore();
9762 
9763   OverloadCandidateSet::iterator Best;
9764   switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
9765   case OR_Success: {
9766     FunctionDecl *FDecl = Best->Function;
9767     MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9768     CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
9769     DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9770     Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9771     return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9772                                  ExecConfig);
9773   }
9774 
9775   case OR_No_Viable_Function: {
9776     // Try to recover by looking for viable functions which the user might
9777     // have meant to call.
9778     ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9779                                   llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9780                                                 RParenLoc,
9781                                                 /*EmptyLookup=*/false,
9782                                                 AllowTypoCorrection);
9783     if (!Recovery.isInvalid())
9784       return Recovery;
9785 
9786     Diag(Fn->getLocStart(),
9787          diag::err_ovl_no_viable_function_in_call)
9788       << ULE->getName() << Fn->getSourceRange();
9789     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9790                                 llvm::makeArrayRef(Args, NumArgs));
9791     break;
9792   }
9793 
9794   case OR_Ambiguous:
9795     Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
9796       << ULE->getName() << Fn->getSourceRange();
9797     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9798                                 llvm::makeArrayRef(Args, NumArgs));
9799     break;
9800 
9801   case OR_Deleted:
9802     {
9803       Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9804         << Best->Function->isDeleted()
9805         << ULE->getName()
9806         << getDeletedOrUnavailableSuffix(Best->Function)
9807         << Fn->getSourceRange();
9808       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9809                                   llvm::makeArrayRef(Args, NumArgs));
9810 
9811       // We emitted an error for the unvailable/deleted function call but keep
9812       // the call in the AST.
9813       FunctionDecl *FDecl = Best->Function;
9814       Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9815       return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9816                                    RParenLoc, ExecConfig);
9817     }
9818   }
9819 
9820   // Overload resolution failed.
9821   return ExprError();
9822 }
9823 
9824 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
9825   return Functions.size() > 1 ||
9826     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9827 }
9828 
9829 /// \brief Create a unary operation that may resolve to an overloaded
9830 /// operator.
9831 ///
9832 /// \param OpLoc The location of the operator itself (e.g., '*').
9833 ///
9834 /// \param OpcIn The UnaryOperator::Opcode that describes this
9835 /// operator.
9836 ///
9837 /// \param Fns The set of non-member functions that will be
9838 /// considered by overload resolution. The caller needs to build this
9839 /// set based on the context using, e.g.,
9840 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9841 /// set should not contain any member functions; those will be added
9842 /// by CreateOverloadedUnaryOp().
9843 ///
9844 /// \param Input The input argument.
9845 ExprResult
9846 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9847                               const UnresolvedSetImpl &Fns,
9848                               Expr *Input) {
9849   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
9850 
9851   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9852   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9853   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9854   // TODO: provide better source location info.
9855   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
9856 
9857   if (checkPlaceholderForOverload(*this, Input))
9858     return ExprError();
9859 
9860   Expr *Args[2] = { Input, 0 };
9861   unsigned NumArgs = 1;
9862 
9863   // For post-increment and post-decrement, add the implicit '0' as
9864   // the second argument, so that we know this is a post-increment or
9865   // post-decrement.
9866   if (Opc == UO_PostInc || Opc == UO_PostDec) {
9867     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
9868     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9869                                      SourceLocation());
9870     NumArgs = 2;
9871   }
9872 
9873   if (Input->isTypeDependent()) {
9874     if (Fns.empty())
9875       return Owned(new (Context) UnaryOperator(Input,
9876                                                Opc,
9877                                                Context.DependentTy,
9878                                                VK_RValue, OK_Ordinary,
9879                                                OpLoc));
9880 
9881     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9882     UnresolvedLookupExpr *Fn
9883       = UnresolvedLookupExpr::Create(Context, NamingClass,
9884                                      NestedNameSpecifierLoc(), OpNameInfo,
9885                                      /*ADL*/ true, IsOverloaded(Fns),
9886                                      Fns.begin(), Fns.end());
9887     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
9888                                                   &Args[0], NumArgs,
9889                                                    Context.DependentTy,
9890                                                    VK_RValue,
9891                                                    OpLoc));
9892   }
9893 
9894   // Build an empty overload set.
9895   OverloadCandidateSet CandidateSet(OpLoc);
9896 
9897   // Add the candidates from the given function set.
9898   AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9899                         false);
9900 
9901   // Add operator candidates that are member functions.
9902   AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9903 
9904   // Add candidates from ADL.
9905   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9906                                        OpLoc, llvm::makeArrayRef(Args, NumArgs),
9907                                        /*ExplicitTemplateArgs*/ 0,
9908                                        CandidateSet);
9909 
9910   // Add builtin operator candidates.
9911   AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9912 
9913   bool HadMultipleCandidates = (CandidateSet.size() > 1);
9914 
9915   // Perform overload resolution.
9916   OverloadCandidateSet::iterator Best;
9917   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
9918   case OR_Success: {
9919     // We found a built-in operator or an overloaded operator.
9920     FunctionDecl *FnDecl = Best->Function;
9921 
9922     if (FnDecl) {
9923       // We matched an overloaded operator. Build a call to that
9924       // operator.
9925 
9926       MarkFunctionReferenced(OpLoc, FnDecl);
9927 
9928       // Convert the arguments.
9929       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
9930         CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
9931 
9932         ExprResult InputRes =
9933           PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9934                                               Best->FoundDecl, Method);
9935         if (InputRes.isInvalid())
9936           return ExprError();
9937         Input = InputRes.take();
9938       } else {
9939         // Convert the arguments.
9940         ExprResult InputInit
9941           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
9942                                                       Context,
9943                                                       FnDecl->getParamDecl(0)),
9944                                       SourceLocation(),
9945                                       Input);
9946         if (InputInit.isInvalid())
9947           return ExprError();
9948         Input = InputInit.take();
9949       }
9950 
9951       DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9952 
9953       // Determine the result type.
9954       QualType ResultTy = FnDecl->getResultType();
9955       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9956       ResultTy = ResultTy.getNonLValueExprType(Context);
9957 
9958       // Build the actual expression node.
9959       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9960                                                 HadMultipleCandidates, OpLoc);
9961       if (FnExpr.isInvalid())
9962         return ExprError();
9963 
9964       Args[0] = Input;
9965       CallExpr *TheCall =
9966         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
9967                                           Args, NumArgs, ResultTy, VK, OpLoc);
9968 
9969       if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
9970                               FnDecl))
9971         return ExprError();
9972 
9973       return MaybeBindToTemporary(TheCall);
9974     } else {
9975       // We matched a built-in operator. Convert the arguments, then
9976       // break out so that we will build the appropriate built-in
9977       // operator node.
9978       ExprResult InputRes =
9979         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9980                                   Best->Conversions[0], AA_Passing);
9981       if (InputRes.isInvalid())
9982         return ExprError();
9983       Input = InputRes.take();
9984       break;
9985     }
9986   }
9987 
9988   case OR_No_Viable_Function:
9989     // This is an erroneous use of an operator which can be overloaded by
9990     // a non-member function. Check for non-member operators which were
9991     // defined too late to be candidates.
9992     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9993                                        llvm::makeArrayRef(Args, NumArgs)))
9994       // FIXME: Recover by calling the found function.
9995       return ExprError();
9996 
9997     // No viable function; fall through to handling this as a
9998     // built-in operator, which will produce an error message for us.
9999     break;
10000 
10001   case OR_Ambiguous:
10002     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10003         << UnaryOperator::getOpcodeStr(Opc)
10004         << Input->getType()
10005         << Input->getSourceRange();
10006     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10007                                 llvm::makeArrayRef(Args, NumArgs),
10008                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10009     return ExprError();
10010 
10011   case OR_Deleted:
10012     Diag(OpLoc, diag::err_ovl_deleted_oper)
10013       << Best->Function->isDeleted()
10014       << UnaryOperator::getOpcodeStr(Opc)
10015       << getDeletedOrUnavailableSuffix(Best->Function)
10016       << Input->getSourceRange();
10017     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10018                                 llvm::makeArrayRef(Args, NumArgs),
10019                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10020     return ExprError();
10021   }
10022 
10023   // Either we found no viable overloaded operator or we matched a
10024   // built-in operator. In either case, fall through to trying to
10025   // build a built-in operation.
10026   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10027 }
10028 
10029 /// \brief Create a binary operation that may resolve to an overloaded
10030 /// operator.
10031 ///
10032 /// \param OpLoc The location of the operator itself (e.g., '+').
10033 ///
10034 /// \param OpcIn The BinaryOperator::Opcode that describes this
10035 /// operator.
10036 ///
10037 /// \param Fns The set of non-member functions that will be
10038 /// considered by overload resolution. The caller needs to build this
10039 /// set based on the context using, e.g.,
10040 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10041 /// set should not contain any member functions; those will be added
10042 /// by CreateOverloadedBinOp().
10043 ///
10044 /// \param LHS Left-hand argument.
10045 /// \param RHS Right-hand argument.
10046 ExprResult
10047 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10048                             unsigned OpcIn,
10049                             const UnresolvedSetImpl &Fns,
10050                             Expr *LHS, Expr *RHS) {
10051   Expr *Args[2] = { LHS, RHS };
10052   LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10053 
10054   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10055   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10056   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10057 
10058   // If either side is type-dependent, create an appropriate dependent
10059   // expression.
10060   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10061     if (Fns.empty()) {
10062       // If there are no functions to store, just build a dependent
10063       // BinaryOperator or CompoundAssignment.
10064       if (Opc <= BO_Assign || Opc > BO_OrAssign)
10065         return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10066                                                   Context.DependentTy,
10067                                                   VK_RValue, OK_Ordinary,
10068                                                   OpLoc));
10069 
10070       return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10071                                                         Context.DependentTy,
10072                                                         VK_LValue,
10073                                                         OK_Ordinary,
10074                                                         Context.DependentTy,
10075                                                         Context.DependentTy,
10076                                                         OpLoc));
10077     }
10078 
10079     // FIXME: save results of ADL from here?
10080     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10081     // TODO: provide better source location info in DNLoc component.
10082     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10083     UnresolvedLookupExpr *Fn
10084       = UnresolvedLookupExpr::Create(Context, NamingClass,
10085                                      NestedNameSpecifierLoc(), OpNameInfo,
10086                                      /*ADL*/ true, IsOverloaded(Fns),
10087                                      Fns.begin(), Fns.end());
10088     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
10089                                                    Args, 2,
10090                                                    Context.DependentTy,
10091                                                    VK_RValue,
10092                                                    OpLoc));
10093   }
10094 
10095   // Always do placeholder-like conversions on the RHS.
10096   if (checkPlaceholderForOverload(*this, Args[1]))
10097     return ExprError();
10098 
10099   // Do placeholder-like conversion on the LHS; note that we should
10100   // not get here with a PseudoObject LHS.
10101   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10102   if (checkPlaceholderForOverload(*this, Args[0]))
10103     return ExprError();
10104 
10105   // If this is the assignment operator, we only perform overload resolution
10106   // if the left-hand side is a class or enumeration type. This is actually
10107   // a hack. The standard requires that we do overload resolution between the
10108   // various built-in candidates, but as DR507 points out, this can lead to
10109   // problems. So we do it this way, which pretty much follows what GCC does.
10110   // Note that we go the traditional code path for compound assignment forms.
10111   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10112     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10113 
10114   // If this is the .* operator, which is not overloadable, just
10115   // create a built-in binary operator.
10116   if (Opc == BO_PtrMemD)
10117     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10118 
10119   // Build an empty overload set.
10120   OverloadCandidateSet CandidateSet(OpLoc);
10121 
10122   // Add the candidates from the given function set.
10123   AddFunctionCandidates(Fns, Args, CandidateSet, false);
10124 
10125   // Add operator candidates that are member functions.
10126   AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10127 
10128   // Add candidates from ADL.
10129   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10130                                        OpLoc, Args,
10131                                        /*ExplicitTemplateArgs*/ 0,
10132                                        CandidateSet);
10133 
10134   // Add builtin operator candidates.
10135   AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10136 
10137   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10138 
10139   // Perform overload resolution.
10140   OverloadCandidateSet::iterator Best;
10141   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10142     case OR_Success: {
10143       // We found a built-in operator or an overloaded operator.
10144       FunctionDecl *FnDecl = Best->Function;
10145 
10146       if (FnDecl) {
10147         // We matched an overloaded operator. Build a call to that
10148         // operator.
10149 
10150         MarkFunctionReferenced(OpLoc, FnDecl);
10151 
10152         // Convert the arguments.
10153         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10154           // Best->Access is only meaningful for class members.
10155           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10156 
10157           ExprResult Arg1 =
10158             PerformCopyInitialization(
10159               InitializedEntity::InitializeParameter(Context,
10160                                                      FnDecl->getParamDecl(0)),
10161               SourceLocation(), Owned(Args[1]));
10162           if (Arg1.isInvalid())
10163             return ExprError();
10164 
10165           ExprResult Arg0 =
10166             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10167                                                 Best->FoundDecl, Method);
10168           if (Arg0.isInvalid())
10169             return ExprError();
10170           Args[0] = Arg0.takeAs<Expr>();
10171           Args[1] = RHS = Arg1.takeAs<Expr>();
10172         } else {
10173           // Convert the arguments.
10174           ExprResult Arg0 = PerformCopyInitialization(
10175             InitializedEntity::InitializeParameter(Context,
10176                                                    FnDecl->getParamDecl(0)),
10177             SourceLocation(), Owned(Args[0]));
10178           if (Arg0.isInvalid())
10179             return ExprError();
10180 
10181           ExprResult Arg1 =
10182             PerformCopyInitialization(
10183               InitializedEntity::InitializeParameter(Context,
10184                                                      FnDecl->getParamDecl(1)),
10185               SourceLocation(), Owned(Args[1]));
10186           if (Arg1.isInvalid())
10187             return ExprError();
10188           Args[0] = LHS = Arg0.takeAs<Expr>();
10189           Args[1] = RHS = Arg1.takeAs<Expr>();
10190         }
10191 
10192         DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10193 
10194         // Determine the result type.
10195         QualType ResultTy = FnDecl->getResultType();
10196         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10197         ResultTy = ResultTy.getNonLValueExprType(Context);
10198 
10199         // Build the actual expression node.
10200         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10201                                                   HadMultipleCandidates, OpLoc);
10202         if (FnExpr.isInvalid())
10203           return ExprError();
10204 
10205         CXXOperatorCallExpr *TheCall =
10206           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10207                                             Args, 2, ResultTy, VK, OpLoc);
10208 
10209         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10210                                 FnDecl))
10211           return ExprError();
10212 
10213         return MaybeBindToTemporary(TheCall);
10214       } else {
10215         // We matched a built-in operator. Convert the arguments, then
10216         // break out so that we will build the appropriate built-in
10217         // operator node.
10218         ExprResult ArgsRes0 =
10219           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10220                                     Best->Conversions[0], AA_Passing);
10221         if (ArgsRes0.isInvalid())
10222           return ExprError();
10223         Args[0] = ArgsRes0.take();
10224 
10225         ExprResult ArgsRes1 =
10226           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10227                                     Best->Conversions[1], AA_Passing);
10228         if (ArgsRes1.isInvalid())
10229           return ExprError();
10230         Args[1] = ArgsRes1.take();
10231         break;
10232       }
10233     }
10234 
10235     case OR_No_Viable_Function: {
10236       // C++ [over.match.oper]p9:
10237       //   If the operator is the operator , [...] and there are no
10238       //   viable functions, then the operator is assumed to be the
10239       //   built-in operator and interpreted according to clause 5.
10240       if (Opc == BO_Comma)
10241         break;
10242 
10243       // For class as left operand for assignment or compound assigment
10244       // operator do not fall through to handling in built-in, but report that
10245       // no overloaded assignment operator found
10246       ExprResult Result = ExprError();
10247       if (Args[0]->getType()->isRecordType() &&
10248           Opc >= BO_Assign && Opc <= BO_OrAssign) {
10249         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10250              << BinaryOperator::getOpcodeStr(Opc)
10251              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10252       } else {
10253         // This is an erroneous use of an operator which can be overloaded by
10254         // a non-member function. Check for non-member operators which were
10255         // defined too late to be candidates.
10256         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10257           // FIXME: Recover by calling the found function.
10258           return ExprError();
10259 
10260         // No viable function; try to create a built-in operation, which will
10261         // produce an error. Then, show the non-viable candidates.
10262         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10263       }
10264       assert(Result.isInvalid() &&
10265              "C++ binary operator overloading is missing candidates!");
10266       if (Result.isInvalid())
10267         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10268                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
10269       return move(Result);
10270     }
10271 
10272     case OR_Ambiguous:
10273       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10274           << BinaryOperator::getOpcodeStr(Opc)
10275           << Args[0]->getType() << Args[1]->getType()
10276           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10277       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10278                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10279       return ExprError();
10280 
10281     case OR_Deleted:
10282       if (isImplicitlyDeleted(Best->Function)) {
10283         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10284         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10285           << getSpecialMember(Method)
10286           << BinaryOperator::getOpcodeStr(Opc)
10287           << getDeletedOrUnavailableSuffix(Best->Function);
10288 
10289         if (getSpecialMember(Method) != CXXInvalid) {
10290           // The user probably meant to call this special member. Just
10291           // explain why it's deleted.
10292           NoteDeletedFunction(Method);
10293           return ExprError();
10294         }
10295       } else {
10296         Diag(OpLoc, diag::err_ovl_deleted_oper)
10297           << Best->Function->isDeleted()
10298           << BinaryOperator::getOpcodeStr(Opc)
10299           << getDeletedOrUnavailableSuffix(Best->Function)
10300           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10301       }
10302       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10303                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10304       return ExprError();
10305   }
10306 
10307   // We matched a built-in operator; build it.
10308   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10309 }
10310 
10311 ExprResult
10312 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10313                                          SourceLocation RLoc,
10314                                          Expr *Base, Expr *Idx) {
10315   Expr *Args[2] = { Base, Idx };
10316   DeclarationName OpName =
10317       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10318 
10319   // If either side is type-dependent, create an appropriate dependent
10320   // expression.
10321   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10322 
10323     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10324     // CHECKME: no 'operator' keyword?
10325     DeclarationNameInfo OpNameInfo(OpName, LLoc);
10326     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10327     UnresolvedLookupExpr *Fn
10328       = UnresolvedLookupExpr::Create(Context, NamingClass,
10329                                      NestedNameSpecifierLoc(), OpNameInfo,
10330                                      /*ADL*/ true, /*Overloaded*/ false,
10331                                      UnresolvedSetIterator(),
10332                                      UnresolvedSetIterator());
10333     // Can't add any actual overloads yet
10334 
10335     return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10336                                                    Args, 2,
10337                                                    Context.DependentTy,
10338                                                    VK_RValue,
10339                                                    RLoc));
10340   }
10341 
10342   // Handle placeholders on both operands.
10343   if (checkPlaceholderForOverload(*this, Args[0]))
10344     return ExprError();
10345   if (checkPlaceholderForOverload(*this, Args[1]))
10346     return ExprError();
10347 
10348   // Build an empty overload set.
10349   OverloadCandidateSet CandidateSet(LLoc);
10350 
10351   // Subscript can only be overloaded as a member function.
10352 
10353   // Add operator candidates that are member functions.
10354   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10355 
10356   // Add builtin operator candidates.
10357   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10358 
10359   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10360 
10361   // Perform overload resolution.
10362   OverloadCandidateSet::iterator Best;
10363   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10364     case OR_Success: {
10365       // We found a built-in operator or an overloaded operator.
10366       FunctionDecl *FnDecl = Best->Function;
10367 
10368       if (FnDecl) {
10369         // We matched an overloaded operator. Build a call to that
10370         // operator.
10371 
10372         MarkFunctionReferenced(LLoc, FnDecl);
10373 
10374         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10375         DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
10376 
10377         // Convert the arguments.
10378         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10379         ExprResult Arg0 =
10380           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10381                                               Best->FoundDecl, Method);
10382         if (Arg0.isInvalid())
10383           return ExprError();
10384         Args[0] = Arg0.take();
10385 
10386         // Convert the arguments.
10387         ExprResult InputInit
10388           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10389                                                       Context,
10390                                                       FnDecl->getParamDecl(0)),
10391                                       SourceLocation(),
10392                                       Owned(Args[1]));
10393         if (InputInit.isInvalid())
10394           return ExprError();
10395 
10396         Args[1] = InputInit.takeAs<Expr>();
10397 
10398         // Determine the result type
10399         QualType ResultTy = FnDecl->getResultType();
10400         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10401         ResultTy = ResultTy.getNonLValueExprType(Context);
10402 
10403         // Build the actual expression node.
10404         DeclarationNameInfo OpLocInfo(OpName, LLoc);
10405         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10406         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10407                                                   HadMultipleCandidates,
10408                                                   OpLocInfo.getLoc(),
10409                                                   OpLocInfo.getInfo());
10410         if (FnExpr.isInvalid())
10411           return ExprError();
10412 
10413         CXXOperatorCallExpr *TheCall =
10414           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10415                                             FnExpr.take(), Args, 2,
10416                                             ResultTy, VK, RLoc);
10417 
10418         if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10419                                 FnDecl))
10420           return ExprError();
10421 
10422         return MaybeBindToTemporary(TheCall);
10423       } else {
10424         // We matched a built-in operator. Convert the arguments, then
10425         // break out so that we will build the appropriate built-in
10426         // operator node.
10427         ExprResult ArgsRes0 =
10428           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10429                                     Best->Conversions[0], AA_Passing);
10430         if (ArgsRes0.isInvalid())
10431           return ExprError();
10432         Args[0] = ArgsRes0.take();
10433 
10434         ExprResult ArgsRes1 =
10435           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10436                                     Best->Conversions[1], AA_Passing);
10437         if (ArgsRes1.isInvalid())
10438           return ExprError();
10439         Args[1] = ArgsRes1.take();
10440 
10441         break;
10442       }
10443     }
10444 
10445     case OR_No_Viable_Function: {
10446       if (CandidateSet.empty())
10447         Diag(LLoc, diag::err_ovl_no_oper)
10448           << Args[0]->getType() << /*subscript*/ 0
10449           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10450       else
10451         Diag(LLoc, diag::err_ovl_no_viable_subscript)
10452           << Args[0]->getType()
10453           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10454       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10455                                   "[]", LLoc);
10456       return ExprError();
10457     }
10458 
10459     case OR_Ambiguous:
10460       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10461           << "[]"
10462           << Args[0]->getType() << Args[1]->getType()
10463           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10464       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10465                                   "[]", LLoc);
10466       return ExprError();
10467 
10468     case OR_Deleted:
10469       Diag(LLoc, diag::err_ovl_deleted_oper)
10470         << Best->Function->isDeleted() << "[]"
10471         << getDeletedOrUnavailableSuffix(Best->Function)
10472         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10473       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10474                                   "[]", LLoc);
10475       return ExprError();
10476     }
10477 
10478   // We matched a built-in operator; build it.
10479   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10480 }
10481 
10482 /// BuildCallToMemberFunction - Build a call to a member
10483 /// function. MemExpr is the expression that refers to the member
10484 /// function (and includes the object parameter), Args/NumArgs are the
10485 /// arguments to the function call (not including the object
10486 /// parameter). The caller needs to validate that the member
10487 /// expression refers to a non-static member function or an overloaded
10488 /// member function.
10489 ExprResult
10490 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10491                                 SourceLocation LParenLoc, Expr **Args,
10492                                 unsigned NumArgs, SourceLocation RParenLoc) {
10493   assert(MemExprE->getType() == Context.BoundMemberTy ||
10494          MemExprE->getType() == Context.OverloadTy);
10495 
10496   // Dig out the member expression. This holds both the object
10497   // argument and the member function we're referring to.
10498   Expr *NakedMemExpr = MemExprE->IgnoreParens();
10499 
10500   // Determine whether this is a call to a pointer-to-member function.
10501   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10502     assert(op->getType() == Context.BoundMemberTy);
10503     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10504 
10505     QualType fnType =
10506       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10507 
10508     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10509     QualType resultType = proto->getCallResultType(Context);
10510     ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10511 
10512     // Check that the object type isn't more qualified than the
10513     // member function we're calling.
10514     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10515 
10516     QualType objectType = op->getLHS()->getType();
10517     if (op->getOpcode() == BO_PtrMemI)
10518       objectType = objectType->castAs<PointerType>()->getPointeeType();
10519     Qualifiers objectQuals = objectType.getQualifiers();
10520 
10521     Qualifiers difference = objectQuals - funcQuals;
10522     difference.removeObjCGCAttr();
10523     difference.removeAddressSpace();
10524     if (difference) {
10525       std::string qualsString = difference.getAsString();
10526       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10527         << fnType.getUnqualifiedType()
10528         << qualsString
10529         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10530     }
10531 
10532     CXXMemberCallExpr *call
10533       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10534                                         resultType, valueKind, RParenLoc);
10535 
10536     if (CheckCallReturnType(proto->getResultType(),
10537                             op->getRHS()->getLocStart(),
10538                             call, 0))
10539       return ExprError();
10540 
10541     if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10542       return ExprError();
10543 
10544     return MaybeBindToTemporary(call);
10545   }
10546 
10547   UnbridgedCastsSet UnbridgedCasts;
10548   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10549     return ExprError();
10550 
10551   MemberExpr *MemExpr;
10552   CXXMethodDecl *Method = 0;
10553   DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10554   NestedNameSpecifier *Qualifier = 0;
10555   if (isa<MemberExpr>(NakedMemExpr)) {
10556     MemExpr = cast<MemberExpr>(NakedMemExpr);
10557     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10558     FoundDecl = MemExpr->getFoundDecl();
10559     Qualifier = MemExpr->getQualifier();
10560     UnbridgedCasts.restore();
10561   } else {
10562     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10563     Qualifier = UnresExpr->getQualifier();
10564 
10565     QualType ObjectType = UnresExpr->getBaseType();
10566     Expr::Classification ObjectClassification
10567       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10568                             : UnresExpr->getBase()->Classify(Context);
10569 
10570     // Add overload candidates
10571     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10572 
10573     // FIXME: avoid copy.
10574     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10575     if (UnresExpr->hasExplicitTemplateArgs()) {
10576       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10577       TemplateArgs = &TemplateArgsBuffer;
10578     }
10579 
10580     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10581            E = UnresExpr->decls_end(); I != E; ++I) {
10582 
10583       NamedDecl *Func = *I;
10584       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10585       if (isa<UsingShadowDecl>(Func))
10586         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10587 
10588 
10589       // Microsoft supports direct constructor calls.
10590       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10591         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10592                              llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10593       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10594         // If explicit template arguments were provided, we can't call a
10595         // non-template member function.
10596         if (TemplateArgs)
10597           continue;
10598 
10599         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10600                            ObjectClassification,
10601                            llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10602                            /*SuppressUserConversions=*/false);
10603       } else {
10604         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10605                                    I.getPair(), ActingDC, TemplateArgs,
10606                                    ObjectType,  ObjectClassification,
10607                                    llvm::makeArrayRef(Args, NumArgs),
10608                                    CandidateSet,
10609                                    /*SuppressUsedConversions=*/false);
10610       }
10611     }
10612 
10613     DeclarationName DeclName = UnresExpr->getMemberName();
10614 
10615     UnbridgedCasts.restore();
10616 
10617     OverloadCandidateSet::iterator Best;
10618     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10619                                             Best)) {
10620     case OR_Success:
10621       Method = cast<CXXMethodDecl>(Best->Function);
10622       MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
10623       FoundDecl = Best->FoundDecl;
10624       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10625       DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10626       break;
10627 
10628     case OR_No_Viable_Function:
10629       Diag(UnresExpr->getMemberLoc(),
10630            diag::err_ovl_no_viable_member_function_in_call)
10631         << DeclName << MemExprE->getSourceRange();
10632       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10633                                   llvm::makeArrayRef(Args, NumArgs));
10634       // FIXME: Leaking incoming expressions!
10635       return ExprError();
10636 
10637     case OR_Ambiguous:
10638       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10639         << DeclName << MemExprE->getSourceRange();
10640       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10641                                   llvm::makeArrayRef(Args, NumArgs));
10642       // FIXME: Leaking incoming expressions!
10643       return ExprError();
10644 
10645     case OR_Deleted:
10646       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10647         << Best->Function->isDeleted()
10648         << DeclName
10649         << getDeletedOrUnavailableSuffix(Best->Function)
10650         << MemExprE->getSourceRange();
10651       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10652                                   llvm::makeArrayRef(Args, NumArgs));
10653       // FIXME: Leaking incoming expressions!
10654       return ExprError();
10655     }
10656 
10657     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10658 
10659     // If overload resolution picked a static member, build a
10660     // non-member call based on that function.
10661     if (Method->isStatic()) {
10662       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10663                                    Args, NumArgs, RParenLoc);
10664     }
10665 
10666     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10667   }
10668 
10669   QualType ResultType = Method->getResultType();
10670   ExprValueKind VK = Expr::getValueKindForType(ResultType);
10671   ResultType = ResultType.getNonLValueExprType(Context);
10672 
10673   assert(Method && "Member call to something that isn't a method?");
10674   CXXMemberCallExpr *TheCall =
10675     new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10676                                     ResultType, VK, RParenLoc);
10677 
10678   // Check for a valid return type.
10679   if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10680                           TheCall, Method))
10681     return ExprError();
10682 
10683   // Convert the object argument (for a non-static member function call).
10684   // We only need to do this if there was actually an overload; otherwise
10685   // it was done at lookup.
10686   if (!Method->isStatic()) {
10687     ExprResult ObjectArg =
10688       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10689                                           FoundDecl, Method);
10690     if (ObjectArg.isInvalid())
10691       return ExprError();
10692     MemExpr->setBase(ObjectArg.take());
10693   }
10694 
10695   // Convert the rest of the arguments
10696   const FunctionProtoType *Proto =
10697     Method->getType()->getAs<FunctionProtoType>();
10698   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10699                               RParenLoc))
10700     return ExprError();
10701 
10702   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10703 
10704   if (CheckFunctionCall(Method, TheCall, Proto))
10705     return ExprError();
10706 
10707   if ((isa<CXXConstructorDecl>(CurContext) ||
10708        isa<CXXDestructorDecl>(CurContext)) &&
10709       TheCall->getMethodDecl()->isPure()) {
10710     const CXXMethodDecl *MD = TheCall->getMethodDecl();
10711 
10712     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10713       Diag(MemExpr->getLocStart(),
10714            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10715         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10716         << MD->getParent()->getDeclName();
10717 
10718       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10719     }
10720   }
10721   return MaybeBindToTemporary(TheCall);
10722 }
10723 
10724 /// BuildCallToObjectOfClassType - Build a call to an object of class
10725 /// type (C++ [over.call.object]), which can end up invoking an
10726 /// overloaded function call operator (@c operator()) or performing a
10727 /// user-defined conversion on the object argument.
10728 ExprResult
10729 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10730                                    SourceLocation LParenLoc,
10731                                    Expr **Args, unsigned NumArgs,
10732                                    SourceLocation RParenLoc) {
10733   if (checkPlaceholderForOverload(*this, Obj))
10734     return ExprError();
10735   ExprResult Object = Owned(Obj);
10736 
10737   UnbridgedCastsSet UnbridgedCasts;
10738   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10739     return ExprError();
10740 
10741   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10742   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10743 
10744   // C++ [over.call.object]p1:
10745   //  If the primary-expression E in the function call syntax
10746   //  evaluates to a class object of type "cv T", then the set of
10747   //  candidate functions includes at least the function call
10748   //  operators of T. The function call operators of T are obtained by
10749   //  ordinary lookup of the name operator() in the context of
10750   //  (E).operator().
10751   OverloadCandidateSet CandidateSet(LParenLoc);
10752   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10753 
10754   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10755                           diag::err_incomplete_object_call, Object.get()))
10756     return true;
10757 
10758   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10759   LookupQualifiedName(R, Record->getDecl());
10760   R.suppressDiagnostics();
10761 
10762   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10763        Oper != OperEnd; ++Oper) {
10764     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10765                        Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10766                        /*SuppressUserConversions=*/ false);
10767   }
10768 
10769   // C++ [over.call.object]p2:
10770   //   In addition, for each (non-explicit in C++0x) conversion function
10771   //   declared in T of the form
10772   //
10773   //        operator conversion-type-id () cv-qualifier;
10774   //
10775   //   where cv-qualifier is the same cv-qualification as, or a
10776   //   greater cv-qualification than, cv, and where conversion-type-id
10777   //   denotes the type "pointer to function of (P1,...,Pn) returning
10778   //   R", or the type "reference to pointer to function of
10779   //   (P1,...,Pn) returning R", or the type "reference to function
10780   //   of (P1,...,Pn) returning R", a surrogate call function [...]
10781   //   is also considered as a candidate function. Similarly,
10782   //   surrogate call functions are added to the set of candidate
10783   //   functions for each conversion function declared in an
10784   //   accessible base class provided the function is not hidden
10785   //   within T by another intervening declaration.
10786   const UnresolvedSetImpl *Conversions
10787     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10788   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
10789          E = Conversions->end(); I != E; ++I) {
10790     NamedDecl *D = *I;
10791     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10792     if (isa<UsingShadowDecl>(D))
10793       D = cast<UsingShadowDecl>(D)->getTargetDecl();
10794 
10795     // Skip over templated conversion functions; they aren't
10796     // surrogates.
10797     if (isa<FunctionTemplateDecl>(D))
10798       continue;
10799 
10800     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10801     if (!Conv->isExplicit()) {
10802       // Strip the reference type (if any) and then the pointer type (if
10803       // any) to get down to what might be a function type.
10804       QualType ConvType = Conv->getConversionType().getNonReferenceType();
10805       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10806         ConvType = ConvPtrType->getPointeeType();
10807 
10808       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10809       {
10810         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10811                               Object.get(), llvm::makeArrayRef(Args, NumArgs),
10812                               CandidateSet);
10813       }
10814     }
10815   }
10816 
10817   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10818 
10819   // Perform overload resolution.
10820   OverloadCandidateSet::iterator Best;
10821   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
10822                              Best)) {
10823   case OR_Success:
10824     // Overload resolution succeeded; we'll build the appropriate call
10825     // below.
10826     break;
10827 
10828   case OR_No_Viable_Function:
10829     if (CandidateSet.empty())
10830       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
10831         << Object.get()->getType() << /*call*/ 1
10832         << Object.get()->getSourceRange();
10833     else
10834       Diag(Object.get()->getLocStart(),
10835            diag::err_ovl_no_viable_object_call)
10836         << Object.get()->getType() << Object.get()->getSourceRange();
10837     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10838                                 llvm::makeArrayRef(Args, NumArgs));
10839     break;
10840 
10841   case OR_Ambiguous:
10842     Diag(Object.get()->getLocStart(),
10843          diag::err_ovl_ambiguous_object_call)
10844       << Object.get()->getType() << Object.get()->getSourceRange();
10845     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10846                                 llvm::makeArrayRef(Args, NumArgs));
10847     break;
10848 
10849   case OR_Deleted:
10850     Diag(Object.get()->getLocStart(),
10851          diag::err_ovl_deleted_object_call)
10852       << Best->Function->isDeleted()
10853       << Object.get()->getType()
10854       << getDeletedOrUnavailableSuffix(Best->Function)
10855       << Object.get()->getSourceRange();
10856     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10857                                 llvm::makeArrayRef(Args, NumArgs));
10858     break;
10859   }
10860 
10861   if (Best == CandidateSet.end())
10862     return true;
10863 
10864   UnbridgedCasts.restore();
10865 
10866   if (Best->Function == 0) {
10867     // Since there is no function declaration, this is one of the
10868     // surrogate candidates. Dig out the conversion function.
10869     CXXConversionDecl *Conv
10870       = cast<CXXConversionDecl>(
10871                          Best->Conversions[0].UserDefined.ConversionFunction);
10872 
10873     CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10874     DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10875 
10876     // We selected one of the surrogate functions that converts the
10877     // object parameter to a function pointer. Perform the conversion
10878     // on the object argument, then let ActOnCallExpr finish the job.
10879 
10880     // Create an implicit member expr to refer to the conversion operator.
10881     // and then call it.
10882     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10883                                              Conv, HadMultipleCandidates);
10884     if (Call.isInvalid())
10885       return ExprError();
10886     // Record usage of conversion in an implicit cast.
10887     Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10888                                           CK_UserDefinedConversion,
10889                                           Call.get(), 0, VK_RValue));
10890 
10891     return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
10892                          RParenLoc);
10893   }
10894 
10895   MarkFunctionReferenced(LParenLoc, Best->Function);
10896   CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10897   DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10898 
10899   // We found an overloaded operator(). Build a CXXOperatorCallExpr
10900   // that calls this method, using Object for the implicit object
10901   // parameter and passing along the remaining arguments.
10902   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10903   const FunctionProtoType *Proto =
10904     Method->getType()->getAs<FunctionProtoType>();
10905 
10906   unsigned NumArgsInProto = Proto->getNumArgs();
10907   unsigned NumArgsToCheck = NumArgs;
10908 
10909   // Build the full argument list for the method call (the
10910   // implicit object parameter is placed at the beginning of the
10911   // list).
10912   Expr **MethodArgs;
10913   if (NumArgs < NumArgsInProto) {
10914     NumArgsToCheck = NumArgsInProto;
10915     MethodArgs = new Expr*[NumArgsInProto + 1];
10916   } else {
10917     MethodArgs = new Expr*[NumArgs + 1];
10918   }
10919   MethodArgs[0] = Object.get();
10920   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10921     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
10922 
10923   DeclarationNameInfo OpLocInfo(
10924                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10925   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
10926   ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10927                                            HadMultipleCandidates,
10928                                            OpLocInfo.getLoc(),
10929                                            OpLocInfo.getInfo());
10930   if (NewFn.isInvalid())
10931     return true;
10932 
10933   // Once we've built TheCall, all of the expressions are properly
10934   // owned.
10935   QualType ResultTy = Method->getResultType();
10936   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10937   ResultTy = ResultTy.getNonLValueExprType(Context);
10938 
10939   CXXOperatorCallExpr *TheCall =
10940     new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
10941                                       MethodArgs, NumArgs + 1,
10942                                       ResultTy, VK, RParenLoc);
10943   delete [] MethodArgs;
10944 
10945   if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
10946                           Method))
10947     return true;
10948 
10949   // We may have default arguments. If so, we need to allocate more
10950   // slots in the call for them.
10951   if (NumArgs < NumArgsInProto)
10952     TheCall->setNumArgs(Context, NumArgsInProto + 1);
10953   else if (NumArgs > NumArgsInProto)
10954     NumArgsToCheck = NumArgsInProto;
10955 
10956   bool IsError = false;
10957 
10958   // Initialize the implicit object parameter.
10959   ExprResult ObjRes =
10960     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10961                                         Best->FoundDecl, Method);
10962   if (ObjRes.isInvalid())
10963     IsError = true;
10964   else
10965     Object = move(ObjRes);
10966   TheCall->setArg(0, Object.take());
10967 
10968   // Check the argument types.
10969   for (unsigned i = 0; i != NumArgsToCheck; i++) {
10970     Expr *Arg;
10971     if (i < NumArgs) {
10972       Arg = Args[i];
10973 
10974       // Pass the argument.
10975 
10976       ExprResult InputInit
10977         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10978                                                     Context,
10979                                                     Method->getParamDecl(i)),
10980                                     SourceLocation(), Arg);
10981 
10982       IsError |= InputInit.isInvalid();
10983       Arg = InputInit.takeAs<Expr>();
10984     } else {
10985       ExprResult DefArg
10986         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10987       if (DefArg.isInvalid()) {
10988         IsError = true;
10989         break;
10990       }
10991 
10992       Arg = DefArg.takeAs<Expr>();
10993     }
10994 
10995     TheCall->setArg(i + 1, Arg);
10996   }
10997 
10998   // If this is a variadic call, handle args passed through "...".
10999   if (Proto->isVariadic()) {
11000     // Promote the arguments (C99 6.5.2.2p7).
11001     for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
11002       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11003       IsError |= Arg.isInvalid();
11004       TheCall->setArg(i + 1, Arg.take());
11005     }
11006   }
11007 
11008   if (IsError) return true;
11009 
11010   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11011 
11012   if (CheckFunctionCall(Method, TheCall, Proto))
11013     return true;
11014 
11015   return MaybeBindToTemporary(TheCall);
11016 }
11017 
11018 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11019 ///  (if one exists), where @c Base is an expression of class type and
11020 /// @c Member is the name of the member we're trying to find.
11021 ExprResult
11022 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11023   assert(Base->getType()->isRecordType() &&
11024          "left-hand side must have class type");
11025 
11026   if (checkPlaceholderForOverload(*this, Base))
11027     return ExprError();
11028 
11029   SourceLocation Loc = Base->getExprLoc();
11030 
11031   // C++ [over.ref]p1:
11032   //
11033   //   [...] An expression x->m is interpreted as (x.operator->())->m
11034   //   for a class object x of type T if T::operator->() exists and if
11035   //   the operator is selected as the best match function by the
11036   //   overload resolution mechanism (13.3).
11037   DeclarationName OpName =
11038     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11039   OverloadCandidateSet CandidateSet(Loc);
11040   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11041 
11042   if (RequireCompleteType(Loc, Base->getType(),
11043                           diag::err_typecheck_incomplete_tag, Base))
11044     return ExprError();
11045 
11046   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11047   LookupQualifiedName(R, BaseRecord->getDecl());
11048   R.suppressDiagnostics();
11049 
11050   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11051        Oper != OperEnd; ++Oper) {
11052     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11053                        0, 0, CandidateSet, /*SuppressUserConversions=*/false);
11054   }
11055 
11056   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11057 
11058   // Perform overload resolution.
11059   OverloadCandidateSet::iterator Best;
11060   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11061   case OR_Success:
11062     // Overload resolution succeeded; we'll build the call below.
11063     break;
11064 
11065   case OR_No_Viable_Function:
11066     if (CandidateSet.empty())
11067       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11068         << Base->getType() << Base->getSourceRange();
11069     else
11070       Diag(OpLoc, diag::err_ovl_no_viable_oper)
11071         << "operator->" << Base->getSourceRange();
11072     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11073     return ExprError();
11074 
11075   case OR_Ambiguous:
11076     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11077       << "->" << Base->getType() << Base->getSourceRange();
11078     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11079     return ExprError();
11080 
11081   case OR_Deleted:
11082     Diag(OpLoc,  diag::err_ovl_deleted_oper)
11083       << Best->Function->isDeleted()
11084       << "->"
11085       << getDeletedOrUnavailableSuffix(Best->Function)
11086       << Base->getSourceRange();
11087     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11088     return ExprError();
11089   }
11090 
11091   MarkFunctionReferenced(OpLoc, Best->Function);
11092   CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11093   DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
11094 
11095   // Convert the object parameter.
11096   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11097   ExprResult BaseResult =
11098     PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11099                                         Best->FoundDecl, Method);
11100   if (BaseResult.isInvalid())
11101     return ExprError();
11102   Base = BaseResult.take();
11103 
11104   // Build the operator call.
11105   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
11106                                             HadMultipleCandidates, OpLoc);
11107   if (FnExpr.isInvalid())
11108     return ExprError();
11109 
11110   QualType ResultTy = Method->getResultType();
11111   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11112   ResultTy = ResultTy.getNonLValueExprType(Context);
11113   CXXOperatorCallExpr *TheCall =
11114     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11115                                       &Base, 1, ResultTy, VK, OpLoc);
11116 
11117   if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11118                           Method))
11119           return ExprError();
11120 
11121   return MaybeBindToTemporary(TheCall);
11122 }
11123 
11124 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11125 /// a literal operator described by the provided lookup results.
11126 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11127                                           DeclarationNameInfo &SuffixInfo,
11128                                           ArrayRef<Expr*> Args,
11129                                           SourceLocation LitEndLoc,
11130                                        TemplateArgumentListInfo *TemplateArgs) {
11131   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11132 
11133   OverloadCandidateSet CandidateSet(UDSuffixLoc);
11134   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11135                         TemplateArgs);
11136 
11137   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11138 
11139   // Perform overload resolution. This will usually be trivial, but might need
11140   // to perform substitutions for a literal operator template.
11141   OverloadCandidateSet::iterator Best;
11142   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11143   case OR_Success:
11144   case OR_Deleted:
11145     break;
11146 
11147   case OR_No_Viable_Function:
11148     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11149       << R.getLookupName();
11150     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11151     return ExprError();
11152 
11153   case OR_Ambiguous:
11154     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11155     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11156     return ExprError();
11157   }
11158 
11159   FunctionDecl *FD = Best->Function;
11160   MarkFunctionReferenced(UDSuffixLoc, FD);
11161   DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
11162 
11163   ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11164                                         SuffixInfo.getLoc(),
11165                                         SuffixInfo.getInfo());
11166   if (Fn.isInvalid())
11167     return true;
11168 
11169   // Check the argument types. This should almost always be a no-op, except
11170   // that array-to-pointer decay is applied to string literals.
11171   Expr *ConvArgs[2];
11172   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11173     ExprResult InputInit = PerformCopyInitialization(
11174       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11175       SourceLocation(), Args[ArgIdx]);
11176     if (InputInit.isInvalid())
11177       return true;
11178     ConvArgs[ArgIdx] = InputInit.take();
11179   }
11180 
11181   QualType ResultTy = FD->getResultType();
11182   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11183   ResultTy = ResultTy.getNonLValueExprType(Context);
11184 
11185   UserDefinedLiteral *UDL =
11186     new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11187                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
11188 
11189   if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11190     return ExprError();
11191 
11192   if (CheckFunctionCall(FD, UDL, NULL))
11193     return ExprError();
11194 
11195   return MaybeBindToTemporary(UDL);
11196 }
11197 
11198 /// FixOverloadedFunctionReference - E is an expression that refers to
11199 /// a C++ overloaded function (possibly with some parentheses and
11200 /// perhaps a '&' around it). We have resolved the overloaded function
11201 /// to the function declaration Fn, so patch up the expression E to
11202 /// refer (possibly indirectly) to Fn. Returns the new expr.
11203 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11204                                            FunctionDecl *Fn) {
11205   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11206     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11207                                                    Found, Fn);
11208     if (SubExpr == PE->getSubExpr())
11209       return PE;
11210 
11211     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11212   }
11213 
11214   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11215     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11216                                                    Found, Fn);
11217     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11218                                SubExpr->getType()) &&
11219            "Implicit cast type cannot be determined from overload");
11220     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11221     if (SubExpr == ICE->getSubExpr())
11222       return ICE;
11223 
11224     return ImplicitCastExpr::Create(Context, ICE->getType(),
11225                                     ICE->getCastKind(),
11226                                     SubExpr, 0,
11227                                     ICE->getValueKind());
11228   }
11229 
11230   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11231     assert(UnOp->getOpcode() == UO_AddrOf &&
11232            "Can only take the address of an overloaded function");
11233     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11234       if (Method->isStatic()) {
11235         // Do nothing: static member functions aren't any different
11236         // from non-member functions.
11237       } else {
11238         // Fix the sub expression, which really has to be an
11239         // UnresolvedLookupExpr holding an overloaded member function
11240         // or template.
11241         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11242                                                        Found, Fn);
11243         if (SubExpr == UnOp->getSubExpr())
11244           return UnOp;
11245 
11246         assert(isa<DeclRefExpr>(SubExpr)
11247                && "fixed to something other than a decl ref");
11248         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11249                && "fixed to a member ref with no nested name qualifier");
11250 
11251         // We have taken the address of a pointer to member
11252         // function. Perform the computation here so that we get the
11253         // appropriate pointer to member type.
11254         QualType ClassType
11255           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11256         QualType MemPtrType
11257           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11258 
11259         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11260                                            VK_RValue, OK_Ordinary,
11261                                            UnOp->getOperatorLoc());
11262       }
11263     }
11264     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11265                                                    Found, Fn);
11266     if (SubExpr == UnOp->getSubExpr())
11267       return UnOp;
11268 
11269     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11270                                      Context.getPointerType(SubExpr->getType()),
11271                                        VK_RValue, OK_Ordinary,
11272                                        UnOp->getOperatorLoc());
11273   }
11274 
11275   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11276     // FIXME: avoid copy.
11277     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11278     if (ULE->hasExplicitTemplateArgs()) {
11279       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11280       TemplateArgs = &TemplateArgsBuffer;
11281     }
11282 
11283     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11284                                            ULE->getQualifierLoc(),
11285                                            ULE->getTemplateKeywordLoc(),
11286                                            Fn,
11287                                            /*enclosing*/ false, // FIXME?
11288                                            ULE->getNameLoc(),
11289                                            Fn->getType(),
11290                                            VK_LValue,
11291                                            Found.getDecl(),
11292                                            TemplateArgs);
11293     MarkDeclRefReferenced(DRE);
11294     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11295     return DRE;
11296   }
11297 
11298   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11299     // FIXME: avoid copy.
11300     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11301     if (MemExpr->hasExplicitTemplateArgs()) {
11302       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11303       TemplateArgs = &TemplateArgsBuffer;
11304     }
11305 
11306     Expr *Base;
11307 
11308     // If we're filling in a static method where we used to have an
11309     // implicit member access, rewrite to a simple decl ref.
11310     if (MemExpr->isImplicitAccess()) {
11311       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11312         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11313                                                MemExpr->getQualifierLoc(),
11314                                                MemExpr->getTemplateKeywordLoc(),
11315                                                Fn,
11316                                                /*enclosing*/ false,
11317                                                MemExpr->getMemberLoc(),
11318                                                Fn->getType(),
11319                                                VK_LValue,
11320                                                Found.getDecl(),
11321                                                TemplateArgs);
11322         MarkDeclRefReferenced(DRE);
11323         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11324         return DRE;
11325       } else {
11326         SourceLocation Loc = MemExpr->getMemberLoc();
11327         if (MemExpr->getQualifier())
11328           Loc = MemExpr->getQualifierLoc().getBeginLoc();
11329         CheckCXXThisCapture(Loc);
11330         Base = new (Context) CXXThisExpr(Loc,
11331                                          MemExpr->getBaseType(),
11332                                          /*isImplicit=*/true);
11333       }
11334     } else
11335       Base = MemExpr->getBase();
11336 
11337     ExprValueKind valueKind;
11338     QualType type;
11339     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11340       valueKind = VK_LValue;
11341       type = Fn->getType();
11342     } else {
11343       valueKind = VK_RValue;
11344       type = Context.BoundMemberTy;
11345     }
11346 
11347     MemberExpr *ME = MemberExpr::Create(Context, Base,
11348                                         MemExpr->isArrow(),
11349                                         MemExpr->getQualifierLoc(),
11350                                         MemExpr->getTemplateKeywordLoc(),
11351                                         Fn,
11352                                         Found,
11353                                         MemExpr->getMemberNameInfo(),
11354                                         TemplateArgs,
11355                                         type, valueKind, OK_Ordinary);
11356     ME->setHadMultipleCandidates(true);
11357     return ME;
11358   }
11359 
11360   llvm_unreachable("Invalid reference to overloaded function");
11361 }
11362 
11363 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11364                                                 DeclAccessPair Found,
11365                                                 FunctionDecl *Fn) {
11366   return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11367 }
11368 
11369 } // end namespace clang
11370